我有一个登录会话ID,需要使用多个活动.如何在多个活动之间共享此公共数据?目前,我正在Intent中传递数据,但它无法正常工作.对于某些活动,我传递了一些其他数据,并且丢失了常见数据.
Pra*_*hat 14
使用这样的共享首选项:
SharedPreferences myprefs= this.getSharedPreferences("user", MODE_WORLD_READABLE);
myprefs.edit().putString("session_id", value).commit();
Run Code Online (Sandbox Code Playgroud)
您可以在您的应用中检索此信息,如下所示:
SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
String session_id= myprefs.getString("session_id", null);
Run Code Online (Sandbox Code Playgroud)
当您想要从当前活动开始另一个活动时,您应该使用意图...如果子活动完全依赖于来自父活动的数据...也可以使用意图
使用Singleton类进行共享.
示例代码
public class Category {
private static final Category INSTANCE = new Category();
public String categoryName = "";
public int categoryColor = 0;
public boolean status = false;
// Private constructor prevents instantiation from other classes
private Category() {}
public static Category getInstance() {
return INSTANCE;
}
}
Run Code Online (Sandbox Code Playgroud)
在其他Activity/Class中将值设置为:
Category cat;
cat=Category.getInstance();
cat.categoryName="some name";
cat.status=ture;
for getting the values every where you want in your application.
Category cat;
cat=Category.getInstance();
String sq=cat.categoryName;
boolean stat=cat.status;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28635 次 |
最近记录: |