【发布时间】:2018-12-27 09:08:41
【问题描述】:
我正在制作一个应用程序,在此活动中,我试图从用户那里获取数据并使用共享首选项保存它。但应用程序在单击注册按钮时崩溃。
这里是 SignUpActivity.java 文件 -
package com.example.abinas.myapplication;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class SignUpActivity extends AppCompatActivity {
private EditText e3;
private EditText e4;
private EditText e5;
private EditText e6;
private Button b2;
private RadioGroup rg;
private RadioButton rb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
rg = (RadioGroup)findViewById(R.id.radioroup);
e3 = (EditText)findViewById(R.id.editText3);
e4 = (EditText)findViewById(R.id.editText4);
e5 = (EditText)findViewById(R.id.editText5);
e6 = (EditText)findViewById(R.id.editText6);
b2 = (Button)findViewById(R.id.button2);
int selected_id = rg.getCheckedRadioButtonId();
rb = (RadioButton)findViewById(selected_id);
}
public void onButtonClick(View view){
final SharedPreferences pref;
pref = getSharedPreferences("user_info",Context.MODE_PRIVATE);
SharedPreferences.Editor edit = pref.edit();
edit.putString("gender",rb.getText().toString());
edit.putString("username",e4.getText().toString());
edit.putString("name",e3.getText().toString());
edit.putString("password",e5.getText().toString());
edit.putInt("phone",Integer.parseInt(e6.getText().toString()));
edit.apply();
edit.commit();
//b2.setText("SAVED");
//b2.setClickable(false);
}
}
应该进行哪些更改才能成功保存数据?
【问题讨论】:
-
请分享您的堆栈跟踪
-
你来错地方了。首先查看崩溃日志,然后通过找出崩溃的原因来解决您的问题
-
请分享 logcat 报告或崩溃报告?
-
创建一个对象,然后将其转换为json并保存为字符串,然后当您要获取数据时,将json字符串转换为对象-->您将毫无问题地获取数据
-
似乎有一个错误,当来自单选按钮的字符串存储在共享首选项中时。logcat 中出现以下错误。引起:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.CharSequence android.widget.RadioButton.getText()”。在注释掉该行时,应用程序正常工作。这个怎么解决????
标签: java android sharedpreferences