Android: Placing, Setting Text & Retrieving checked Radio Button is table/grid view (n x n) format

When I was working with one of my app I was came to a state where I need to use Radio buttons in 2 x 2 format. In Radio group I can set orientation either horizontal or vertical. I got into stuck how to do that. I start googling for the solution. In many solutions they stated using TableRow for each Radio Button rows, so for my case it will be 2 TableRows with 2 radio buttons in each row. I didn’t want to do it with TableRow so I used LinearLayout with 2 Radio Buttons in each LinearLayout, & my parent layout’s orientation was vertical.

Screen Shot 2017-12-04 at 1.03.05 PM
What I wanted

Hmmmm….. that solved my puzzle for placing radio buttons as 2×2. Let test the app then :). When app ran it was simply perfect placing, was happy for the solution. Now comes selecting and getting checked radio button. When I selected a radio button it was selected properly. Then I tried to select another radio button…….. oopsssss now both the radio buttons are showing as checked 😦 That is really heartbreaking 😥

 

So my next challenge is to fix the issue and get the checked radio option. Started googling again and got the solution. Need to modify a bit to fit my problem but the main idea was to use to separate Radio Group with two Radio Buttons each (with horizontal orientation), and put the Groups in a Layout with vertical orientation.

So in the layout.xml file it will look like:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <RadioGroup
        android:id="@+id/radioGrp1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/rBtn1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Option 1" />

        <RadioButton
            android:id="@+id/rBtn2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Option 2" />

    </RadioGroup>

    <RadioGroup
        android:id="@+id/radioGrp2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/rBtn3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Option 3" />

        <RadioButton
            android:id="@+id/rBtn4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Option 4" />

    </RadioGroup>

</LinearLayout>

For setting text for the radio buttons for both groups use the following code in your ?.java file:

rg1 = (RadioGroup) findViewById(R.id.radioGrp1);
rg2 = (RadioGroup) findViewById(R.id.radioGrp2);
rg1.clearCheck(); // clears checked state of any radio button
rg2.clearCheck();// clears checked state of any radio button

rg1.setOnCheckedChangeListener(listenerForRG1);//setting listener to take action for any checked state change
rg2.setOnCheckedChangeListener(listenerForRG2);//setting listener to take action for any checked state change

Here are the listener functions for both the groups:

private RadioGroup.OnCheckedChangeListener listenerForRG1 = new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId != -1) {
            rg2.setOnCheckedChangeListener(null); // remove the listener before clearing so we don't throw that stackoverflow exception
            rg2.clearCheck(); // clear the second radio group
            rg2.setOnCheckedChangeListener(listener2); //reset the listener
        }
    }
};

private RadioGroup.OnCheckedChangeListener listenerForRG2 = new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId != -1) {
            rg1.setOnCheckedChangeListener(null);
            rg1.clearCheck();
            rg1.setOnCheckedChangeListener(listener1);
        }
    }
};

To get the checked radio button:

int chkId1 = rg1.getCheckedRadioButtonId(); //Get checked radio button id from radio group 1 (if any radio button is checked it will return id else will return -1)
int chkId2 = rg2.getCheckedRadioButtonId();//Get checked radio button id from radio group 2 (if any radio button is checked it will return id else will return -1)
int realCheck = chkId1 == -1 ? chkId2 : chkId1;//Get checked radio button id 
RadioButton rb = findViewById(realCheck); //Get the checked radio button
String radioText = rb.getText(); //Get the text of checked radio button

That’s it…. Now you can get the checked value from your radio groups and proceed with your goal 🙂

Hope this will help you.

🙂 Happy Coding 🙂

 

Acknowledgement: I got the solution from the following link and modified little to fit my problem.

https://stackoverflow.com/questions/10425569/radiogroup-with-two-columns-which-have-ten-radiobuttons
Advertisements

{Windows 10} Remove Write Protected from USB Flash Drive

One fine day when I tried to empty my USB Flash Drive, then an error was showing that reads The drive is Write Protected. That’s weird as the flash drive do not have such physical switch. So it must be something to be deal with software. So I started some common practices, that is using some third party tools to resolve my problem. But those disappointed me.

So start start looking for a solution for my problem again ignoring any usage of third party tool, that is using help of Windows Command. After trying a lot of solutions, which also disappointed me, I finally got the one that solved my problem. I am stating the solution step by step below:

  • Open command prompt as ADMIN.

open_cmd_as_admin

  • Type DISKPART and press .
  • Type LIST VOLUME and press .
  • Type SELECT VOLUME #, where # is the volume number (volume number appears in the list from above command) you want to remove the write protect from.
  • Type ATTRIBUTES DISK CLEAR READONLY and press .
  • You will see a message that the write protect is removed.
  • Now type EXIT to exit from DISKPART.
  • Unplug the flash drive.
  • Re-plug the flash drive.

WALLA, You should be able to write on the disk now.

Please note, the above solution solved my problem, but it is not necessary that it also solves yours. At least you can give a try 🙂

Thank you

Add Jenkins Slave Java command to run at startup at Ubuntu 14.04 instance of Amazon EC2

While working with AWS Ubuntu 14.04 instance for setting up my VM for a Jenkins job I got stuck with this simple task – adding the Jenkins slave connection java command to Ubuntu startup service. I looked at different blogs and sites for the solution, even took help from developers, but unfortunately it didn’t work. So I give a break to refresh myself!

After the break (that is next day) I sat with the solutions I got from all the sources. The one I got from my colleague (who is a developer) seems good enough to serve my requirement, but I had a gut feelings that I am missing some simple thing for which it is not working.  Before going there let me start from creating the service file in the machine.

NOTE: You can scroll way down for the solution quickly 🙂

Creating Jenkins Slave script:

1. Login to the VM
2. Switch to root user
ubuntu@ip-***-**-**-**:~$ sudo -s
After switched to root user it should look like this:
root@ip-***-**-**-**:~#
3. Goto init.d directory
root@ip-***-**-**-**:~# cd /etc/init.d
After this command it will look like this:
root@ip-***-**-**-**:/etc/init.d#
4. Now create the file. We named the file as jenkins-slave
root@ip-***-**-**-**:/etc/init.d# nano jenkins-slave
Nano editor was opened and we wrote (pasted) the following in the editor.

#! /bin/sh
### BEGIN INIT INFO
# Provides: jenkins-slave
# Required-Start:
# Required-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Jenkins Slave
# Description: This file starts and stops connection of Jenkins Slave
#
### END INIT INFO
case “$1” in
start)
sudo java -jar slave.jar -jnlpUrl http://&lt; jenkins_url >:< port >/computer/< jenkins node name >/slave-agent.jnlp -jnlpCredentials < username >:< password >
;;
stop)
;;
restart)
sudo java -jar slave.jar -jnlpUrl http://&lt; jenkins_url >:< port >/computer/< jenkins node name >/slave-agent.jnlp -jnlpCredentials < username >:< password >
;;
*)
echo “Usage: jenkins-slave {start|stop|restart}” >&2
exit 3
;;
esac

NOTE: ‘#!’ in the first line tells that it will be run as root user

5. Save the file and returned to terminal mode from editor.
6. After that ran the update-rc.d command to add the script to startup
root@ip-***-**-**-**:/etc/init.d# update-rc.d jenkins-slave defaults
7. After command ran successfully I rebooted the machine.
8. What!!! it didn’t work. I verified it with the Jenkins Node, that was still showing not connected!
9. I Stopped my AWS VM and the Started it again.
10. Urgh….. No luck this time also

So that was our first attempt so run the command as service. We Failed??? May be or may not be 🙂 This failure boosted my motivation to solve the problem. Next day I pinged my colleague again but for a release he was too busy to sit again. So I decided to move on, this time All Alone 🙂 As stated above, this time I sat with the solutions I got from different sources.

Now I decided to check the System Log of the AWS VM for my instance, which was the first TURING point for the solution. For checking the system log I did:

  • Open EC2 Manage Console of AWS
  • Goto Instances page
  • Select my instance
  • From Actions dropdown menu select: Instance Settings > Get System Log
  • Walla…. Got the System Log

When I checked the log I found that it is showing the following error:

Error: Unable to access slave.jar

Hmm… that’s weird. So I figure out that I should download the slave.jar and then run the connection command. So I downloaded it and give proper permission and also updated the connection command to reflect the location of the slave.jar file. Now restarted the VM….. Sigh… No luck again….

Check the system log again and found the same command. There is something fishy going on with the slave.jar permission, so I deleted the slave.jar:

root@ip-***-**-**-**:# rm slave.jar

So I was thinking that whatever it is I need the slave.jar first in order to connect my slave with master.idea

TADAAAA…. Got the idea, why not add a download command for slave.jar before the connection command? So I immediately added the following line:

sudo wget < URL for slave.jar >

