简体   繁体   English

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

[英]Android app crashes when using Shared Preferences

I'm making a simple android app that saves a user name and an email address using shared preferences. 我正在制作一个简单的android应用,该应用使用共享的首选项保存用户名和电子邮件地址。 But the problem is that whenever I declare the shared preferences, the app crashes. 但是问题是,每当我声明共享首选项时,应用程序就会崩溃。 When I delete the shared preferences code, the app runs fine. 当我删除共享的首选项代码时,该应用程序运行良好。

Can somebody see the problem? 有人可以看到问题吗?

Here is my code: 这是我的代码:

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();
    }
}
}

EDIT 编辑

Logcat: 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

You are getting this: 你得到这个:

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

So basically it's saying your casting an EditText to a Button . 因此,基本上这就是说您将EditText转换为Button It would be in the following line: 在下面的行中:

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

So unless you're using the wrong ID and btnSave actually refers to an EditText field, it's a glitch. 因此,除非您使用了错误的ID,并且btnSave实际上引用了EditText字段,否则它是一个小故障。 Most likely it's a glitch in Eclipse. 最有可能是Eclipse中的一个小故障。 Here's how to usually fix (it's common): 以下是通常的解决方法(很常见):

Go to the tabs at the top and select Project > Clean... and clean your project. 转到顶部的标签,然后选择Project > Clean...然后清理您的项目。

The error message says: "You cast the TextBox to Button". 错误消息显示:“您将文本框强制转换为按钮”。 Are you gave the correct names for widgets? 您为小部件指定了正确的名称吗? Check it! 核实!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM