CheckBoxes unchecked after scrolling my custom ListView - android

I created a custom ListView, and put some CheckBoxes in it.
At First, I check all the CheckBoxes and then I scroll down the ListView, then the CheckBoxes become unchecked.
What should I do?
CustomListItem.java
public class HomeListAdapter extends ArrayAdapter<HashMap<String, Object>> {
//new
//private final boolean[] mCheckedState;
// private final Context mContext;
boolean[] itemChecked;
//
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
private DisplayImageOptions options;
public HomeListAdapter(Context context, ArrayList<HashMap<String, Object>> dataMap) {
super(context, 0, dataMap);
//new
itemChecked = new boolean[dataMap.size()];
// mContext = context;
//
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.com_facebook_profile_picture_blank_square)
.showImageForEmptyUri(R.drawable.com_facebook_profile_picture_blank_square)
.showImageOnFail(R.drawable.log)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.displayer(new RoundedBitmapDisplayer(20)).build();
this.notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
HashMap<String, Object> dataMap = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item1, parent, false);
}
TextView description = (TextView) convertView.findViewById(R.id.description);
description.setText(dataMap.get(Home1.TAG_CNAME).toString());
TextView email = (TextView) convertView.findViewById(R.id.company);
email.setText(dataMap.get(Home1.TAG_EMAIL).toString());
final CheckBox check= (CheckBox) convertView.findViewById(R.id.ck);
//new
/*
check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (check.isChecked())
itemChecked[position] = true;
Toast.makeText(getContext(),itemChecked,);
else
itemChecked[position] = false;
}
});*/
check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (check.isChecked())
itemChecked[position] = true;
// Toast.makeText(getContext(),itemChecked,);
else
itemChecked[position] = false;
}
});
//
if (dataMap.get(Home1.TAG_LIKE).toString().equals("true")) {
check.setChecked(true);
}else{
check.setChecked(false);
}
ImageView logo = (ImageView) convertView.findViewById(R.id.logo);
ImageLoader.getInstance().displayImage(dataMap.get(Home1.TAG_IMAGE).toString(),logo, options, animateFirstListener);
return convertView;
}
This is my Adapter Classs please help me guys to resolve this issue....
#Override
public void onCreate(Bundle savedInstanceState) {
//Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
session = new SessionManager(getApplicationContext());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// apikey
apikey = user.get(SessionManager.KEY_api);
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
ImageView back = (ImageView) findViewById(R.id.sel);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Intent intent = new Intent(Home1.this, Selected.class);
// finish();
// startActivity(intent);
try {
ListView lv = getListView();
ids = "";
int count = 0;
String text = "";
//CheckBox cbView;
TextView textView;
int total = lv.getCount();
for (int i = 0; i < total; i++) {
if (lv.getChildAt(i) != null) {
textView = (TextView) lv.getChildAt(i).findViewById(R.id.company);
text = textView.getText().toString();
cbView = (CheckBox) lv.getChildAt(i).findViewById(R.id.ck);
if (cbView.isChecked()) {
count += 1;
ids += text + ", ";
}
}
}
ids = ids.substring(0, ids.length()-2);
//Toast.makeText(getApplicationContext(), "Company emails: " + ids + " Total Checked: " + count, Toast.LENGTH_SHORT).show();
new DownloadOperation().execute();
}
catch(Exception ex){
System.out.println("My Message");
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
});

