简体   繁体   中英

How to Set Values in Shared Preferences using Java in Android?

here is the Method:

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;   
    }
}

i am trying to set value "1" in shared Preferences on PostExecuteMethod() of Async Task:

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());  
}

But it still it saves 0 in Variable Here is the 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

You can easily do this in the following way.

First you will need declare the SharedPreferences inside the Activity in this manner:

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
.
.
}

Now when you would like to save the value in background asynch task. Please put this code inside onPostExecute(..) method in this manner:

SharedPreferences.Editor editor=sp.edit();
editor.putInt("VALIDATION", 1);
editor.commit();

It is better to use this code on doInBackground(..) method.

After saving the value, refresh or re-run the Activity. It will show the effect .

Enjoy the code!!

If my answer will help you then please support my answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM