Android SharedPreferences示例

EGH*_*HDK 3 java android sharedpreferences

我正在尝试学习SharedPreferences,但我收到了一个错误.

我的布局有一个按钮,可以重现该方法 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();
    }

}
Run Code Online (Sandbox Code Playgroud)

我唯一可以在logcat中查明的是 10-15 19:28:17.707: E/AndroidRuntime(16657): Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x1

aho*_*der 8

你的祝酒词不对.你正在将一个数字传递给toast,希望它能给出一个字符串,而不是认为它应该查找一个字符串资源值.尝试:

Toast.makeText(getContext(), number + "" , Toast.LENGTH_LONG).show();
Run Code Online (Sandbox Code Playgroud)

编辑,除此之外,你的代码很好.