You can overcome this easily by using the ChoiceMode option CHOICE_MODE_MULTIPLE for the ListView as used in the API Demo -
public class List11 extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, GENRES));
final ListView listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
private static final String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
};
}
EDIT
Alternate for your context-
Have an extra boolean object with your HashMap<String, Object> isChecked and initialize it to false when you populate your list.
Set your CheckBox in getView() method as-
check.setChecked(Boolean.parseBoolean(dataMap.get("isChecked"));
Now in the listener OnCheckedChangeListener() set the value of your dataMap true or false accordingly.

Related

how to get all listview checked item on buttonclick?

setContentView(R.layout.activity_violation);
db = new DatabaseHelper(this);
sqLiteDatabase = db.getReadableDatabase();
spinner = (Spinner) findViewById(R.id.spinner1);
loadspinnerdata();
txtTexts = (TextView) findViewById(R.id.texts);
btnBack = (Button) findViewById(R.id.btnBack);
btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listviewData();
}
});
strSelectedItem = spinner.getSelectedItem().toString();
listview = (ListView) findViewById(R.id.listView);
LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup) inflater.inflate(R.layout.list_header, listview, false);
listview.addHeaderView(header, null, false);
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list_query = "select _id,section,offence,fine from tblSection";
Cursor clistview = sqLiteDatabase.rawQuery(list_query, null);
listadapter = new ListAdapter(this, clistview, 0);
listview.setAdapter(listadapter);private void listviewData() {
int cntChoice = listview.getCount();
String checked = "";
String unchecked = "";
SparseBooleanArray sparseBooleanArray = listview.getCheckedItemPositions();
for(int i = 0; i < cntChoice; i++)
{
if(sparseBooleanArray.get(i))
{
checked += listview.getItemAtPosition(i).toString() + "\n";
}
else if(!sparseBooleanArray.get(i))
{
unchecked+= listview.getItemAtPosition(i).toString() + "\n";
}
}
I am using cursorAdapter in order to populate listview from database?so I am not getting position as i get from getView method in arrayAdapter
public class ListAdapter extends CursorAdapter{
TextView tvSection,tvOffence,tvId,tvFine;
CheckBox chkBox;
ArrayAdapter<String> objects;
private boolean chkItem;
CompoundButton.OnCheckedChangeListener myCheckChangList;
public ListAdapter(Context context, Cursor c, int _id) {
super(context, c,_id);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
return LayoutInflater.from(context).inflate(R.layout.listview_item,viewGroup,false);
}
public class ViewHolder{
TextView tvSection,tvOffence,tvId,tvFine;
CheckBox chkBox;
boolean chkItem;
boolean selected = false;
public ViewHolder(boolean chkItem){
super();
this.chkItem=chkItem;
}
public ViewHolder() {
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder=null;
holder = new ViewHolder();
holder.tvSection = (TextView) view.findViewById(R.id.txtSection);
holder.tvOffence = (TextView) view.findViewById(R.id.txtOffence);
holder.tvId = (TextView) view.findViewById(R.id.txtId);
holder.tvFine = (TextView) view.findViewById(R.id.txtFine);
holder.chkBox = (CheckBox) view.findViewById(R.id.checkBox);
holder.chkBox.setOnCheckedChangeListener(myCheckChangList);
view.setTag(holder);
strFine=cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
String strSection = cursor.getString(cursor.getColumnIndexOrThrow("section"));
String strOffence = cursor.getString(cursor.getColumnIndexOrThrow("offence"));
int strFine = cursor.getInt(cursor.getColumnIndexOrThrow("fine"));
holder.tvSection.setText(strSection);
holder.tvOffence.setText(strOffence);
holder.tvFine.setText(String.valueOf(strFine));
final ViewHolder finalHolder = holder;
}
I tried this but this isn't working.I tried checkbox.setOnclicklistener which gives me the checked row value single item but not multiple checked item.I tried sparseboolean array also.
If you are trying to get selected values from listing using checkbox,try this way it will work
public class CardViewActivity extends AppCompatActivity {
private Toolbar toolbar;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<Student> studentList;
private Button btnSelection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
btnSelection = (Button) findViewById(R.id.btnShow);
studentList = new ArrayList<Student>();
for (int i = 1; i <= 15; i++) {
Student st = new Student("Student " + i, "androidstudent" + i
+ "#gmail.com", false);
studentList.add(st);
}
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Android Students");
}
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// create an Object for Adapter
mAdapter = new CardViewDataAdapter(studentList);
// set the adapter object to the Recyclerview
mRecyclerView.setAdapter(mAdapter);
btnSelection.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String data = "";
List<Student> stList = ((CardViewDataAdapter) mAdapter)
.getStudentist();
for (int i = 0; i < stList.size(); i++) {
Student singleStudent = stList.get(i);
if (singleStudent.isSelected() == true) {
data = data + "\n" + singleStudent.getName().toString();
/*
* Toast.makeText( CardViewActivity.this, " " +
* singleStudent.getName() + " " +
* singleStudent.getEmailId() + " " +
* singleStudent.isSelected(),
* Toast.LENGTH_SHORT).show();
*/
}
}
Toast.makeText(CardViewActivity.this,
"Selected Students: \n" + data, Toast.LENGTH_LONG)
.show();
}
});
}
}
http://android-pratap.blogspot.in/2015/01/recyclerview-with-checkbox-example.html
On clicking outside the adapter, use the following code. "ListAdapter" should be the Adapter class name.
ListAdapter.unCheck((ViewGroup)view.getParent());
If your on clicking is inside the adapter, then ignore the above code and use the below one.
unCheck((ViewGroup)view.getParent());
make the following function in Adapter.
public static void unCheck(ViewGroup vg) {
for (int i = 0; i < vg.getChildCount(); i++) {
View v = vg.getChildAt(i);
if (v instanceof CheckBox) {
((CheckBox) v).setChecked(true);
} else if (v instanceof ViewGroup) {
unCheck((ViewGroup) v);
}
}
}
The above function will checked all the checkBox of the list view. Have Fun. Take Care.

Retrieving data from listview when im using adapter

