2012-11-15 28 views
2
// I declared myPrefs globally in the lass 
SharedPreferences myPrefs = null; 

// this is called in my do draw function 

public void doDraw() {
myPrefs = this.getSharedPreferences("myPrefs", Context.MODE_WORLD_READABLE); SharedPreferences.Editor editor = myPrefs.edit();
editor.putInt("MYHIGHSCORE", score); editor.commit();
}聲明SharedPreferences.Editor崩潰我的應用程序

每當我打電話SharedPreferences.Editor editor = myPrefs.edit();,我的程序崩潰。我做錯了什麼?我正在嘗試爲高分系統存儲一個int。並且SharedPreferences對於像我這樣的迷你高分系統提出了很多建議。

+1

什麼是錯誤信息? –

+0

@LawrenceChoy對日誌貓說它有一個空指針異常。 – CtheW

+0

是你的活動類裏面的繪製函數嗎? –

回答

1

編輯:

package com.example.logindemo; 

import android.app.Activity; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.View; 
import android.widget.EditText; 

public class LoginPage extends Activity { 

    EditText name = null, pwd = null; 
    SharedPreferences login_pref = null; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_login_page); 
     name = (EditText) findViewById(R.id.name_edt); 
     pwd = (EditText) findViewById(R.id.pwd_edt); 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_login_page, menu); 
     return true; 
    } 

    public void loginMethod(View v) { 
     login_pref = this.getSharedPreferences("login_pref", 
       MODE_WORLD_READABLE); 
     SharedPreferences.Editor login_pref_editor = login_pref.edit(); 
     login_pref_editor.putString("Name", name.getText().toString()); 

     login_pref_editor.commit(); 
     startActivity(new Intent(this, WelcomeScreen.class)); 
    } 
} 

試試這個。我認爲你的共享pref對象沒有被正確取出。 注意:編輯帖子以添加整個班級的代碼。

+0

sry,但是按名稱(「name」.gettext()。tostring()),它代表什麼? – CtheW

+0

這是我的編輯文本。我從我的項目中複製了這一行。您將不得不使用任何想要保存在共享首選項中的值。我已將該編輯文本的值與共享首選項中的「名稱」 –

+0

這個值應用於int嗎? – CtheW

0

我猜問題不在edit()但是當你apply()你的變化。看看解決方案here

+0

我使用commit()而不是apply。只需擁有'SharedPreferences.Editor editor = myPrefs.edit();'。我的應用程序崩潰。 – CtheW

1

如果您打算只有一個首選項文件,請嘗試使用此代碼檢索SharedPreference

myPrefs = PreferenceManager.getDefaultSharedPreferences(this);