我正在爲新聞製作一個android應用程序。 我想提出一個選項,允許某人喜歡新聞或評論,之後,如果有人試圖用同一部手機來完成,應用程序不應該允許這樣做。在我的應用程序中實現sharedPreferences
我知道這應該由sharedpreferences完成但我不知道如何存儲用戶喜歡的新聞的多個ID,以後如何檢查有人想要喜歡的新聞ID是否已保存在sharedpreferences中。
任何幫助將不勝感激。
對不起,我英文很差。
我正在爲新聞製作一個android應用程序。 我想提出一個選項,允許某人喜歡新聞或評論,之後,如果有人試圖用同一部手機來完成,應用程序不應該允許這樣做。在我的應用程序中實現sharedPreferences
我知道這應該由sharedpreferences完成但我不知道如何存儲用戶喜歡的新聞的多個ID,以後如何檢查有人想要喜歡的新聞ID是否已保存在sharedpreferences中。
任何幫助將不勝感激。
對不起,我英文很差。
我不知道如果我的語法是正確的做,就以存儲已經在在SharedPreferences被註釋了news id
和對證的
// Retrieve and hold the contents of the preferences file 'name'
SharedPreferences sp = getSharedPreferences(String name , int mode)
SharedPreferences.Editor spEdit = sp.edit();
// key is ID
spEdit.putInt (String key, int value)
// don't forget
spEdit.commit();
的一種方式。
應用程序共享偏好可以通過getSharedPreferences()
方法...
SharedPreferences prefs = getApplicationContext().getSharedPreferences(
"PrefsFile", MODE_PRIVATE);
中獲取我們需要一個SharedPreferences.Editor
編輯sharedpreference
值...
SharedPreferences.Editor editor = prefs.edit()
Android ShredPreferences DOCS將幫助您更好地瞭解。
對於您的情況,如前所述,您可以使用存儲news id
並每次檢查它以驗證。 (不知道這是最好的方式,但它的一個開始你指出正確的方向。)
可以存儲news id
這樣的...
SharedPreferences prefs = getApplicationContext().getSharedPreferences(
"PrefsFile", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("newsId", 108); // 108 is the news id and "newsId" is the variable name
editor.commit();
可以讀取它回來就好這...
int newsId = 0;
// check if the value exists in sharedpreferences
if(prefs.contains("newsId")) {
newsId = prefs.getInt("newsId", 0);
}
// do your stuff!
希望這有助於!