我正在制作一个简单的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
发布例外的LogCat – panini 2014-10-30 20:38:16
编辑帖子逻辑 – Bouss 2014-10-30 20:47:08
您100%确定''''''''''''''''''''''''''''activity_preferences.xml''中的'''btnSave'属于'''Button'''类型。而不是''EditText'''? – 2014-10-30 20:53:52