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

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

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

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

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

您不能将整数类型设置为Toast消息。

你只能将String类型放到Toast.makeText方法的message参数中。

至于解决方案,你可以尝试这些

 Toast.makeText(getApplicationContext(), Integer.toString(number), Toast.LENGTH_LONG).show(); Toast.makeText(getApplicationContext(), ""+number, Toast.LENGTH_LONG).show(); 

是的,您的共享偏好用法非常好。

这里的问题是你使用整数值作为Toa​​st字符串。 你必须做以下事情。

 String.valueOf(number); 

要么

 Integer.toString(number); 

您的共享偏好部分没问题。 但是有关SharedPreferences的更多信息,您可以访问此post。 Android SharedPreferences示例