I am able to display the toast in my menuactivity but now i will need to get the selected data from listview and display it on another page. I have tried alot of methods and search on it but i cant seem to get it.
menuactivity :
public class MenuActivity extends Activity {
private String server = "http://172.16.156.56";
private String sql_table = "orders";
private ListView list;
private TextView txtOrder, txtMember, txtPrice;
private Button btnAdd;
ArrayList<String> rows;
ListView listView1;
Button btnSubmit;
ArrayList<CustomItem> itemList, selectedList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
list=(ListView) findViewById(R.id.listView);
btnAdd = (Button)findViewById(R.id.button);
rows = new ArrayList<String>();
itemList=new ArrayList<CustomItem>();
itemList.add(new CustomItem("Fried Rice","description","1","Quantity"));
itemList.add(new CustomItem("Fried Noodle","description","2","Quantity"));
itemList.add(new CustomItem("Prawn noodle","description","3","Quantity"));
itemList.add(new CustomItem("Chicken Rice","description","4","Quantity"));
int[] prgmImages={R.drawable.friedrice,R.drawable.friednoodle,R.drawable.pnoodle,R.drawable.chickenrice};
listView1 = (ListView) findViewById(R.id.listView);
final CustomLVAdapter customLVAdapter = new CustomLVAdapter(this, itemList,prgmImages);
listView1.setAdapter(customLVAdapter);
txtOrder = (TextView) findViewById(R.id.txt1);
txtMember = (TextView) findViewById(R.id.txt2);
txtPrice = (TextView) findViewById(R.id.txt3);
btnSubmit = (Button) findViewById(R.id.button);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
selectedList = new ArrayList<CustomItem>();
int total = 0;
for (int i = 0; i < itemList.size(); i++) {
CustomItem object = itemList.get(i);
if (object.isSelected()) {
responseText.append(object.getItem() + "," + object.getQty() + ",");//item
selectedList.add(object);
//calculate price
total = total + Integer.parseInt(object.getQty()) * Integer.parseInt(object.getPrice());
}
}
Add(responseText.toString(), "5565", String.valueOf(total));
Intent i = new Intent(v.getContext(), ReceiptActivity.class);
startActivity(i);
Toast.makeText(getApplicationContext(), responseText + " $" + total,
Toast.LENGTH_SHORT).show();
SelectAll();
//store in database
//go to ReceiptActivity - membership, item, totalprice
}
});
}
public void Add(final String item, final String membership, final String price)
{
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = server + "/insertorder.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("item",item );
MyData.put("membership",membership );
MyData.put("price",price );
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
SelectAll();
}
public void SelectAll()
{
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = server + "/fetchorder.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray jsonMainNode = jsonResponse.optJSONArray(sql_table);
rows.clear();
for(int i=0; i < jsonMainNode.length(); i++)
{
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String order = jsonChildNode.optString("item").toString();
String membership = jsonChildNode.optString("membership").toString();
String price = jsonChildNode.optString("price").toString();
rows.add(order + ", " + membership + ", " + price );
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MenuActivity.this,
android.R.layout.simple_list_item_1, rows);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
});
MyRequestQueue.add(MyStringRequest);
}
}
Receipt activity ( the page i wan to display my results)
public class ReceiptActivity extends Activity {
static public String txtOrder = "";
TextView foodorder;
ArrayList<CustomItem> itemList, selectedList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receipt);
CustomLVAdapter item = (CustomLVAdapter) parent.getItemAtPosition(position);
TextView foodorder = (TextView)findViewById(R.id.foodorder);
foodorder.setText("Order:" +strOrder+" ");
Custom adapter
public class CustomLVAdapter extends BaseAdapter {
private Context context;
LayoutInflater inflater;
private ArrayList<CustomItem> objectList;
private int[] imageId;
public static ArrayList<CustomItem> arl_food=new ArrayList<>();
private class ViewHolder {
TextView txt1,txt2,txt3;
CheckBox ckBox;
ImageView image;
NumberPicker np;
}
public CustomLVAdapter(Context context, ArrayList<CustomItem> objectList,int[]prgmImages){
this.context = context;
this.inflater = LayoutInflater.from(context);
this.objectList = objectList;
this.imageId = prgmImages;
}
public int getCount(){
return objectList.size();
}
public CustomItem getItem (int position) {
return objectList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row_checkbox_textview, null);
holder.txt1 = (TextView) convertView.findViewById(R.id.txt1);
holder.txt2 = (TextView) convertView.findViewById(R.id.txt2);
holder.txt3 = (TextView) convertView.findViewById(R.id.txt3);
holder.image=(ImageView) convertView.findViewById(R.id.image);
holder.ckBox = (CheckBox) convertView.findViewById(R.id.ckBox);
holder.np = (NumberPicker) convertView.findViewById(R.id.numberPicker);
holder.np.setMinValue(0);
holder.np.setMaxValue(10);
convertView.setTag(holder);
holder.ckBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
CustomItem object = (CustomItem) cb.getTag();
Toast.makeText(context,
"You have selected: " + object.getItem() +
"Price: " + object.getPrice() +
"Qty: " + object.getQty(),
Toast.LENGTH_LONG).show();
object.setSelected(cb.isChecked());
}
}
);
holder.np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
NumberPicker p = picker;
CustomItem object = (CustomItem) p.getTag();
object.setQty(String.valueOf(newVal));
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
CustomItem object = objectList.get(position);
holder.txt1.setText(object.getItem());
holder.txt2.setText(object.getDesc());
holder.txt3.setText(object.getPrice());
holder.np.setTag(object);
holder.image.setImageResource(imageId[position]);
holder.ckBox.setChecked(object.isSelected());
holder.ckBox.setTag(object);
return convertView;
}
}
It looks like you are already starting an activity when the submit button is clicked. Now all you have to do is pass a couple extras in the intent you are creating.
So when you make the intent you should also do this:
...
Intent i = new Intent(v.getContext(), ReceiptActivity.class);
i.putExtra("PRICE", price);
i.putExtra("MEMBERSHIP", membership);
i.putExtra("ITEM", item);
startActivity(i);
...
Then in your new activity you will read out the extras in your onCreate method like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receipt);
int price = getIntent().getStringExtra("PRICE");
String membership = getIntent().getStringExtra("MEMBERSHIP");
CustomItem item = getIntent().getStringExtra("ITEM");
...
One Caveat! It looks like you are representing your items with the object CustomItem. In order to pass that as an extra it will have to implement Parcelable. When you implement Parcelable you will define how to turn the object and its fields into a "parcel" and how to turn a "parcel" back into your object. The google docs give a pretty good example for it.
I lied, another caveat! I would recommend that you make the keys for the extras "public static final String"s inside of your ReceiptActivity. That way you will have an easier time managing them.

