Adam
Adam

Reputation: 418

Shared preferences wont save before closing the app or activity

I am making an activity that will edit the shared preferences just when the activity starts before it executes any functions. I am stuck and dont know how to. My app only edits the shared preferences when i close the app or go back to another activity. I want to edit them when the activity starts without executing any function ie checkpreferences();.Precisely How to edit the shared preferences on start of activity?

public class MyActivity extends Activity {

private SharedPreferences app_preferences;

@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  // Get the app's shared preferences
  app_preferences = PreferenceManager.getDefaultSharedPreferences(this);

  final int id = 42;

  int idd = app_preferences.getInt("idd", 0);
  // I am Stuck in this part
  SharedPreferences.Editor editor = app_preferences.edit();  
    editor.putInt("idd", 43);
    editor.commit(); // Very important

  final int iddd = idd;
  checkpreferences(id, iddd);

        }

private void checkpreferences(int di, int dii) {
      if(di == dii) {
        Toast.makeText(AudioActivity.this,"id is same"+dii+"="+di , Toast.LENGTH_SHORT).show();
      }else{

            Toast.makeText(AudioActivity.this,"id is different"+dii+"!="+di, Toast.LENGTH_SHORT).show();

      }

}

 }

Upvotes: 1

Views: 733

Answers (1)

Avi Kumar
Avi Kumar

Reputation: 4433

I think the error is here you are tryinh to fetvh the value of shared preference before saving it

// Fetching of value

    int idd = app_preferences.getInt("idd", 0);

Log.e("value " , " is "  + idd);
as at this time there shall be no value in  preference 

    // and commitng after it 



      SharedPreferences.Editor editor = app_preferences.edit();  
        editor.putInt("idd", 43);
        editor.commit(); // Very important

you should save preference before fetching and to assure it print the logs as well

Upvotes: 2

Related Questions