Reputation: 2811
My work flow is as follows:
LoginActivity -> ActivityB -> ActivityC -> ActivityD
I'd like to pass data from LoginActivity to ActivityD, but not go directly to ActivityD. ie, I'd like to pass data from LoginActivity to ActivityD, but go to ActivityB and ActivityC before I get to ActivityD and get the data there.
Is this possible?
I know to pass data from one activity to another the code is as follows:
Intent i = new Intent(getApplicationContext(), AnotherActivity.class);
i.putExtra("key", (int)1);
i.putExtra("something", something);
startActivity(i);
And in AnotherActivity
you do the following to get the data:
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
String var = extras.getString("something");
}
But this does not work if I want to delay going straight to the activity. So if I take out startActivity(i);
and go to another activity. The program crashes when tyring get the data in the final activity. The good old NullPointerExeption pops up.
Does anyone know a way of doing what I've described? Get the data from one activity to another, but not go (or start) that activity right away?
Upvotes: 0
Views: 456
Reputation: 3193
You can do it by two approaches. 1 ) Shared Preferences
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key", "Value");
editor.commit();
// fetching Shared Pref .
String value = pref.getString("key" , "");
2 ) Defining application level class and access same.
Class Consisting of getter and setter functions for variables. setting in one activity and getting into another activity.
Upvotes: 0
Reputation: 1665
If you want to pass the data like this, it is preferable to use shared preferences. It is simple to use and you can use the data any where in your program.
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key", (int)1);
editor.putString("something", something);
editor.commit();
at the time of receiving:
SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);
String something = prefs.getString("something", null);
Upvotes: 2
Reputation: 2889
I can think of two options to solving your problem. One is that you just keep passing the data, which means in ACtivityB and ACtivityC you need to run the code
Intent i = new Intent(getApplicationContext(), AnotherActivity.class);
i.putExtra("key", (int)1);
i.putExtra("something", something);
startActivity(i);
The other option (which I think is more practical) is to create a seperate class with static members and static methods for accessing the data. It could look something like this
public class SharedResource{
public static String mPassedName;
}
This class would not necessarily be threadsafe so be forewarned, if you have mutlithreaded access take the appropriate precautions.
Upvotes: 0