我正在开发一个移动应用程序,其中我需要用户对象在所有活动中都可用,并且我不想使用每个活动的意图将其发送到另一个活动。
有谁能帮帮我吗?
发布于 2012-08-27 22:37:21
只需将对象设置为'public static‘即可。然后在其他活动中访问它,如:
PreviousActivity.userobj发布于 2012-08-26 19:10:11
如果您可以将其存储在:
我认为SharedPreferences的实现会简单得多。这里有一个例子,你如何创建一个静态函数,你可以从你的所有活动中访问:
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);
}
}
}然后从你所有的活动中:
User user = UserCreator.getUser(this);发布于 2012-08-26 19:02:16
编写一个扩展Application类的类。并将全局参数放在那里。这些参数将在应用程序上下文中有效。
https://stackoverflow.com/questions/12129522
复制相似问题