如何在多个活动之间共享相同的数据

10

我有一个登录会话ID,多个活动需要使用。如何在多个活动之间共享此公共数据?目前,我通过意图传递数据,但它不能正常工作。对于某些活动,我传递了其他一些数据,导致公共数据丢失。


1
你想要传递什么?请在这里发布你的代码。 - Paresh Mayani
你可以通过Intent共享数据,也可以创建一个全局类并通过它访问数据。通过Intent发送数据非常简单,只需将数据放入intent.putExtra(适当的数据类型)方法中,并在多个活动之间共享即可。 - android
我在我的应用程序中有登录功能,其中我会得到一个sessionid,我需要在所有登录后的活动中使用它,并且还需要将一些其他数据传递给下一个活动(包括sessionid)。现在我正在尝试使用intent,但有时会转向其他活动。 - Harish
9个回答

14

像这样使用共享偏好:

SharedPreferences myprefs= this.getSharedPreferences("user", MODE_WORLD_READABLE);
myprefs.edit().putString("session_id", value).commit();
你可以通过以下方式在你的应用中获取这些信息:
SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
String session_id= myprefs.getString("session_id", null);

当你想从当前活动启动另一个活动时,应该使用意图(Intents)...还有,如果子活动完全依赖于父活动的数据...使用意图。


7
请使用单例模式进行共享。
示例代码:
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;
    }
}

在其他的Activity/类中设置数值为:
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;


2
阅读了有关SharedPreferences和关于在Android中使用Singleton vs Application的讨论, 我得出结论:请驳斥任何结论。
  • SharedPreferences: Good if you plan to keep only primitives, and easy to keep different parcels.
  • Parcelable: A low level solution, with a lot of boilerplate code, you can use in Extras
  • Serializable: If you don't want to bother with Parcelable. See this
  • Singleton: My choice. Simple, quick and no boilerplate. My contribution is to use a Map inside for flexibility.

    public class Config {
    
        private static Config instance;
        private HashMap<String, Object> map;
    
        /*Keep doc about keys and its purpose if needed*/
    
        public static final String TOKEN = "token";
        public static final String SESSION = "sessionId";
    
        /** A bean with A LOT of useful user info */ 
        public static final String USER_BEAN = "userBean";
    
        private Config() {
            map = new HashMap<String, Object>();
        }
    
        public static final Config getInstance() {
            if (instance == null) {
                instance = new Config();
            }
            return instance;
        }
    
        public void setKey(String key, Object value) {
            map.put(key, value);
        }
    
        public Object getKey(String key) {
            return map.get(key);
        }
    }
    
  • Application: Almost the same as singleton, but for some hide-to-me reason, ease the testing and more android standarized way of doing things.


2

1

我不知道你正在处理的代码是什么,但你尝试过像这样吗?

在你当前的活动中,创建一个意图。

Intent i = new Intent(getApplicationContext(), ActivityB.class);
i.putExtra(key, value);
startActivity(i);

然后在另一个活动中检索这些值。

Bundle extras = getIntent().getExtras(); 
if(extras !=null) {
    String value = extras.getString(key);
}

0
你可以将它存储在SharedPreferences或Singleton类中,我建议使用Singleton类。
  • SharedPreferences:

写入值

SharedPreferences mPref= this.getSharedPreferences("session", MODE_WORLD_READABLE);
mPref.edit().putString("session_id", your_session_value).commit();

读取数值

SharedPreferences mPref= getSharedPreferences("session", MODE_WORLD_READABLE);
String sSession_id= mPref.getString("session_id", null);
  • 单例类

    public class Session {
    
        private static Session session = null;
    
        private String mSessionId;
    
        private Session() {
        }
    
        public static Session getInstance() {
            if (session == null) {
                session = new Session();
            }
            return session;
        }
    
        public String getSessionId() {
            return mSessionId;
        }
    
        public void setSessionId(String pSessionId) {
            this.mSessionId = pSessionId;
        }
    }
    

写入单例

Session mSession  = Session.getInstance();
mSession.setSessionId("your_session_id");

从单例读取

Session mSession  = Session.getInstance();
String mSessionId = mSession.getSessionId();

0

一种方法是扩展Application,然后在您的活动中调用getApplication这个网站有一些示例。


不是很好的解决方案,但它是很久以前编写的...所以我敦促作者改进它 ;) - Ewoks

0
我通常的做法是从Activity扩展一个全局类,然后从它扩展所有用户将与之交互的实际活动。这就是我从一些“学习为Android编码”的书籍中学到的方法。
这与使用Application类几乎相同。

内存泄漏怎么办?你如何共享数据? - Nico

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接