好的,我在这里搞简单了。
我在一个活动中有三个类:
public class ActivityUserAccountCreate extends Activity implements
OnClickListener {
}
private class postToHttps extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
try {
createUserAccount();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public void createUserAccount() throws ClientProtocolException, IOException {
...
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
Log.d("Posting Username", usernameFinal);
nameValuePairs.add(new BasicNameValuePair("username", "usernameFinal"));
...
}
在我的Activity类中,我初始化布局中的三个字符串。基本上用户在EditText中输入他们的用户名。字符串= =从字段中获取文本。一切正常,但我试图在createUserAccount()中使用相同的字符串。我相信字符串在那时是空的,所以我必须在createUserAccount()中再次重新初始化这三个相同的字符串吗?如果是这样,我应该像在Activity类中那样做吗?
由于
好的,我已根据以下建议编辑:
...
new postToHttps().execute(usernameFinal,passwordFinal,userEmail);
...
private class postToHttps extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
String usernameFinal = params[0];
String passwordFinal = params[1];
String userEmail = params[2];
try {
createUserAccount(usernameFinal, passwordFinal, userEmail);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public void createUserAccount(String usernameFinal, String passwordFinal, String userEmail) throws ClientProtocolException, IOException {
String uri = "editedout.php";
Log.d("Action", "Posting user data to php");
HttpClient client = new DefaultHttpClient();
HttpPost getMethod = new HttpPost(uri);
Log.d("Posting Location", uri);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
Log.d("Posting Username", usernameFinal);
nameValuePairs
.add(new BasicNameValuePair("username", usernameFinal));
Log.d("Posting Pass", passwordFinal);
nameValuePairs
.add(new BasicNameValuePair("password", passwordFinal));
nameValuePairs.add(new BasicNameValuePair("email", userEmail));
getMethod
.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
client.execute(getMethod);
Log.d("Action", "Finished Posting Data to PHP");
}
但是我遇到了崩溃。看起来它在doInBackground中崩溃了,但我还在学习读取LogCat。
答案 0 :(得分:0)
您不必重新初始化任何内容,但如果您尝试将三个字符串传入AsyncTask
,我建议您利用doInBackground(String... params)
中使用的变量参数。
例如:
...
private class PostToHttps extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
String username = params[0];
String firstName = params[1];
String lastName = params[2];
createUserAccount(username, firstName, lastName);
}
...
PostToHttps httpsTask = new PostToHttps();
httpsTask.execute(usernameEditText.getText().toString(),
firstNameEditText.getText().toString(),
lastNameEditText.getText().toString);
...
public void createUserAccount(String username, String firstName, String lastName)
throws ClientProtocolException, IOException {
...