2014-10-30 202 views
0

我正在製作一個簡單的android應用程序,該應用程序使用共享首選項保存用戶名和電子郵件地址。但問題是,每當我聲明共享首選項時,應用程序崩潰。當我刪除共享首選項代碼時,該應用程序運行良好。使用共享首選項時Android應用程序崩潰

有人可以看到問題嗎?

這裏是我的代碼:

public class PreferencesActivity extends Activity implements OnClickListener { 
private TextView textUserName; 
private TextView textEmail; 
private String userName; 
private String email; 
public static final String MyPREFERENCES = "MyPrefs" ; 

SharedPreferences sharedPref; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    sharedPref = this.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); 
    setContentView(R.layout.activity_preferences); 

    textUserName = (TextView)findViewById(R.id.txtUserName); 
    userName = textUserName.getText().toString(); 
    textEmail = (TextView)findViewById(R.id.txtEmail2); 
    email = textEmail.getText().toString(); 

    Button saveButton = (Button)findViewById(R.id.btnSave); 
    saveButton.setOnClickListener(this); 
} 

@Override 
public void onClick(View v) { 

    Editor editor = sharedPref.edit(); 

    if(v.getId() == R.id.btnSave) { 
     editor.putString(userName, email); 
     editor.commit(); 
    } 
} 
} 

編輯

的logcat:

10-30 20:41:25.246: E/AndroidRuntime(2797): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lab4ex1preferencesactivity/com.example.lab4ex1preferencesactivity.Prefe rencesActivity}: java.lang.ClassCastException: android.widget.EditText cannot be cast to android.widget.Button 
+0

發佈例外的LogCat – panini 2014-10-30 20:38:16

+0

編輯帖子邏輯 – Bouss 2014-10-30 20:47:08

+0

您100%確定''''''''''''''''''''''''''''activity_preferences.xml''中的'''btnSave'屬於'''Button'''類型。而不是''EditText'''? – 2014-10-30 20:53:52

回答

1

您收到此:

java.lang.ClassCastException: android.widget.EditText cannot be cast to android.widget.Button 

所以基本上是在說你投EditTextButton。這將是以下行:

Button saveButton = (Button)findViewById(R.id.btnSave); 

所以,除非你使用了錯誤的ID和btnSave實際上指的是EditText場,這是一個小故障。這很可能是Eclipse中的一個小故障。以下是通常的修復方法(這很常見):

轉到頂部的選項卡並選擇Project > Clean...並清理項目。

+1

非常感謝,解決了這個問題! – Bouss 2014-10-30 20:56:15

+0

@布斯很高興幫助。 – 2014-10-30 20:57:01

1

錯誤消息說:「您將文本框投到按鈕」。你是否給出了小部件的正確名稱?覈實!