Android的共享preferences例 [英] Android SharedPreferences Example
本文介绍了Android的共享preferences例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想学习共享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.
这篇关于Android的共享preferences例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文