Side NOTE: You can get the url simply by:

  1. Goto Jenkins and open Jenkins Node
  2. As slave is not connected it will show some connection commands
  3. In the command for headless slave, you can see that the slave.jar is a hyperlink.
  4. Right click on it and get the url.
  5. You are DONE

So I saved the file and ran the update-rc.d command again. This time it shows that this is already added. Do not worry about the message. I rebooted the system but….. again it didn’t work. This time I felt that if a thermometer would have place over my head that it would surely burst out due to over temperature. I asked myself WHY its not working now? So I moved to /etc/init.d and checked the permission of jenkins-slave

root@ip-***-**-**-**:/etc/init.d# ls -la

The permission is not satisfying… it showed something like –rw-r-x-x–. So I updated the permission

root@ip-***-**-**-**:/etc/init.d# chmod a+w jenkins-slave

Now I re-run the update-rc.d, it was not needed even though. Got the message again telling that it is added already. That’s OK I just wanted to double sure that this is attached to startup service. Now I rebooted the system.

Yahoooooooo…… I worked now. Felt a big relief and one of my project was hanging at the edge just for this simple thing 🙂 I am listing the solution below so that it becomes easy to get it right away:

Solution for adding Jenkins slave connection command to run at startup at Ubuntu 14.04 AWS:

1. Login to the VM
2. Switch to root user
$ sudo -s
3. Goto /etc/init.d
# cd /etc/init.d
4. Create a file for your service (for example using jenkins-slave, you can give any name as you like)
# nano jenkins-slave
5. Enter the following:

#! /bin/sh
### BEGIN INIT INFO
# Provides: jenkins-slave
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Jenkins Slave
# Description: This file starts and stops connection of Jenkins Slave
#
### END INIT INFO
case “$1” in
start)

sudo wget < url_for_slave.jar (please see above for how you can get this link) >
sudo java -jar slave.jar -jnlpUrl http://&lt; jenkins_url >:< port >/computer/< jenkins node name >/slave-agent.jnlp -jnlpCredentials < username >:< password >
;;
stop)
;;
restart)

sudo wget < url_for_slave.jar (please see above for how you can get this link) >
sudo java -jar slave.jar -jnlpUrl http://&lt; jenkins_url >:< port >/computer/< jenkins node name >/slave-agent.jnlp -jnlpCredentials < username >:< password >
;;
*)
echo “Usage: jenkins-slave {start|stop|restart}” >&2
exit 3
;;
esac

6. Save and close file
7. Change the permission of jenkins-slave
# chmod a+x jenkins-slave
8. Run command
# update-rc.d <script-file-name> defaults
9. Reboot the system. You can also Stop and Start your AWS instance.
10. Check your Jenkins Node, it should be connected now 🙂

Hope this will help you 🙂

It shows error “SenTestingKit.Framework not found” when trying to build/run Unit Test in Xcode

It is more or less common error “SenTestingKit.Framework not found” that people sees when building/running Unit Test after adding it in an existing project in Xcode. It can be shown also with existing Unit Test project which may ran properly before. To fix this error simply follow the steps below:

Step 1

Select the project icon (blue XCode icon) in the Project Navigator and open the tab Build Settings.

Step 2

Goto:  Linking > Bundle Loader

Add the following: $(BUILT_PRODUCTS_DIR)/Your_App_Name.app/Your_App_Name

Step 3

Goto: Unit Testing > Test Host

Add: $(BUNDLE_LOADER)

Step 4

Goto: Search Path > Framework Search Path

Add these 2 lines without double quotation (“) :

“$(SDKROOT)/Developer/Library/Frameworks”

“$(DEVELOPER_LIBRARY_DIR)/Frameworks”

Now Clean and Build the project. Hopefully your Project will Build and Run successfully this time 🙂

~~ 🙂 ~~ Happy Testing ~~ 🙂 ~~

Wait while [NSTimer scheduledTimerWithTimeInterval…] works in function while Unit Testing

Wait while [NSTimer scheduledTimerWithTimeInterval…] works in function while Unit Testing

 
Insert the code:
 
NSDate *runUntil = [NSDate dateWithTimeIntervalSinceNow: 3.0 ];
NSLog(@”about to wait”);
[[NSRunLoop currentRunLoop] runUntilDate:runUntil];
NSLog(@”wait time is over”);
 
Just after the function call that uses NSTimer.
 
Reference:

Android showing the error: activity_name cannot be resolved or is not a field

When trying to build android if you get a message like:
activity_main cannot be resolved or is not a field

