Storing an int value using Shared preferences

自作多情 提交于 2021-02-18 18:52:57

问题


I have an int "flag" variable , which will have two possible int values , 0 & 1.

Main theme of the app here is : Ask user yes or no?

If user selects YES, assign int=1. else if Selects No, assign int=0;

I am achieving this using:

public static int flag;


    @Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.flag0:
        flag=0;
        System.err.println("Flag : " + flag);
        break;
    case R.id.flag1:
        flag=1;
        System.err.println("Flag : " + flag);
        break;
    default:
        break;
    }
}

My problem is here: it is ok & saving the preference upto my Application is running either foreground or background.

and once if we close/kill the application, all the stored preferences are being cleared i.e., setting to the default value of Zero.

As I just started working on STORAGE Options, I just tried to implement SHARED PREFERENCES, which still having the same above problem . the method I used to store the int value using Shared preferences is ;

Edit: I just tried the below answers but in vain & here is my total code I am posting it , will be helpful for you to test(Maybe)

xml File:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/text"
    android:textSize="30sp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

<Button android:id="@+id/flag0"
    android:layout_marginTop="10dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/text"
    android:text="set to 0"/>

<Button android:id="@+id/flag1"
    android:layout_marginTop="10dp"
    android:layout_below="@+id/text"
    android:layout_toRightOf="@+id/flag0"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="set to 1"/>

<Button android:id="@+id/test0"
    android:layout_marginTop="10dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/flag1"
    android:text="Test for 0"/>

MainActivity:

public class MainActivity extends Activity implements OnClickListener {
TextView textView;
Button bt1,bt2,testbt1;
public static int flag;
SharedPreferences pref;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView) findViewById(R.id.text);
    bt1 = (Button) findViewById(R.id.flag0);
    bt2 = (Button) findViewById(R.id.flag1);
    testbt1 = (Button) findViewById(R.id.test0);

    bt1.setOnClickListener(this);
    bt2.setOnClickListener(this);
    testbt1.setOnClickListener(this);


    pref=getSharedPreferences("Sai", MODE_PRIVATE);
    pref.getInt("lang_us", 0);
    System.err.println("Flag Value in Main method : " + flag);
}
public void saveFlag(){

    pref=getSharedPreferences("Sai",MODE_PRIVATE);
    Editor editor = pref.edit();
    editor.putInt("lang_us", flag);
    editor.commit();

}
@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.flag0:
        flag=0;
        saveFlag();
        System.err.println("Flag : " + flag);
        break;
    case R.id.flag1:
        flag=1;
        saveFlag();
        System.err.println("Flag : " + flag);
        break;
    case R.id.test0:
        System.err.println("Flag : " + flag);
        if (flag == 0) {
            textView.setText("flag is zero");
        } else {
            textView.setText("flag is not zero");
        }

        break;

    default:
        break;
    }
}

}

Where is it going wrong?


回答1:


Your way of doing it is wrong

1.> Use Mode_PRIVATE(Used when you want your shared preference file should be accessible only to your app) instead of MODE_WORLD_WRITABLE(Used when you want your shared preference file should be accessible only outside your app)

2.> Make a method to save the state of flag

public void saveFlag(){

    pref=getSharedPreferences("Sai",Context.MODE_PRIVATE);
    Editor editor = pref.edit();
    editor.putInt("lang_us", flag);
    editor.commit();

}

3.> Call this method whenever you change flag

     @Override
     public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.flag0:
    flag=0;
    saveFlag();
    System.err.println("Flag : " + flag);
    break;
case R.id.flag1:
    flag=1;
    saveFlag();
    System.err.println("Flag : " + flag);
    break;
default:
    break;
}

4.> Then in your onCreate() method you should retrieve this value.

pref=getSharedPreferences("Sai",Context.MODE_PRIVATE);
flag  = prefs.getInt("lang_us", 0); 



回答2:


Put this code in your onClick method:

pref=getSharedPreferences("Sai",Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putInt("lang_us", flag);
editor.commit();

Then in your onCreate() method you should retrieve this value.

  pref=getSharedPreferences("Sai",Context.MODE_PRIVATE);
  flag  =prefs.getInt("lang_us", 0); 

flag should now have the value you saved.




回答3:


Try this:

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor sharedEditor = preferences.edit();

   sharedEditor.putInt("lang_us", flag);
   sharedEditor.commit();

It works for me.

And dont forget to retrieve the values with sharedEditor.getInt(..);




回答4:


Why not you use Boolean SharedPreferences I think that is best in your case.

This is an example

SharedPreferences prefs = PreferenceManager
                    .getDefaultSharedPreferences(this);
            if (!prefs.getBoolean("firstTime", false)) {

                SharedPreferences.Editor editor = prefs.edit();
                editor.putBoolean("firstTime", true);
                editor.commit();
            }


来源:https://stackoverflow.com/questions/18757299/storing-an-int-value-using-shared-preferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!