Android 在我的应用程序中实现SharedReferences
我正在为新闻制作一个android应用程序。 我想做一个选项,允许某人喜欢一条新闻或一条评论,稍后,如果有人试图从同一部手机上这样做,应用程序不应该允许这样做 我知道这应该通过SharedReferences完成,但我不知道如何存储用户喜欢的多个新闻ID,以及稍后如何检查有人喜欢的新闻ID是否已保存在SharedReferences中 任何帮助都将不胜感激Android 在我的应用程序中实现SharedReferences,android,sharedpreferences,Android,Sharedpreferences,我正在为新闻制作一个android应用程序。 我想做一个选项,允许某人喜欢一条新闻或一条评论,稍后,如果有人试图从同一部手机上这样做,应用程序不应该允许这样做 我知道这应该通过SharedReferences完成,但我不知道如何存储用户喜欢的多个新闻ID,以及稍后如何检查有人喜欢的新闻ID是否已保存在SharedReferences中 任何帮助都将不胜感激 对不起,我的英语很差。我不确定我的语法是否正确 // Retrieve and hold the contents of the prefe
对不起,我的英语很差。我不确定我的语法是否正确
// 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();
一种方法是存储SharedReferences中已注释的
新闻id
,并对照它进行检查
可以使用getSharedReferences()
方法获取应用程序共享首选项
SharedPreferences prefs = getApplicationContext().getSharedPreferences(
"PrefsFile", MODE_PRIVATE);
我们需要一个SharedReference.Editor
来编辑SharedReference
值
SharedPreferences.Editor editor = prefs.edit()
会帮助你更好地理解
对于您的情况,如前所述,您可以使用存储新闻id
,并在每次验证时对其进行检查。(不确定这是否是最好的方式,但这是为您指明正确方向的开始。)
您可以像这样存储新闻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!
你可以像这样把它读回
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!
希望这有帮助