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 is the sender and
B is the recipient. Use the following code in activity
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(A.this); SharedPreferences.Editor editor = prefs.edit(); editor.putString("string", "This is a string."); editor.putInt("number", 50); editor.commit();
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
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
For further details on
SharedPreferences, the official documentation can be checked at this link.