2011-12-26 220 views
0

當我執行此代碼時,我的程序獲得強制關閉..誰能告訴我..什麼是解決方案.. package com.test.sharedPreferences;共享首選項關閉

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); 

    } 
    } 
+3

粘貼logcat錯誤 – aromero 2011-12-26 13:38:34

+0

確切的例外是什麼? logcat輸出請求 – 2011-12-26 13:42:19

+0

其中是您的首選項名稱和聲明時的靜態字符串值。 – 2011-12-26 13:49:08

回答

0

我會用Context.MODE_PRIVATE

+0

在代碼中沒有錯誤..我只是將該代碼粘貼到另一個項目中,並且其工作正常。 – 2012-01-06 06:37:22

0

當你寫getInt ....這意味着你要打開的編輯器。

所以首先打開編輯器並寫入getInt代碼。

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

你不需要編輯器來讀取值。 – 2011-12-26 14:02:48

+0

很抱歉我寫的關於編輯的陳述。但我粘貼的代碼工作正常。所以請嘗試一下。 – 2011-12-27 05:17:50

0

這是你的問題。你開放使用MODE_WORLD_READABLE的共享偏好(即只讀模式)在這裏:

SharedPreferences pref = getSharedPreferences("Preference",MODE_WORLD_READABLE); 

,然後按照該上升試圖在這裏編輯共享偏好:

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

隱而不宣」你對這件事看起來不正確嗎?如果沒有,here's the documentation to clarify things.