保存Int(共享首选项)的值

时间:2016-09-02 01:56:54

标签: java android xml

我是java的新手。我做了一个计数器,当用户按住按钮时它会上升。我希望应用程序以它离开的位置的int值开始。我知道SharedPreference是要走的路,但我不知道如何使用它。我不知道在哪里放置SharedPreference的哪一部分。谢谢。

public class MainActivity extends AppCompatActivity {
Button button;
int count = 1;
TextView text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button) findViewById(R.id.button);
    text = (TextView) findViewById(R.id.textView);

    button.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
           count++;
            text.setText(String.valueOf(count));
        return false;
        }
    });

}

}

3 个答案:

答案 0 :(得分:0)

将以下功能添加到您的活动中

 public int getValue(String key) {
        SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
        int value = sharedPref.getInt(key, 0);
        return value;
 }
 public void saveValue(String key, int value) {
        SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(key, value);
        editor.commit();
 }

您的onCreate()方法

中添加了一些代码
final String key = "somekey";
count  = getValue(key); //get value from sharedPreference
button = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.textView);
text.setText(String.valueOf(count)); // set it first
button.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View view) {
        count++;
        saveValue(key,count);
        text.setText(String.valueOf(count));
        return false;
    }
});

答案 1 :(得分:0)

尝试转动

int count = 1;

static int count = 1;

我也有点像Java noobie,所以这可能会或可能不会起作用。

答案 2 :(得分:0)

您可以这样做,在销毁活动时将count保存在SharedPreference中,并在创建时从SharedPreference中读取值:

public class MainActivity extends AppCompatActivity {
    Button button;
    int count = 1;
    TextView text;
    SharedPreferences sh;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        text = (TextView) findViewById(R.id.textView);

        sh = getSharedPreferences("sh_name", MODE_PRIVATE);
        count = sh.getInt("count", 1);

        button.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                count++;
                text.setText(String.valueOf(count));
                return false;
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        sh.edit().putInt("count", count).apply();
    }
}