我正在尝试从编辑文本输入框中检索值并将它们存储在数据库中。我得到一个空指针异常,我不知道为什么。在此先感谢您的帮助:)
这是我的代码,我在这里检索值并将它们作为参数传递给数据库:
public class MyPage extends Activity {
final Context context = this;
public String stringName;
public int intAge;
public int intWeight;
public int intHeight;
public String stringGoal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_page);
final Button button = (Button) findViewById(R.id.btn_addInfo);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialogue_userinfo);
dialog.setTitle("Add Your Information");
Button dialogButton = (Button) dialog.findViewById(R.id.btnDone);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText textName = (EditText)findViewById(R.id.txtName);
stringName = textName.getText().toString();
EditText textAge = (EditText)findViewById(R.id.txtAge);
intAge = Integer.parseInt(textAge.getText().toString());
EditText textWeight = (EditText)findViewById(R.id.txtWeight);
intWeight = Integer.parseInt(textWeight.getText().toString());
EditText textHeight = (EditText)findViewById(R.id.txtHeight);
intHeight = Integer.parseInt(textHeight.getText().toString());
EditText textGoal = (EditText)findViewById(R.id.txtGoal);
stringGoal = textGoal.getText().toString();
DatabaseAccess();
dialog.dismiss();
}
});
dialog.show();
Window window = dialog.getWindow();
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
}
});
}
private void DatabaseAccess(){
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Inserting User
Log.d("Insert: ", "Inserting ..");
db.addUser(new User(stringName, intAge, intWeight, intHeight, stringGoal));
//db.addUser(new User("Peter Parker", 23, 50, 150, "Hi"));
// Reading all users
Log.d("Reading: ", "Reading all contacts..");
List<User> users = db.getAllUsers();
for (User us : users) {
String log = "Id: "+us.getId()+" ,Name: " + us.getName() + " ,Age: " + us.getAge()
+ " ,Weight: " + us.getWeight() + " ,Height: " + us.getHeight()
+ " ,Goal: " + us.getGoal()
+ " ,BMI: " + us.getBmi();
Log.d("Name: ", log);
}
}
}
答案 0 :(得分:2)
如果所有EditText内部的对话框dialogue_userinfo layout
然后使用Dialog实例在按钮单击上初始化EditText的实例。这样做:
EditText textName = (EditText)dialog.findViewById(R.id.txtName);
stringName = textName.getText().toString();
EditText textAge = (EditText)dialog.findViewById(R.id.txtAge);
intAge = Integer.parseInt(textAge.getText().toString());
//....same for others...
答案 1 :(得分:0)
getText将返回Editable
对象。如果您的edittext没有任何字符,则可能返回null对象。所以你必须检查getText()是否返回一个空对象。
if(youreditView.getText() != null ) {
String content = youreditView.getText().toString();
}