Monday, December 5, 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 :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.putuguna.checkboxtransferdata.MainActivity">
<TextView
android:layout_width="match_parent"
android:gravity="center"
android:textStyle="bold"
android:layout_height="wrap_content"
android:text="Kind of Electronc Item" />
<android.support.v7.widget.RecyclerView
android:layout_weight="1"
android:id="@+id/rv_item_electronic"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
<TextView
android:layout_marginBottom="10dp"
android:gravity="bottom|center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="10sp"
android:text="androidbie.blogspot.com || putuguna.com"/>
</LinearLayout>
2. Modify your second_activity.xml, paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_second"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.putuguna.checkboxtransferdata.SecondActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="YOUR LIST ITEM "
android:textColor="@android:color/black"
android:textStyle="bold"
android:gravity="center"/>
<ListView
android:layout_weight="1"
android:id="@+id/listview_detail_item"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
<TextView
android:layout_marginBottom="10dp"
android:gravity="bottom|center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="10sp"
android:text="androidbie.blogspot.com || putuguna.com"/>
</LinearLayout>
3. Modify your activity_detail.xml, paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:padding="@dimen/activity_horizontal_margin"
android:layout_height="wrap_content">
<LinearLayout
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="@+id/checkbox_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv_item_name"
android:layout_marginLeft="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item chosend"/>
</LinearLayout>
</LinearLayout>
4. Modify your add_item.xml, paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="@dimen/activity_horizontal_margin"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="INPUT YOUR ITEM "
android:textStyle="bold"
android:textColor="@android:color/black"/>
<EditText
android:id="@+id/edit_text_add_item"
android:layout_width="match_parent"
android:hint="type your item"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_weight="1"
android:id="@+id/btn_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save"/>
<Button
android:layout_weight="1"
android:id="@+id/btn_cancel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Cancel"/>
</LinearLayout>
</LinearLayout>
view raw add_item.xml hosted with ❤ by GitHub
5. Modify your main_menu.xml in directory res/menu/. Paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/add_item"
android:icon="@drawable/ic_content_add"
android:title="Add Item"
app:showAsAction="always"
/>
<item android:id="@+id/done_add_item"
android:icon="@drawable/ic_navigation_check"
android:title="Done"
app:showAsAction="always"
/>
</menu>
view raw main_menu.xml hosted with ❤ by GitHub
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 :

package com.putuguna.checkboxtransferdata;
/**
* Created by putuguna on 04/12/16.
*/
public class Constants {
public static final String KEY_SHARED = "key-shared";
public static final String MODE_SHARED = "mode-shared";
}
view raw Constants.java hosted with ❤ by GitHub
7. Modify your ItemAdapter.java. This java class used to set your added item using holder. Paste the following code :


package com.putuguna.checkboxtransferdata;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
/**
* Created by putuguna on 04/12/16.
*/
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.Holder> {
private List<String> itemList;
private Context context;
private List<String> itemSelected = new ArrayList<>();
public ItemAdapter(List<String> itemList, Context context) {
this.itemList = itemList;
this.context = context;
}
@Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.activity_detail, parent, false);
return new Holder(view);
}
@Override
public void onBindViewHolder(final Holder holder, final int position) {
final String itemName = itemList.get(position);
holder.tvItemName.setText(itemName);
final List<String> listItemChosen = new ArrayList<>();
SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.MODE_SHARED, Context.MODE_PRIVATE);
final SharedPreferences.Editor edit = sharedPreferences.edit();
final Gson gson = new Gson();
holder.cbItem.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
itemSelected.add(itemName);
String jsonString = gson.toJson(getSelectedString());
edit.putString(Constants.KEY_SHARED,jsonString);
edit.commit();
System.out.println("JSON : " + jsonString);
System.out.println("SIZE : " + listItemChosen.size());
}else{
itemSelected.remove(itemName);
String jsonString = gson.toJson(getSelectedString());
edit.putString(Constants.KEY_SHARED,jsonString);
edit.commit();
System.out.println("JSON : " + jsonString);
System.out.println("SIZE : " + listItemChosen.size());
}
}
});
}
@Override
public int getItemCount() {
return itemList.size();
}
/**
* create inner class for custom holder
*/
public static class Holder extends RecyclerView.ViewHolder{
public TextView tvItemName;
public CheckBox cbItem;
public Holder(View itemView) {
super(itemView);
tvItemName = (TextView) itemView.findViewById(R.id.tv_item_name);
cbItem = (CheckBox) itemView.findViewById(R.id.checkbox_item);
}
}
/**
* create this method for return new value in list item selected
* @return
*/
private List<String> getSelectedString(){
return itemSelected;
}
}
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 :

package com.putuguna.checkboxtransferdata;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView rvItem;
private List<String> listItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rvItem = (RecyclerView) findViewById(R.id.rv_item_electronic);
listItem = new ArrayList<>();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==R.id.add_item){
addItem();
}else if(id==R.id.done_add_item){
startActivity(new Intent(MainActivity.this, SecondActivity.class));
}
return super.onOptionsItemSelected(item);
}
/**
* this method used to add item
*/
private void addItem(){
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.add_item);
final EditText etInputItem = (EditText) dialog.findViewById(R.id.edit_text_add_item);
Button btnSave = (Button) dialog.findViewById(R.id.btn_save);
Button btnCancel = (Button) dialog.findViewById(R.id.btn_cancel);
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String item = etInputItem.getText().toString();
if(TextUtils.isEmpty(item)){
Toast.makeText(MainActivity.this, "Item name is required!", Toast.LENGTH_SHORT).show();
return;
}
listItem.add(item);
ItemAdapter adapter = new ItemAdapter(listItem, MainActivity.this);
rvItem.setLayoutManager(new LinearLayoutManager(MainActivity.this));
rvItem.setItemAnimator(new DefaultItemAnimator());
rvItem.setAdapter(adapter);
dialog.dismiss();
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
}
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 :

package com.putuguna.checkboxtransferdata;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.gson.Gson;
import java.util.List;
public class SecondActivity extends AppCompatActivity {
private ListView lvItemChosen;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
lvItemChosen = (ListView) findViewById(R.id.listview_detail_item);
//start convert the string value to array
SharedPreferences sharedPreferences = getSharedPreferences(Constants.MODE_SHARED, Context.MODE_PRIVATE);
Gson gson = new Gson();
String jsonString = sharedPreferences.getString(Constants.KEY_SHARED, null);
String[] listItem = gson.fromJson(jsonString, String[].class);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItem);
lvItemChosen.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
DOWNLOAD THE PROJECT HERE : LINK GITHUB

Related Posts


EmoticonEmoticon

:)
:(
hihi
:-)
:D
=D
:-d
;(
;-(
@-)
:o
:>)
(o)
:p
:-?
(p)
:-s
8-)
:-t
:-b
b-(
(y)
x-)
(h)