Search code examples
androidandroid-arrayadapterandroid-radiobuttonandroid-database

Saving radio button state and repopulating the state


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.


Solution

  • 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.