CristianoWilson
CristianoWilson

Reputation: 143

Save checkbox state with sharedpreferences

In my code I added sharedpreferences and all but it doesnt save anything. What I need is that when a user ticks a few checkboxes the checkboxes should still be the same when the app is restarted or when the back button is pressed.

Here is my code:

public class MyActivity3 extends Activity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my3);
    Button m = (Button) findViewById(R.id.button3);
    tv = (TextView) findViewById(R.id.textViewcat);
    Typeface typeface = Typeface.createFromAsset(getAssets(), "BebasNeue Bold.ttf");
    tv.setTypeface(typeface);

        SharedPreferences sharedPreferences=getSharedPreferences("ticks", Context.MODE_PRIVATE);
    sharedPreferences.getString("name","");

    //LISTVIEW IS BELOW! Still needs check checkbox onItemClick and save state on exit and back pressed!
    String listArray[] = new String[] { "All", "Friends & Family", "Sports", "Outside",
            "At School", "Fitness", "Photography", "Food", "Beach", "Money" };
    ListView listView = (ListView) findViewById(R.id.listView);
    List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
    for (int i = 0; i <= listArray.length - 1; i++) {
       HashMap<String, String> hm = new HashMap<String, String>();
        hm.put("title", listArray[i]);
        aList.add(hm);
    }
    String[] sfrm = { "title"};
    int[] sto = { R.id.title};
    SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList,
            R.layout.row_layout, sfrm, sto);
   listView.setAdapter(adapter);
   listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

       @Override
       public void onItemClick(AdapterView<?> arg0, View view,
                               int position, long id) {
           switch (position) {
           }
       }
   });
}

public void save(View view)
{
        SharedPreferences sharedPreferences=getSharedPreferences("ticks", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor=sharedPreferences.edit();
    editor.putString("key","");
    editor.commit();
}
@Override
public void onBackPressed() {
    super.onBackPressed();
    overridePendingTransition(R.anim.animation8, R.anim.animation7);
    }
}

here's my .xml where the checkbox has an onClick="save" :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >

<com.MR.brd.CustomTextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:text="Country name"
    android:textColor="#FFFFFF"
    android:textSize="48sp" />

<CheckBox android:id="@+id/chk"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@drawable/custom_checkbox_design"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:onClick="save"/>


</RelativeLayout>

Am I doing something wrong? I followed a tutorial on the sharedpreferences but clearly I am not getting it somehow...

Upvotes: 0

Views: 1926

Answers (2)

Jose Rodriguez
Jose Rodriguez

Reputation: 10152

You are not saving nothing on shared preference:

editor.putString("key","");

always save a empty string. And on onCreate you are not using a retrieved string and you must use the same key.

sharedPreferences.getString("name","");

You must change "name" for "key".

Also you are not catching the event when checked state change on CheckBox. In some part of your code, you must set an OnCheckedChangeListener for checkboxes, because setOnItemClickListener is fired when one view of ListView is selected, not when a checkBox is selected or deselected.

Modify your onCreate Activity method, and remove save method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my3);
    Button m = (Button) findViewById(R.id.button3);
    tv = (TextView) findViewById(R.id.textViewcat);
    Typeface typeface = Typeface.createFromAsset(getAssets(), "BebasNeue Bold.ttf");
    tv.setTypeface(typeface);

    String[] listArray = new String[] { "All", "Friends & Family", "Sports", "Outside", "At School", "Fitness", "Photography", "Food", "Beach", "Money" };
    SharedPreferences sharedPreferences = getSharedPreferences("status", MODE_PRIVATE);

    Boolean[] checkedStatus = new Boolean[listArray.length];
    for ( int index = 0; index < checkedStatus.length; index++)
        checkedStatus[index] = sharedPreferences.getBoolean(Integer.toString(index), false);

    ListView listView = (ListView) findViewById(R.id.listview);
    MyAdapter adapter = new MyAdapter(this, R.layout.row_layout, listArray, checkedStatus);
    listView.setAdapter(adapter);
}

And create MyAdapter class:

public class MyAdapter extends ArrayAdapter<String> implements CompoundButton.OnCheckedChangeListener{

String[] values;
Boolean[] checkedStatus;

public MyAdapter(Context context, int resource, String[] values, Boolean[] checkedStatus) {
    super(context, resource, values);

    this.values = values;
    this.checkedStatus = checkedStatus;
}

@Override
public int getCount() {
    return values.length;
}

@Override
public String getItem(int position) {
    return values[position];
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if(view == null){
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.row_layout, null);
    }

    TextView textView = (TextView) view.findViewById(R.id.title);
    textView.setText(values[position]);

    CheckBox box = (CheckBox) view.findViewById(R.id.chk);
    box.setTag(position);
    box.setOnCheckedChangeListener(this);
    box.setChecked(checkedStatus[position]);

    return view;
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    Integer index = (Integer) buttonView.getTag();
    checkedStatus[index] = isChecked;
    String key = index.toString();

    SharedPreferences sharedPreferences=getContext().getSharedPreferences("status", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor=sharedPreferences.edit();
    editor.putBoolean(key,isChecked);
    editor.apply();
}

}

Also, modify a checkbox declaration on .xml file:

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:text="Country name"
    android:textColor="#FFFFFF"
    android:textSize="48sp" />

<CheckBox android:id="@+id/chk"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@drawable/custom_checkbox_design"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"/>

removing,

android:onClick="save"

Upvotes: 1

ligi
ligi

Reputation: 39519

if you would like to save a lot of code ( and possible bugs ) you can use AXT - then it looks like this:

AXT.at(yourCheckBox).careForCheckedStatePersistence("some_tag");

the tag in your case needs the position of your checkbox.

https://github.com/ligi/AXT

Upvotes: 0

Related Questions