![](/img/trans.png)
[英]Android: SharedPreferences Issue (Multiple SharedPreferences)
[英]SharedPreferences Android issue
我正在嘗試在我的應用程序中使用SharedPreferences,我需要一點幫助,因為我剛開始使用它。我要做的基本上是:我在主活動中創建SharedPreference對象,然后在第二個活動中有一個列表查看並單擊項目,我使用putInt putInt();
放置整數以發送文本。在新活動中,我有一個按鈕,可在adroid系統中添加sharedpreference。 最后,根據發送給第二個活動的ID,我想在活動編號3中顯示不同的文本。
這是一些代碼:
主要活動 :
SharedPreferences faves = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = faves.edit();
editor.putInt("favorites",0);
editor.commit();
第二項活動:
SharedPreferences favs= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final SharedPreferences.Editor editor = favs.edit();
我要在其中顯示文本的“第三項活動”取決於單擊的項目:
favs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
editor.putInt("favorites", getIntent().getIntExtra("id", 0));
}
});
任何建議如何解決?
您實際上不必創建自己的SharedPreference對象,api Activity.getSharedPreference(name,mode)可以實現。
基本上,它的作用是在應用程序自己的文件夾下創建一個xml文件,每個put ...()都會在xml中添加一個項目,以便您以后可以更新和閱讀,您只需要提供正確的名稱即可。
擁有全局編輯器是一個壞主意,有時它可能會丟失您的數據,因此,每當您要讀取/寫入sharedPreference時,都要獲得一個編輯器。
好吧,首先很難理解這個問題。 在示例代碼中,您嘗試在主活動和第三個活動中存儲值,但似乎從未讀取過值。 然后最后您問“任何建議如何解決該問題?” “那個”代表什么? 您收到錯誤或意外結果嗎? 這是我使用的一些示例代碼。 我有一個帶有某些值的靜態Constants類,可以在我的應用程序的其他部分中重用,但是您明白了。
ApplicationContext context = ApplicationContext.getInstance(); //I use a custom app context but any context will do.
SharedPreferences prefs = context.getSharedPreferences(
Constants.PREFS_FILE_NAME, Activity.MODE_PRIVATE);
prefs.getString("favorites", null);//or any other getter you want to use
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.