Monday, 5 December 2016

Android Get Value Of List Checkbox And Displaying On Other Activity As A List

Have you work with checkbox? exactly list of checkbox. I pretty sure you have worked with it and you may agree with me if you are newbie in android, it feels so difficult to get the value of list checkbox and display to other activity, right? I was felt it. hahaha




PREPARATION



Compile this libraries in your build.gradle (Module : app) :

compile 'com.android.support:recyclerview-v7:25.0.1'
compile 'com.google.code.gson:gson:2.6.2'

then, create four xml layouts and one menu in your res/menu:
  1. activity_main.xml 
  2. second_activity.xml
  3. activity_detail.xml || this layout used in your Adapter
  4. add_item.xml || popup layout
  5. main_menu.xml 
and, create some java classes :
  1. MainActivity.java
  2. SecondActivity.java
  3. ItemAdapter.java
  4. Constants.java || this java class for save all our string value 

IMPLEMENTATION


1. Modify your activity_main.xml, paste the following code :

2. Modify your second_activity.xml, paste the following code :

3. Modify your activity_detail.xml, paste the following code :

4. Modify your add_item.xml, paste the following code :

5. Modify your main_menu.xml in directory res/menu/. Paste the following code :

After all of file xmls have been modified, now modify all of your java classes

6. Modify your Constants.java. This java class used to save our string value. In this case, just save string value of sharedPreferences. Paste the following code :

7. Modify your ItemAdapter.java. This java class used to set your added item using holder. Paste the following code :

Please take a look clearly at the code above, there is a method namely getSelectedString() and return a list. That method used in checkbox state condition. Gson used to format list item chosen as a string and store using SharedPreferences.

8. Modify your MainActivity.java. Paste the following code :

In MainActivity.java, we do add the item by using the action bar menu. And main_menu.xml used in this class.

9. Finally, Modify your SecondActivity.java. In this class we'll display all the checkbox value that has been chosen as a list. Because we stored the data in SharedPreferences, so first we have to format or convert the string value that we got from SharedPreferences to Array using Gson. Paste the following code :

DOWNLOAD THE PROJECT HERE : LINK GITHUB


EmoticonEmoticon