Android 共享偏好强制关闭

Android 共享偏好强制关闭,android,Android,当我执行此代码时,我的程序将强制关闭。。谁能告诉我解决办法是什么。。 包com.test.SharedReferences import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.TextView; public class Sharedpreference extends Activity { @Over

当我执行此代码时,我的程序将强制关闭。。谁能告诉我解决办法是什么。。 包com.test.SharedReferences

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;

public class Sharedpreference extends Activity {
    @Override
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      SharedPreferences pref = getSharedPreferences("Preference",MODE_WORLD_READABLE);
      SharedPreferences.Editor editor = pref.edit();
      editor.putBoolean("keyBoolean", true);
      editor.putFloat("keyFloat", 1.0f);
      editor.putInt("keyInt", 1);
      editor.putLong("keyLong", 1000000L);
      editor.putString("keyString", "Hello Android");
      editor.commit();

//    boolean dataFromPrefBool = pref.getBoolean("keyBoolean", false);
//    float dataFromPrefflaot = pref.getFloat("keyFloat", 0.0f);
      int dataFromPrefInt = pref.getInt("keyInt", 0);
//    long dataFromPrefLong = pref.getLong("keyLong", 0);
//    String dataFromPrefString = pref.getString("keyString", null);

      TextView tv = new TextView(this);
      tv.setText(dataFromPrefInt);
      setContentView(tv);

     }
    }

当您编写getInt时,我会使用Context.MODE\u PRIVATE,这意味着您正在打开编辑器

因此,首先打开编辑器并编写getInt代码

SharedPreferences pref = getSharedPreferences("Preference",MODE_WORLD_READABLE);
int dataFromPrefInt = pref.getInt("keyInt", 0);

这是你的问题。您正在使用
模式\u WORLD\u READABLE
(即只读模式)打开共享首选项,如下所示:

然后在这里编辑共享首选项:

SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("keyBoolean", true);
...
editor.commit();

你不觉得这有什么不对吗?如果没有,具体的例外情况是什么?logcat输出PLS这里是您的首选项名称和声明中的静态字符串值。我为我写的关于编辑器的声明感到抱歉。但是我粘贴的代码运行良好。所以请尝试一下。代码中没有错误。我只是将代码粘贴到另一个项目中。它工作正常。
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("keyBoolean", true);
...
editor.commit();