Reputation: 133
I have a brain freeze as that obvious feature doesn't see to work for me and any help would be appreciated. Here is what I do:
Both activities seem to have their own personal instance of SharedPreferences. Is there a better solution to sharing variables across activites, what am I doing here wrong?
Thank you
//
// Activity A
//
SharedPreferences prefToDos = this.getApplicationContext().getSharedPreferences("MyPref_ToDos", MODE_PRIVATE);
SharedPreferences.Editor editorToDos = prefToDos.edit();
// Works OK I get 2 items for that activity
JSONArray jArrToDos = new JSONArray(prefToDos.getString("todos",null));
//
// Activity B
//
SharedPreferences prefToDos = this.getApplicationContext().getSharedPreferences("MyPref_ToDos", MODE_PRIVATE);
SharedPreferences.Editor editorToDos = prefToDos.edit();
// Works OK I get 2 items for that activity
JSONArray jArrToDos = new JSONArray(prefToDos.getString("todos",null));
//Yes button clicked
jArrToDos.remove(todoIndex);
editorToDos.putString("todos",jArrToDos.toString());
editorToDos.commit();
finish();
//
// Back to Activity A to onResume()
//
SharedPreferences prefToDos = this.getApplicationContext().getSharedPreferences("MyPref_ToDos", MODE_PRIVATE);
SharedPreferences.Editor editorToDos = prefToDos.edit();
// DOESN'T WORK I still get 2 items for that activity
JSONArray jArrToDos = new JSONArray(prefToDos.getString("todos",null));
Upvotes: 0
Views: 149
Reputation: 798
i have another solution rather then delete sharepreference store "" (blank)which field you want to delete blank . when you come back next activity you will not get value or you will get "" just put one if else in your code and validate .its working for me.
Upvotes: 0
Reputation: 1887
First try to use apply() instead of commit(). Other things from your code seem to be correct.
Alternative to SharedPreferences
, You can
Start the Activity B using startActivityForResult(Intent, int, Bundle)
And pass the string through intent by setResult (int resultCode, Intent data)
Retrieve the string from intent in Activity A using onActivityResult (int requestCode, int resultCode, Intent data)
Upvotes: 2
Reputation: 496
Nothing seems to be wrong with your code. Try to print what you are getting after performing jArrToDos.remove(todoIndex);
and check if the item is getting removed from the array.
To pass data from one activity to other you can use Intents, which is more preferable for local temporary sharing.
Example:
Intent intent = new Intent(getBaseContext(), MyActivity.class);
intent.putExtra(KeyForTheValueToPass, ValueToPass);
startActivity(intent);
Upvotes: 0