2015-02-12 66 views
1

在我的應用程序中,用戶可以爲多個人添加名稱和年齡。很可能它只會在2或3左右。我想將它們存儲在共享偏好中。我設置了一個計數器來跟蹤有多少人被存儲以及管理哪個鍵與哪個值相關。我接受了edittext輸入並將其放入一個字符串中,然後將其放入共享首選項中,然後添加到櫃檯上,以便我知道這是第一個人,並且可以使用「name1」訪問該人員。增加值後遞增共享首選項鍵

//this is in the class 
public int count = 1; 

//this is in the main 
SharedPreferences sharedPreferences = getSharedPreferences("registerData", Context.MODE_PRIVATE); 
      SharedPreferences.Editor myEditor = sharedPreferences.edit(); 

      myEditor.putString("Name"+count, name); 
      myEditor.putString("Age"+count, age); 

除非我誤會,否則應該將字符串「name」放入「Name1」中。

然後我去嘗試訪問它與其他活動......

SharedPreferences sharedPreferences = getSharedPreferences("registerData", Context.MODE_PRIVATE); 
    String name = sharedPreferences.getString("Name"+count,""); 
    String age = sharedPreferences.getString("Age"+count,""); 

,那麼我會更新計數器將被添加下一個人之前改變的關鍵在於「名稱2」「AGE2歲」 , 等等。

每當我嘗試將字符串設置爲textview時,它們都顯示爲空白。這意味着它不一樣的字符串來訪問密鑰。 putString必須得到「Name1」,因爲即使當我嘗試訪問getString(「Name」,「」)時,它仍然是空白的。有什麼我做錯了或失蹤。或者有更好的方法來做到這一點?謝謝。

+1

*等* ....換句話說,你需要的,因爲你已經增加了計數,現在試圖獲取字符串名稱數據庫不sharedpreferences – Selvin 2015-02-12 04:05:51

+0

「+因爲這會導致名稱2 – 2015-02-12 04:08:02

+0

我只是在質疑使用數據庫,因爲將不會有超過3人加入到它中。除了sharedpreferences以外,是否值得這樣做? – ZWis212 2015-02-16 03:59:36

回答

1
 SharedPreferences sharedPreferences = getSharedPreferences("registerData",Context.MODE_PRIVATE); 
     SharedPreferences.Editor myEditor = sharedPreferences.edit(); 

     myEditor.putString("Name"+count, name); 
     myEditor.putString("Age"+count, age); 
     myEditor.apply();//returns nothing,don't forgot to commit changes 

也可以使用

 myEditor.commit() //returns true if the save works, false otherwise. 
+1

不要在ui上使用提交線程。使用apply()代替.http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply() – Xyaren 2015-02-12 04:33:04

+0

謝謝@Xyaren。 – Nooh 2015-02-12 04:36:55

1

有什麼我做錯了或失蹤。或者有更好的方法來做到這一點?

如果SharedPreferences鍵名稱是動態的,那麼你應該使用SharedPreferences.getAll()它會返回在選擇優先使用的所有密鑰:

Map<String, ?> allKeys = sharedPreferences.getAll(); 

現在通過allKeys遍歷檢查鍵名,並從Map.Entry喜歡鍵關聯獲取值:

for (Map.Entry<String, ?> entry : allKeys.entrySet()) { 
    Log.v("TAG","Key Name :" entry.getKey()); 
    Log.v("TAG","Key Value :" entry.getValue()); 
} 
1

您必須在更改共享首選項後調用apply()秒。

... 
myEditor.apply(); 

但是,共享首選項並不意味着存儲與內容相關的數據。考慮使用更合適的解決方案,如數據庫。