问题
I'm trying to learn SharedPreferences, but I'm getting an error.
My layout has one button that reeacts to the method doThis
This is my 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();
}
}
Only thing I can pinpoint in logcat is 10-15 19:28:17.707: E/AndroidRuntime(16657): Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x1
回答1:
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();
Edit, other than that, your code is fine.
回答2:
You can't make a integer type to Toast message.
you can only put String type to the message parameter to Toast.makeText method.
as for solution, you can try these
Toast.makeText(getApplicationContext(), Integer.toString(number), Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), ""+number, Toast.LENGTH_LONG).show();
and yes, your sharedpreference usage is perfectly fine.
回答3:
The problem here is you are using an integer value as the Toast string. You have to do the following.
String.valueOf(number);
or
Integer.toString(number);
Your sharedpreferences part is ok. But for more info about SharedPreferences you can visit this post. Android SharedPreferences Example
来源:https://stackoverflow.com/questions/12905456/android-sharedpreferences-example