0

I have a custom ArrayAdapter which is populated by a layout containing a radio button with single choice mode. I managed to save the items added to the ListView and repopulate the ListView when the activity is destroyed but checked radio buttons lose it's state. Have searched online for two days with the only solution found being to save the radio button with SharedPreference. Here is what I have done so far, maybe someone can point me in the right direction. Thanks.

Code:- I used the setOnItemClickListener() to capture the item and the radio button in the listview to save but can't figure out how to repopulate the checked radiobutton from the sharedpreference if that indeed is the correct way.

OnCreate() method code:-

ListView sist = (ListView) findViewById(R.id.list);
adapter = new SAdapter(this, populateArrayList());
sList.setOnItemClickListener(itemListener);
sList.setAdapter(adapter);

onItemClickListener code:-

   private AdapterView.OnItemClickListener itemListener = new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        for (int i= 0; i < parent.getCount(); i++) {
            view = parent.getChildAt(i);
            RadioButton s_rb = (RadioButton) view.findViewById(R.id.s_rdb);
            int checkedState = s_rb.isChecked() ? 1 : 0;
            saveState(s_rb.getId(), checkedState);
        }
    }
};

Code that adds item to the adapter and database:-

InfoHelper helper = new InfoHelper(Number_et.getText().toString(),messageBody_et.getText().toString());
adapter.add(helper);
insertInfoToDB(helper);

My question is how do I save state of radio button given that the list is previously updated from the a database. More codes can be given if this isn't sufficient enough.

CodeZero
  • 179
  • 2
  • 15

1 Answers1

0

1)For this you have to create one table in database which will maintain all radiobutton related data like text of radiobutton also maintain one unique id for data and one boolean flag for each row which stored radiobutton state

2)you can get all data from database into arraylist and set that to adapter.

3)For maintaing radiostate when user clicks on radiobutton according to that update row in database against that id.

Pavan
  • 5,016
  • 1
  • 26
  • 30
  • I didn't get (3) how do I query the database to set the radio button state. Also the radio button doesn't have a text. Am using a textview to display the respective items in the listview – CodeZero Sep 07 '15 at 16:21
  • 1
    when you click on radio button from that position you can get id of that row so against that id update boolean flag that radio button ischecked or not, next time when you get all data from database just check flag and set radio button state according to that – Pavan Sep 08 '15 at 08:07