方法如下:
public class SessionManager {
public static void setStatus(Context context, int value, String key) {
// TODO Auto-generated method stub
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = pref.edit();
editor.putInt(key,value);
editor.commit();
}
public static int getStatus(Context c,String key){
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(c);
int a = pref.getInt(key,0);
return a;
}
}
我正在尝试在异步任务的 PostExecuteMethod()
共享首选项中设置值“1”:
protected void onPostExecute(Void result){
super.onPostExecute(result);
progressDialog.dismiss();
Log.i("Setting Status Variables Value in Customer:",""+AndroidUtil.getStatusForServices());
SessionManager.setStatus(context,1,"status");
Log.i("Setting Status Variables Value in Customer after:",""+AndroidUtil.getStatusForServices());
}
但它仍然在变量中保存 0 这是 Logcat:
01-04 03:31:32.430: I/Setting Status Variables Value in Customer:(20879): 0
01-04 03:31:32.440: I/Setting Status Variables Value in Customer after:(20879): 0
最佳答案
您可以通过以下方式轻松做到这一点。
首先,您需要以这种方式在 Activity 中声明 SharedPreferences:
public class MainActivity extends Activity
{
SharedPreferences sp;
int val=2;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp=this.getSharedPreferences("service_validation", MODE_WORLD_READABLE);
val=sp.getInt("VALIDATION", val);
.
.// you can put here anything code
.
}
.
.// you can put here anything method
.
.
}
现在,当您想在后台异步任务中保存值时。请以这种方式将这段代码放在 onPostExecute(..) 方法中:
SharedPreferences.Editor editor=sp.edit();
editor.putInt("VALIDATION", 1);
editor.commit();
最好在 doInBackground(..) 方法上使用此代码。
保存值后,刷新或重新运行 Activity 。会显示效果。
享受代码!!
如果我的回答对你有帮助,请支持我的回答。
关于java - 如何在 Android 中使用 Java 设置共享首选项的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20903046/