函数总是在提交sharedpreferences后返回false而没有任何错误

时间:2013-10-23 09:31:51

标签: android boolean sharedpreferences return-value commit

我有问题的部分如下:

public class MainActivity extends BaseActivity implements
    OnContactsInteractionListener, OnAdModeListener {

private SharedPreferences sp;
private SharedPreferences.Editor ed;

...

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    sp = this.getSharedPreferences("me.name",
            MODE_PRIVATE);
    ed = sp.edit();



private boolean parseIntent(Intent intent) {
    if (intent.getAction().equals("SHOW_PHONE_CALL_LIST")
            && sp.getBoolean("SHOW_SECOND", false)) {
        try {
            goToPage(1);
            int random = sp.getInt("RANDOM", 9999);
            counterAdsAndLoad("2", random);
            //ed is editor object
            ed.putString("MP3PATH", "");
            ed.putBoolean("SHOW_SECOND", false);
            ed.commit()
            return true;


        } catch (Exception e) {
            e.printStackTrace();

        }
    }
    ed.remove("RANDOM").commit();
    return false;

}

我因为不合理的不良行为而进行了调试,我看到了以下内容: if条件为真,正如我预期的那样,在第二个commit()之后程序跳转到return false

可能是什么原因?

2 个答案:

答案 0 :(得分:0)

确保您已遵循此规定。

创建SharedPrefrences引用。

SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);

创建SharedPreferncesEditor的引用

SharedPreferences.Editor editor = prefs.edit();

将值放入编辑器

editor.putBoolean("SHOW_SECOND", true); 
editor.putString("MP3_PATH", "");

最后提交修改

editor.commit();

答案 1 :(得分:0)

试试这个......

public class MainActivity extends BaseActivity implements
OnContactsInteractionListener, OnAdModeListener {

private SharedPreferences sp;

...

 @Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  sp = getSharedPreferences("me.name",
        MODE_PRIVATE);
}

private boolean parseIntent(Intent intent) {
if (intent.getAction().equals("SHOW_PHONE_CALL_LIST")
        && sp.getBoolean("SHOW_SECOND", false)) {
    try {
        goToPage(1);
        int random = sp.getInt("RANDOM", 9999);
        counterAdsAndLoad("2", random);
        //ed is editor object
        SharedPreferences.Editor ed = sp.edit();
        ed.putString("MP3PATH", "");
        ed.putBoolean("SHOW_SECOND", false);
        ed.commit()
        return true;


    } catch (Exception e) {
        e.printStackTrace();

    }
 }
 SharedPreferences.Editor ed = sp.edit();
 ed.remove("RANDOM").commit();
 return false;

}