Reputation: 1323
I am developing a mobile application where I need the user object to be available through all the activities and I don't want to send it using the Intent from each activity to the other.
Can anyone help me please ?
Upvotes: 0
Views: 230
Reputation: 2621
Just make that object 'public static'. Then access it in other activities like:
PreviousActivity.userobj
Upvotes: 1
Reputation: 13807
If you could store it in:
I think the SharedPreferences would be much simpler to implement. Here is an example, how you could create a static function, wich you can access from all your activities:
public class UserCreator
{
public static User getUser(Context context)
{
SharedPreferences prefs = context.getSharedPreferences("Name", Context.MODE_PRIVATE);
//Check if the user is already stored, if is, then simply get the data from
//your SharedPreference object.
boolean isValid = prefs.getBoolean("valid", false);
if(isValid)
{
String userName = prefs.getString("username", "");
String passWord = prefs.getString("password", "");
...
return new User(userName, passWord,...);
}
//If not, then store data
else
{
//for example show a dialog here, where the user can log in.
//when you have the data, then:
if(...login successful...)
{
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", "someusername");
editor.putString("password", "somepassword");
editor.putBoolean("valid", true);
...
editor.commit();
}
// Now, if the login was successful, then you can recall this function,
// and it will return a valid user object.
// if it was not, then it will show the login-dialog again.
return getUser(context);
}
}
}
And then from all your activites:
User user = UserCreator.getUser(this);
Upvotes: 3
Reputation: 2579
Write a class which extends Application
class. And put global parameters there. Those parameters will be valid in application context.
Upvotes: 1