我有一个小部件,我想从设置活动中设置一些值。 我已使用以下代码将值保存到共享pref:
MainActivity.editor.putInt("selected_theme", 1);
MainActivity.editor.commit();
在remoteview类中,我在onUpdate方法中做了这样的事情:
MainActivity.prefs = context.getSharedPreferences("prefs", Context.MODE_PRIVATE );
MainActivity.editor = MainActivity.prefs.edit();
int saved_value = MainActivity.prefs.getInt("selected_theme", 0);
Log.d("ggg", "receiver: " + saved_value);
然而它总是给我值 0 ,这是默认值。我需要从共享首选项中获取整数值,如 1,2,3 ...... ,这些值已在Activity类中完成。 在此先感谢:)
答案 0 :(得分:2)
您应始终使用Utility Classes
来执行数据持久性(共享首选项,数据库,序列化等)等任务。
我在这里为您提供一个基本模板:
GenericUtility.class :
package com.your.packagename;
import android.content.Context;
import android.content.SharedPreferences;
public class GenericUtility {
public static int getIntFromSharedPrefsForKey(String key, Context context)
{
int selectedValue = 0;
SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
selectedValue = prefs.getInt(key, 0);
return selectedValue;
}
public static boolean setIntToSharedPrefsForKey(String key, int value, Context context)
{
boolean savedSuccessfully = false;
SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
try
{
editor.putInt(key, value);
editor.apply();
savedSuccessfully = true;
}
catch (Exception e)
{
savedSuccessfully = false;
}
return savedSuccessfully;
}
public static String getStringFromSharedPrefsForKey(String key, Context context)
{
String selectedValue = "";
SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
selectedValue = prefs.getString(key, "");
return selectedValue;
}
public static boolean setStringToSharedPrefsForKey(String key, String value, Context context)
{
boolean savedSuccessfully = false;
SharedPreferences prefs = context.getSharedPreferences("com.your.packagename", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
try
{
editor.putString(key, value);
editor.apply();
savedSuccessfully = true;
}
catch (Exception e)
{
savedSuccessfully = false;
}
return savedSuccessfully;
}
}
用法示例:
用于在共享首选项中保存数据:
GenericUtility.setIntToSharedPrefsForKey("selected_theme", 1, getApplicationContext());
OR
GenericUtility.setIntToSharedPrefsForKey("selected_theme", 1, MyActivity.this));
从共享首选项中检索数据:
int selectedValue = GenericUtility.getIntFromSharedPrefsForKey("selected_theme", getApplicationContext());
OR
int selectedValue = GenericUtility.getIntFromSharedPrefsForKey("selected_theme", MyActivity.this);
我希望这会有所帮助。