Android的共享preferences例Android、preferences

2023-09-06 15:12:08 作者:人生得意须尽欢

我想学习共享preferences,但我得到一个错误。

I'm trying to learn SharedPreferences, but I'm getting an error.

我的布局有一个按钮reeacts的方法 doThis

My layout has one button that reeacts to the method doThis

这是我的Java:

package com.example.sharedprefs;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
    int i = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void doThis (View view){
        i++;
        SharedPreferences sharedPref = getSharedPreferences("FileName",MODE_PRIVATE);
        SharedPreferences.Editor prefEditor = sharedPref.edit();
        prefEditor.putInt("userChoice",i);
        prefEditor.commit();
        int number = sharedPref.getInt("userChoice", 0);
        Toast.makeText(getApplicationContext(), number, Toast.LENGTH_LONG).show();
    }

}

只有我可以在logcat中精确定位的是 10-15 19:28:17.707:E / AndroidRuntime(16657):$ android.content.res.Resources NotFoundException:产生的原因字符串资源ID#为0x1

推荐答案

您敬酒不正确。您传递一个数字土司希望它会给一个字符串,反而是认为它应该找一个字符串资源的价值。尝试:

Your toast is incorrect. You are passing a number into the toast hoping that it will give a string, instead is thinks it should be looking up a string resource value. Try:

Toast.makeText(getContext(), number + "" , Toast.LENGTH_LONG).show();

编辑,除此之外,你的code是罚款。

Edit, other than that, your code is fine.