Search code examples
androidandroid-activityandroid-preferencespreferenceactivity

How to close activity with old preferences data?


I am developing an android app with preferences. I have 2 activities: MainActivity and PrefActivity. At MainActivity I am show textview with value from preferences. At PrefActivity I change this value from ListPreference. When i press back button in the PrefActivity, it is refer me to the MainActivity with text of new value from preferences. But if i press back button once more, then it refer me to the old MainActivity with text of old value from preference. How I can escape from the old MainActivity? Code of retrieve value from preferences:

sp = PreferenceManager.getDefaultSharedPreferences(this);
String sharedpreferences = sp.getString("sharedpreference", "");
TextView tv_info = findviewbyid(R.id.tvinfo);
tv_info.settext(sharedpreferences);

Solution

  • Kindly check the below logic and implement.

    Your MainActivity

    if (id == R.id.action_settings) { 
    Intent intent = new Intent(MainActivity.this, PrefActivity.class); 
    intent.putExtra("fwflag","from_menu_item"); 
    startActivity(intent);
    }
    

    Remove your implementation of setting data from the shared preference from oncreate method, and paste it to the onResume method:

    @Override
    public void onResume() {
        super.onResume();
    sp = PreferenceManager.getDefaultSharedPreferences(this);
    String sharedpreferences = sp.getString("sharedpreference", "");
    TextView tv_info = findviewbyid(R.id.tvinfo);
    tv_info.settext(sharedpreferences);
    }
    

    Then in your PrefActivity

    update the below code - remove onbackpressed() and put finish().

    toolbar.setNavigationOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
    finish(); 
    } 
    

    Under PrefFragment

    remove the below code

    Intent intent = new Intent(PrefActivity.this, MainActivity.class); 
    startActivity(intent); 
    

    and just put

    finish(); 
    

    and now try.

    Let me know for queries.