Search code examples
javaandroidstring-comparisonandroid-dialogandroid-sharedpreferences

Shared preference value not reflecting in app


I am getting the saved value in shared preference but not being able to update TextView or ImageView on basis of the value in shared preference.

Here is my code for Shared Pref's class :

public class SharedPref {

public SharedPref(Context context){
}

public void saveString(Context context,String key, String value) {
    SharedPreferences sharedPref = context.getSharedPreferences(key,Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString(key, value);
    editor.apply();
}

public String getString(Context context,String key){
    SharedPreferences sharedPref = context.getSharedPreferences(key, Context.MODE_PRIVATE);
    String value = sharedPref.getString(key, "");

    return value;
}
}

Here is the code to save & retrieve value of preference :

@Override
public void onNumberOfOversClick(String _overs) {

    final SharedPref sharedPref = new SharedPref(MainActivity.this);

    String local = sharedPref.getString(MainActivity.this,"overs");

    // custom dialog
    final Dialog dialog = new Dialog(MainActivity.this);
    dialog.setContentView(R.layout.custom_overs_dialog);
    dialog.setTitle("Choose Overs...");

    TextView text_3 = (TextView) dialog.findViewById(R.id.text_3);
    TextView text_5 = (TextView) dialog.findViewById(R.id.text_5);

    final ImageView icon_tick_3 = (ImageView) dialog.findViewById(R.id.icon_tick_3);
    final ImageView icon_tick_5 = (ImageView) dialog.findViewById(R.id.icon_tick_5);

    if(local == "3" || local == "")
    {
        icon_tick_3.setImageResource(R.drawable.tick);
    }
    else if(local == "5")
    {
        icon_tick_5.setImageResource(R.drawable.tick);
    }
    dialog.show();

    text_3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            icon_tick_3.setVisibility(View.VISIBLE);
            icon_tick_3.setImageResource(R.drawable.tick);
            icon_tick_5.setVisibility(View.INVISIBLE);
            sharedPref.saveString(MainActivity.this, "overs", "3");
        }
    });

    text_5.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            icon_tick_3.setVisibility(View.INVISIBLE);
            icon_tick_5.setVisibility(View.VISIBLE);
            icon_tick_5.setImageResource(R.drawable.tick);
            sharedPref.saveString(MainActivity.this, "overs", "5");
        }
    });
}

As you can see I am able to retrieve value in String variable local, but ImageView is not updated to R.drawable.tick when I re-open the app.


Solution

  • String comparison the way you are working right now. You need to change equals statement into this

     if(local.equals("3") || local.equals(""))
    {
        icon_tick_3.setImageResource(R.drawable.tick);
    }