使用共享首选项时Android应用程序崩溃
我正在制作一个简单的android应用程序,使用共享首选项保存用户名和电子邮件地址。但问题是,每当我声明共享首选项时,应用程序就会崩溃。当我删除共享首选项代码时,应用程序运行正常 有人能看到问题吗 这是我的密码:使用共享首选项时Android应用程序崩溃,android,eclipse,sharedpreferences,Android,Eclipse,Sharedpreferences,我正在制作一个简单的android应用程序,使用共享首选项保存用户名和电子邮件地址。但问题是,每当我声明共享首选项时,应用程序就会崩溃。当我删除共享首选项代码时,应用程序运行正常 有人能看到问题吗 这是我的密码: public class PreferencesActivity extends Activity implements OnClickListener { private TextView textUserName; private TextView textEmail; priva
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();
}
}
}
编辑
日志:
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
你得到的是:
java.lang.ClassCastException: android.widget.EditText cannot be cast to android.widget.Button
因此,基本上就是说,您将一个编辑文本
转换为一个按钮
。这将是以下一行:
Button saveButton = (Button)findViewById(R.id.btnSave);
因此,除非您使用了错误的ID并且btnSave
实际上引用了EditText
字段,否则这是一个小故障。很可能是Eclipse中的一个小故障。以下是通常的修复方法(这很常见):
转到顶部的选项卡,选择
Project>Clean…
并清理项目。错误消息显示:“您将文本框强制转换为按钮”。您是否为小部件提供了正确的名称?检查一下 发布例外的日志用逻辑编辑帖子您100%确定活动首选项中的btnSave
。xml
类型为按钮
,而不是编辑文本
?