Passing Data using SharedPreferences

Sometimes while passing data between two activities, we are just concerned with passing data and not launching the activity to which the data is passed. SharedPreferences make this data passing easier without necessitating launch of the recipient activity. The usage is discussed briefly below:

Say you have two activities A and B where A is the sender and B is the recipient. Use the following code in activity A.

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(A.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("string", "This is a string.");
editor.putInt("number", 50);
editor.commit();

In activity B, use the following code to receive the variables from sender activity:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String s = prefs.getString("string", "hello");
Integer i = prefs.getInt("number", 0);

Default values should be set in the getString(), getInt() or any of the get methods used in the recipient activity. The variables in which the received values are stored can be used for further processing in activity B.

For further details on SharedPreferences, the official documentation can be checked at this link.

2 comments / Add your comment below

Leave a Reply

Follow

Get notified with the latest posts

Plugin Supporter WordPress Post Navigation
%d bloggers like this: