在Android的共享preference问题 [英] SharedPreference problem in android

查看:181
本文介绍了在Android的共享preference问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class WordDisplay extends Activity {

private int level;      
private int group;      
private int set;        

private WordDisplay mContext=this;

private int l;
private int g;
private int s;

SharedPreferences preferences;

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

          }
protected void loadPreferences() {
 preferences = PreferenceManager.getDefaultSharedPreferences(this);
    // preferences = getSharedPreferences("one", Context.MODE_PRIVATE);

     l= preferences.getInt("Level", 0);
     g=preferences.getInt("Group", 0);
     s= preferences.getInt("Set", 0);
    // Log.d("lll"," - "+preferences.getInt("level",0));

}

    @Override
protected void onStop() {
    super.onStop();
    savePreferences(this.level,this.group,this.set);
 }

protected void savePreferences(int level, int group, int set) {
         preferences = PreferenceManager.getDefaultSharedPreferences(this);
        //preferences = getSharedPreferences("one", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();

        editor.putInt("Level", l);
        editor.putInt("Group", g);
        editor.putInt("Set", s);

       editor.commit();

        //return getPreferences(s).getInt("Set", 0);

    }
 }

在这里,我的数据不能正确地坚持。什么是错我的code。请提供良好的便利性。
上述code的评论,也检查,但不能有任何影响。

Here, my data could not persist properly. what is the wrong my code. please give good convenience. Comments of the above code, Also checking but could not any effect.

推荐答案

首先,的onStop()可能永远不会被调用(请参见活动生命周期),实践是保存在的onPause()方法您的数据。

First, onStop() "might" never be called (see Activity life cycle), practice is to save your data in the onPause() method.

也许尝试添加更多的日志,看看这是怎么回事?

Maybe try to add more logs to see what's going on?


  • 的onStop()叫什么名字?

  • 什么是保存/加载的值?


  • is onStop() called?
  • what are the saved / loaded values?
  • etc.

这篇关于在Android的共享preference问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