如何在Android中使用Java在共享首选项中设置值?

时间:2014-01-03 11:52:23

标签: java android sharedpreferences

这是方法:

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

1 个答案:

答案 0 :(得分:4)

您可以通过以下方式轻松完成此操作。

首先,您需要以这种方式声明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(..)方法上使用此代码。

保存值后,刷新或重新运行活动。它会显示效果。

享受代码!!

如果我的回答对您有所帮助,那么请支持我的回答。