这是方法:
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 。它将显示效果。
享受代码!!
如果我的回答对您有帮助,请支持我的回答。