In general:
<activity name> cannot be resolved or is not a field

Then it become difficult to get the exact cause! Don’t worry there is a simple solution for this.

Solution

Just delete:

import android.R;

and rebuild. You are done 🙂

= 🙂 = Happy Coding = 🙂 =

How to add Unit Test Project in an existing Objective-C project in XCode 4

There are many posts in web regarding this topic. My post is like reinventing the wheel. In this post I will try to guide you to add unit test project in an existing Objective-C project in Xcode 4, step-by-step.

Before the journey I want to state that if you are planning to start your new project then you can add your test project at the time of creation. That process will be discussed in separate post. So let’s start.

Considering your existing project name <My_Apps>.

  • Open your <My_Apps> in your XCode.
  • Select the Projects Blue icon in the Project Navigator panel.
  • Click Add Target resides at the bottom panel.

Add Test Project

  • Select Other of iOS section from the left panel of the pop-up appeared.
  • From list of options in the right panel select Cocoa Touch Unit Testing Bundle.
  • Click Next.

Select Test Project

  • Enter the Product Name , say <My_Apps_Test> and Click Finish.

Project Name

A test project with your given name should be added in the Project Navigator. In your test project there should be 2 files added by default – My_Apps_Test.h & My_Apps_Test.m.

Let’s check the files that XCode created for us.

Open My_Apps_Test.h. In this file the test framework will be imported by default with empty @interface declaration as below:

        #import <SenTestingKit/SenTestingKit.h>
        @interface My_Apps_Test : SenTestCase

        @end

Open My_Apps_Test.m and you should be able to see 3 functions XCode created for you – setUp, tearDown & testExample.

WAIT…… you are not done yet.

Click on the Unit Test Project icon again and follow the steps:

  • Click Build Phases tab.
  • Expand Target Dependencies.

Target-Dependencies

  • Click +.
  • In the pop-up appeared, you should be able to see your project. Select it and click Add.
  • Your project should be added to the Target Dependencies section.

Let us check the Compile Source section immediately under the Target Dependencies section. In this section the .m extension file of the test project <My_Apps_Test> file should be added by default. Note if your test project directory have more files then all the .m extensions of the files will be added by default.

Compile-Source

We are left out with one more task to do for Build Phases tab. Expand Link Binary With Libraries. In this section notice that the SenTestingKit’s library file is highlighted with red color and no yellow icon will be shown beside it as others – SenTestingKit.Framework. Now let us fix this problem with the following three (03) steps:

  • Select SenTestingKit.Framework.
  • Click – situated below of the section.
  • Now click + at the left side of –.
  • From the pop-up select the SenTestingKit.Framework again. (Good idea is to type the framework name in the search field.)
  • Click Add.
  • Check the Library list. The framework should be added properly and the yellow icon beside the framework should be shown properly.

Now check the Project Navigator. Newly added SenTestingKit framework is added under the Project. If you like you can drag it to the Frameworks directory in the Project Navigator panel.

Next step will be to open the Frameworks directory. Here you will have another SenTestingKit.Framework highlighted in red color with no yellow icon. Remove it with no worries.

Next Step will be adding build settings and for that click on the Build Settings tab right beside Build Phases tab. After the tab opens add the following value to their proper fields, exactly in the same order as the steps defines:

  • Linking > Bundle Loader > $(BUILT_PRODUCTS_DIR)/<YOUR APP NAME>.app/<YOUR APP NAME>. According to my tutorial <YOUR APP NAME> will be replaced with My_Apps.
  • Unit Testing > Test Host > $(BUNDLE_LOADER)
  • Apple LLVM compiler 4.1 – Code Generation > Symbol Hidden By Default > NO.

OK now we are done with adding our test project. Let us make a test run. To Test we need to click: Product > Test  or  ⌘U.

OOPS!!! Now why the Test option is disabled? Don’t worry one simple step will solve this problem. From scheme, at the top left of the XCode just beside the RUN and STOP buttons, click My_Apps. From pop-up list select My_Apps_Test > iPhone 6.0 Simulator, considering you are trying to test in iPhone Simulator. It is OK to select any other Simulator from simulator available list for the target – My_Apps_Test.

Now again try to Test the project. This time you should be able to run the test.

After the test is done, test result will show FAIL and will show the message that is set in the My_Apps_Test.m file – Unit tests are not implemented yet in My_Apps_Test. As no test has been implemented yet in your test project thus the test shows the fail message, which is expected.

Test Fail

That’s all folks!!

~::~     Happy Testing     ~::~