On Scrolling Of listview radio button is automatically changing its state and some are previously checked in android

it is list of student selected by me it is list of student already selected when i scroll list in my custom list view when i am running application then radio buttons at bottom are already checked when i am checking upper radio button .how can i set radio button so that its state never change on scrolling list .
Here is my code for studentlist.java
public class studentlist extends AppCompatActivity {
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_ClassDet = "classdetails";
private static final String TAG_YEAR = "yearof";
private static final String TAG_BRANCH ="branchof";
private static final String TAG_SECTION ="sectionof";
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private ArrayList<HashMap<String, String>> studentattendence,studentstatus;
ListView listView;
ArrayAdapter<Model> adapter;
List<Model> list = new ArrayList<Model>();
public ArrayList<HashMap<String, String>> personList;
private static final String KEY_STUDENT = "student";
private RadioGroup radioGroup;
private RadioButton radiobtn;
public Button ok;
private RadioButton radioButton;
HashMap<String, String> contact,contactstatus;
private String convertjson;
private String statusofattendence;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.liststudent);
listView = (ListView) findViewById(R.id.my_list);
studentattendence=new ArrayList<HashMap<String, String>>();
studentstatus=new ArrayList<HashMap<String, String>>();
personList = new ArrayList<HashMap<String, String>>();
Intent getstud = getIntent();
personList = (ArrayList<HashMap<String, String>>) getstud.getSerializableExtra(KEY_STUDENT);
ok= (Button) findViewById(R.id.ok);
Toast.makeText(getApplicationContext(), pioGroup.ersonList.get(0).get("enrolment") + "" + personList.get(1).get("enrolment") + "" + personList.get(2).get("enrolment"), Toast.LENGTH_LONG).show();
adapter = new MyAdapter(this, getModel(personList));
listView.setAdapter(adapter);
radioGroup = (RadioGroup) findViewById(R.id.radio);
listView.childDrawableStateChanged(radioGroup);
////ok button click get status of each radio button and store in hashmap
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int child=listView.getChildCount();
ArrayList<String> radio=new ArrayList<>();
View[] vy = new View[1];
Log.d("child", String.valueOf(child));
for(int i=0;i<child;i++) {
// RadioGroup rd = (RadioGroup) listView.getChildAt(i);
View rgg=listView.getChildAt(i);
Log.d("radioview",String.valueOf(rgg));
radioGroup = (RadioGroup) rgg.findViewById(R.id.radio);
Log.d("radiogroup", String.valueOf(radioGroup));
int selectedId=radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) rgg.findViewById(selectedId);
TextView tv= (TextView) rgg.findViewById(R.id.label);
Log.d("radiobutton and id", selectedId + "" + radioButton);
String status= radioButton.getText().toString();
Log.d("hello",status);
String enrol=tv.getText().toString();
contact = new HashMap<String, String>();
contact.put("enrollmentnum",enrol);
Log.d("enum",enrol);
studentattendence.add(contact);
contactstatus = new HashMap<String, String>();
contactstatus.put("status",status);
Log.d("ststuss",status);
studentstatus.add(contactstatus);
}
///here converting arraylist in to json string
convertjson = new Gson().toJson(studentattendence);
statusofattendence=new Gson().toJson(studentstatus);
Toast.makeText(getApplicationContext(),""+convertjson+""+statusofattendence,Toast.LENGTH_LONG).show();
NetAsync(v, convertjson,statusofattendence);
}
});
}
private List<Model> getModel(ArrayList<HashMap<String, String>> personList) {
for (int i = 0; i < personList.size(); i++) {
String enrolment = personList.get(i).get("enrolment");
list.add(new Model(enrolment));
}
return list;
}
////now we will send taked attendence to webservice
private class NetCheck extends AsyncTask<String,String,Boolean>
{
public final String convertjson,statusofattendence;
private ProgressDialog nDialog;
public NetCheck(String convertjson,String statusofattendence) {
this.convertjson=convertjson;
this.statusofattendence=statusofattendence;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
nDialog = new ProgressDialog(studentlist.this);
nDialog.setMessage("Loading..");
nDialog.setTitle("Checking Network");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected Boolean doInBackground(String... args) {
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
/*
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
// return false;
return true;
}
#Override
protected void onPostExecute(Boolean th) {
if (th == true) {
nDialog.dismiss();
new ProcessRegister().execute();
} else {
nDialog.dismiss();
}
}
}
private class ProcessRegister extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String forgotpassword;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(studentlist.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
TeacherFunctions userFunction = new TeacherFunctions();
Log.d("convertjson",convertjson);
Log.d("convertjson",statusofattendence);
JSONObject json = userFunction.addAttendence(convertjson,statusofattendence);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
/**
* Checks if the Password Change Process is sucesss
**/
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
String red = json.getString(KEY_ERROR);
if(Integer.parseInt(res) == 1){
pDialog.dismiss();
Toast.makeText(getApplicationContext(),"students Attendence Uploaded successfully"+json.getString("user"),Toast.LENGTH_LONG).show();
}
else if (Integer.parseInt(red) == 2)
{ pDialog.dismiss();
}
else {
pDialog.dismiss();
}
}}
catch (JSONException e) {
e.printStackTrace();
pDialog.dismiss();
Toast.makeText(getApplicationContext()," not Uploaded successfully"+e,Toast.LENGTH_LONG).show();
}
}}
public void NetAsync(View view, String convertjson,String statusofattendence){
new NetCheck(convertjson,statusofattendence).execute();
}
}
Code for model.java
public class Model {
private String name;
private boolean selected;
public Model(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
code for MyAdapter.java
public class MyAdapter extends ArrayAdapter<Model> {
private final List<Model> list;
private final Activity context;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public MyAdapter(Activity context, List<Model> list) {
super(context, R.layout.row, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView text;
protected RadioButton radiobox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.row, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.label);
viewHolder.radiobox = (RadioButton) convertView.findViewById(R.id.radio1);
viewHolder.radiobox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.label, viewHolder.text);
convertView.setTag(R.id.radio1, viewHolder.radiobox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.radiobox.setTag(position); // This line is important.
viewHolder.text.setText(list.get(position).getName());
viewHolder.radiobox.setChecked(list.get(position).isSelected());
return convertView;
}
}
You are using setOnCheckedChangeListener() on viewHolder.radiobox. it is very bad code for that, because each time convertView getting null to view then setOnCheckedChangeListener() also called. And it set your modal data to next position. If you want to check it just put Log in onCheckedChange or try to put breakpoint in it.
just try this :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.row, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.label);
viewHolder.radiobox = (RadioButton) convertView.findViewById(R.id.radio1);
convertView.setTag(viewHolder);
convertView.setTag(R.id.label, viewHolder.text);
convertView.setTag(R.id.radio1, viewHolder.radiobox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.radiobox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if(viewHolder.radiobox.isChecked())
{
viewHolder.radiobox.setChecked(false);
}
else
{
viewHolder.radiobox.setChecked(true);
}
list.get(getPosition).setChecked( viewHolder.radiobox.isChecked()); // Set the value of checkbox to maintain its state.
}
});
viewHolder.text.setText(list.get(position).getName());
viewHolder.radiobox.setChecked(list.get(position).isChecked());
return convertView;
}
hope it will help you.
enter code here
getListView().setOnScrollListener(this);***
enter code here
public void onScroll(AbsListView view, int firstCell, int cellCount, int itemCount) {
RadioButton rb1 = (RadioButton) findViewById(R.id.option1);
rb1.setChecked(flase);
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
Actually everything was not working properly and then i had moved to listview with 4 button in place of radio button.

Android fragment BaseAdapter list view not working

I got problem in show list view using BaseAdapter in Fragment activity.
I did not get any error log but list view is not showing,I don't know how solve this ?
My FragmentActivity class :
public class Fragment_Activity extends FragmentActivity {
/** Called when the activity is first created. */
private static final String TAB_1_TAG = "Invitation";
private static final String TAB_2_TAG = "Occasion";
private static final String TAB_3_TAG = "Friends";
private FragmentTabHost tabHost;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_tabs);
// Get TabHost Refference
tabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
tabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
tabHost.addTab(tabHost.newTabSpec(TAB_1_TAG).setIndicator(""), InvitationFragment.class, null);
tabHost.addTab(tabHost.newTabSpec(TAB_2_TAG).setIndicator(""), OccasionFragment.class, null);
tabHost.addTab(tabHost.newTabSpec(TAB_3_TAG).setIndicator(""), ContactActivity.class, null);
// Set drawable images to tab
tabHost.getTabWidget().getChildAt(1).setBackgroundResource(R.drawable.ic_action_event);
tabHost.getTabWidget().getChildAt(2).setBackgroundResource(R.drawable.ic_action_phone);
// Set Tab1 as Default tab and change image
tabHost.getTabWidget().setCurrentTab(0);
tabHost.getTabWidget().getChildAt(0).setBackgroundResource(R.drawable.ic_action_person);
}
}
My contact activity class:
public class ContactActivity extends Fragment implements OnItemClickListener {
private Gson gson = new Gson();
private List<String> userName = new ArrayList<String>();
private List<String> mobileNumber = new ArrayList<String>();
private ContactDispAdapter contactDispAdapter;
private Button btnAdd;
private Button btnSend;
private ProgressDialog prgDialog;
UserDelegate userDelegate = new UserDelegate();
private Context context;
private HashMap<String, UserMO> userMosMapAll = new HashMap<String, UserMO>();
private ArrayList<UserMO> userMOs = new ArrayList<UserMO>();
private UserMO userMO = new UserMO();
private View V;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
V = inflater.inflate(R.layout.contactslistmain, container, false);
context = getActivity().getApplicationContext();
// in contact page click load button get all contacts from device and
// send to server and return matching user
// remove old values from list
userName.clear();
mobileNumber.clear();
// Instantiate Progress Dialog object
prgDialog = new ProgressDialog(getActivity());
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
prgDialog.show();
final String[] mobileNumbers = Utility.getAllContacts(context.getContentResolver());
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return userDelegate.getMatchingExistingUserList(mobileNumbers, context);
}
#Override
protected void onPostExecute(String contactList) {
if (contactList != "null") {
Toast.makeText(context, "contact String" + contactList, Toast.LENGTH_LONG).show();
List<UserMO> userMOs = gson.fromJson(contactList, new TypeToken<List<UserMO>>() {
}.getType());
Toast.makeText(context, "total items of userMo" + userMOs.size(), Toast.LENGTH_LONG).show();
for (UserMO userMO : userMOs) {
userName.add(userMO.getUserName());
mobileNumber.add(userMO.getMobileNumber());
userMosMapAll.put(userMO.getMobileNumber(), userMO);
}
DatabaseHelper dbHelper = new DatabaseHelper(context);
long totalInsertion = dbHelper.insertUserRelationTable(userMOs);
prgDialog.dismiss();
Toast.makeText(context, "total userMos size " + userMOs.size() + "total db insertion size " + totalInsertion, Toast.LENGTH_LONG).show();
ListView contactListView = (ListView) V.findViewById(R.id.contact_List_view);
contactDispAdapter = new ContactDispAdapter();
contactListView.setAdapter(contactDispAdapter);
contactListView.setItemsCanFocus(false);
contactListView.setTextFilterEnabled(true);
contactListView.setOnItemClickListener(contactListView.getOnItemClickListener());
}
}
}.execute(null, null, null);
/*
* btnSend = (Button) V.findViewById(R.id.Btn_Send);
* btnSend.setOnClickListener(new OnClickListener() {
*
* #Override public void onClick(View arg0) { ; for (int i = 0; i <
* mobileNumber.size(); i++) { if
* (contactDispAdapter.mCheckStates.get(i) == true) { if
* (userMosMapAll.containsKey(mobileNumber.get(i).toString())) userMO =
* userMosMapAll.get(mobileNumber.get(i).toString());
* System.out.println("Checked......" + mobileNumber.get(i).toString());
* } else { System.out.println("Not Checked......" +
* mobileNumber.get(i).toString()); } }
*
* Intent chatAct = new Intent(context, ChatActivity.class); // Clears
* History of Activity chatAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
* chatAct.putExtra("userMo", userMO); startActivity(chatAct);
*
* } });
*/
btnAdd = (Button) V.findViewById(R.id.btn_Contact_Add);
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DatabaseHelper dbHelper = new DatabaseHelper(context);
// by default first primary user is current user in sql lite
// user table
final UserMO userMO = dbHelper.getRingeeUserData(1);
System.out.println(".............." + contactDispAdapter.mCheckStates.size());
for (int i = 0; i < mobileNumber.size(); i++) {
if (contactDispAdapter.mCheckStates.get(i) == true) {
if (userMosMapAll.containsKey(mobileNumber.get(i).toString())) {
userMOs.add(userMosMapAll.get(mobileNumber.get(i).toString()));
}
System.out.println("Checked......" + mobileNumber.get(i).toString());
} else {
System.out.println("Not Checked......" + mobileNumber.get(i).toString());
}
}
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return userDelegate.addUserRelationShipMapping(userMOs, Long.toString(userMO.getRingeeUserId()));
}
#Override
protected void onPostExecute(String response) {
Toast.makeText(context, "response is " + response.toString(), Toast.LENGTH_LONG).show();
}
}.execute(null, null, null);
}
});
return V;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
contactDispAdapter.toggle(arg2);
}
// add name and mobile number in adapter to show in contact page
private class ContactDispAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView mobileNumTxtV, userNameTxtV;
CheckBox cb;
ContactDispAdapter() {
mCheckStates = new SparseBooleanArray(userName.size());
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return userName.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return 0;
}
// show list values name and mobile number in contact page
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.contactlist, null,false);
userNameTxtV = (TextView) vi.findViewById(R.id.text);
mobileNumTxtV = (TextView) vi.findViewById(R.id.mobile_number);
cb = (CheckBox) vi.findViewById(R.id.check_box);
userNameTxtV.setText(userName.get(position));
mobileNumTxtV.setText(mobileNumber.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
My problem is only not showing list view and i got no error.
Please help me...
Advance thanks..

Using SharedPreferences to store state of checkbox within a listview

How would I use shared preferences to store the state of my checkbox for the next time the app is opened? I'm using a custom adapter so am guessing it has to be placed inside that but I'm not quite sure.
My Adapter:
public class MobileArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
public MobileArrayAdapter(Context context, String[] values) {
super(context, R.layout.list_adapter, values);
this.context = context;
this.values = values;
for (int i = 0; i < this.getCount(); i++) {
itemChecked.add(i, false);
}
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.list_adapter,
parent, false);
}
// in your code you search for the CheckBox with the id checkBox1 2 times so I assumed that you are referring to the same view.
CheckBox cBox = (CheckBox) rowView.findViewById(R.id.checkBox1);
cBox.setTextColor(0xFFFFFFFF);
cBox.setText(values[position]);
cBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
itemChecked.set(position, true);
// do some operations here
} else {
itemChecked.set(position, false);
// do some operations here
}
}
});
cBox.setChecked(itemChecked.get(position));
return rowView;
}
}
My main Activity:
public class TheKevinAndEricaBoxActivity extends Activity {
/** Called when the activity is first created. */
private String[] myString;
private String list;
private String[] myString2;
private String list2;
private static final Random rgenerator = new Random();
private static final Random rgenerator2 = new Random();
MediaPlayer mp;
final Context mContext = this;
final Context context = this;
private Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources();
addListenerOnButton();
myString = res.getStringArray(R.array.myArray);
list = myString[rgenerator.nextInt(myString.length)];
myString2 = res.getStringArray(R.array.myArray2);
list2 = myString2[rgenerator.nextInt(myString2.length)];
}
public void addListenerOnButton() {
final Context context2 = this;
ImageButton ibg = (ImageButton) findViewById(R.id.buttongallery);
ibg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context2, App2Activity.class);
startActivityForResult(intent, 0);
}
});
ImageButton ib = (ImageButton) findViewById(R.id.imagebutton1);
ib.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View erica) {
AlertDialog.Builder b = new AlertDialog.Builder(
TheKevinAndEricaBoxActivity.this);
b.setMessage(myString[rgenerator.nextInt(myString.length)]);
b.setTitle(R.string.title1);
b.setIcon(R.drawable.menuiconerica);
b.setPositiveButton("Back",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
Dialog d = b.create();
d.show();
}
});
ImageButton ib2 = (ImageButton) findViewById(R.id.imagebutton2);
ib2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View kevin) {
AlertDialog.Builder b = new AlertDialog.Builder(
TheKevinAndEricaBoxActivity.this);
b.setMessage(myString2[rgenerator2.nextInt(myString2.length)]);
b.setTitle(R.string.title2);
b.setIcon(R.drawable.menuiconkevin);
b.setPositiveButton("Back",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
Dialog d = b.create();
d.show();
}
});
ImageButton Ib3 = (ImageButton) findViewById(R.id.imagebutton3);
Ib3.setOnClickListener(new View.OnClickListener() {
public void onClick(View lemonclick) {
mp = MediaPlayer.create(getApplicationContext(),R.raw.lemonspeech);
mp.start();
}
});
button = (Button) findViewById(R.id.button01);
// add button listener
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.list);
dialog.setTitle("The List");
// set the custom dialog components - text, image and button
//TextView text = (TextView) dialog.findViewById(R.id.TextView01);
//text.setText("Did you not read the button? :P i'm not finshed on this yet XD");
ListView listView = (ListView) findViewById(R.id.myList);
String[] values = new String[] { "value1", "value2", };
MobileArrayAdapter mAdapter = new MobileArrayAdapter(getBaseContext(), values);
ListView mListView = (ListView) dialog.findViewById(R.id.myList);
mListView.setAdapter(mAdapter);
Button dialogButton = (Button) dialog.findViewById(R.id.Button01);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
}
In the OnCLickListener for your Button add this:
//...
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.list);
dialog.setTitle("The List");
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefsEditor = prefs.edit();
String currentlyStored = prefs.getString("checked_list", null);
int[] savedStatus = null;
if (currentlyStored != null) {
String[] tmp = currentlyStored.split(",");
savedStatus = new int[tmp.length];
for (int i = 0; i < tmp.length; i++) {
savedStatus[i] = Integer.parseInt(tmp[i]);
}
}
adapter = new MobileArrayAdapter(this, soundnames, savedStatus);
ListView mListView = (ListView) dialog.findViewById(R.id.myList);
mListView.setAdapter(mAdapter);
//...
where:
private SharedPreferences prefs;
private SharedPreferences.Editor prefsEditor;
private MobileArrayAdapter adapter;
are fields in your class with the ListView(the adapter field will hold your adapter object that you set on the list).
Modify the constructor of your custom adapter like this:
public MobileArrayAdapter(Context context, String[] values,
int[] oldStatus) {
super(context, R.layout.adapters_simpleplay_row, values);
this.context = context;
this.values = values;
// make every CheckBox unchecked and then loop through oldStatus(if
// not null)
for (int i = 0; i < this.getCount(); i++) {
itemChecked.add(i, false);
}
if (oldStatus != null) {
for (int j = 0; j < oldStatus.length; j++) {
itemChecked.set(oldStatus[j], true);
}
}
}
Also add the following method in your custom adapter MobileArrayAdapter:
public ArrayList<Boolean> getCheckedStatus() {
return itemChecked;
}
Last in the listener for your dialogButton add this:
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String toStore = "";
ArrayList<Boolean> status = adapter.getCheckedStatus();
for (int i = 0; i < status.size(); i++) {
if (status.get(i)) {
toStore += i + ",";
}
}
prefsEditor.putString("checked_list", toStore.equals("") ? null
: toStore.substring(0, toStore.length() - 1));
prefsEditor.commit();
dialog.dismiss();
}
});
To save selections make a method saveSelections and call it in onPause() and onDestroy(), or create a Button to do the same for you...
Edit:
Since you are using a ListView which is MultipleChoice I suppose you can do this in onCreate...
listView = (ListView) findViewById(R.id.list);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,
android.R.id.text1, names));
Create these three methods outside onCreate()
private void LoadSelections() {
SharedPreferences sp = getPreferences(MODE_PRIVATE);
if (sp.contains(LOAD_LIST)) {
String savedItems = sp.getString(LOAD_LIST, "");
this.selectedItems.addAll(Arrays.asList(savedItems.split(",")));
int count = this.listView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
String currentItem = (String) listView.getAdapter().getItem(i);
if (this.selectedItems.contains(currentItem)) {
this.listView.setItemChecked(i, true);
}
}
}
}
public void SaveSelections() {
SharedPreferences sp = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefEditor = sp.edit();
String savedItems = getSavedItems();
prefEditor.putString(LOAD_LIST, savedItems);
prefEditor.commit();
}
private String getSavedItems() {
String savedItems = "";
int count = listView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (listView.isItemChecked(i)) {
if (savedItems.length() > 0) {
savedItems += "," + listView.getItemAtPosition(i);
} else {
savedItems += listView.getItemAtPosition(i);
}
}
}
return savedItems;
}
Then in onPause(), do this:
#Override
protected void onPause() {
SaveSelections();
super.onPause();
}
Then finally in onCreate call this..
LoadSelections();
You can make a string of 0 & 1 and store it using shared preference. The number of checkboxes (or the number of view) you are using will be the length of string. You save it accordingly.
Eg:
String s[]="0000000000";
for (i=0;i<s.length();i++)
if (checkboxAtLocation(i)==true) //checkboxAtLocation() will return a boolean variable on basis of its checked or not
s[i]=1;
Now store this string.
On starting activity again, use this string to set the checkbox.
This is bit complex to implement but most efficient way as per my knowledge.
I hope it solves your doubt.

Categories

Resources