使用共享首选项时Android应用程序崩溃

时间:2014-10-30 20:37:46

标签: android eclipse sharedpreferences

我正在创建一个简单的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

2 个答案:

答案 0 :(得分:1)

你得到了这个:

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

所以基本上它是说你向EditText施放Button。它将在以下行中:

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

因此,除非您使用了错误的ID并且btnSave实际上引用了EditText字段,否则这是一个小问题。很可能这是Eclipse中的一个小故障。以下是通常修复的方法(通常):

转到顶部的标签,然后选择Project > Clean...并清理项目。

答案 1 :(得分:1)

错误消息显示:"您将TextBox转换为Button"。你给小部件正确的名字了吗?检查一下!

相关问题