我有2个EditText字段,分别是电子邮件和姓名。当用户单击按钮时,我会在AsyncTask onPreExecute()方法中获得这两个字段的值。我的问题是我现在如何将该值传递给 doInBackground()方法并将其插入到字符串答案中?我了解到你不应该将UI项目传递到 doInBackground()。我一直在这里搜索并测试代码的不同变体,但不断获得Null值。
private class myprofile extends AsyncTask<String,Void,Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Email= (EditText)findViewById(R.id.email);
String email= Email.getText().toString();
Name= (EditText)findViewById(R.id.name);
String name= Name.getText().toString();
}
@Override
protected Boolean doInBackground(String... params) {
String email = params[0];
String name = params[1];
String Answers="email="+email+"&name="+name;
return null;
}
// @Override
protected void onPostExecute(Boolean result) {
}
}
答案 0 :(得分:3)
有很多方法可以做到这一点。您似乎已将其设置为将其传递到execute()
。
1)转入AsyncTask.execute()
String email= Email.getText().toString();
String name= Name.getText().toString();
new myprofile().execute(email, name);
2)传递给构造函数
private class myprofile extends AsyncTask<Void,Void,Boolean> {
private String email;
private String name;
public myprofile(String email, String name){
this.email = email;
this.name = name;
}
...
}
String email= Email.getText().toString();
String name= Name.getText().toString();
new myprofile(email, name).execute();
3)检索onPreExecute()
private String email;
private String name;
protected void onPreExecute() {
super.onPreExecute();
email = Email.getText().toString();
name = Name.getText().toString();
}