我正在尝试从InBackground方法获取返回值,该方法是第一次获取,然后返回正确,但是返回NULL后,我的逻辑如下:在onPostExecute方法中,我调用另一个函数来设置变量的值,但是由于某种原因,该变量在正确接收数据后变为NULL。这是我的代码:
if (TextUtils.isEmpty(firstname))
{
Toast.makeText(Signup.this, "Enter your first name.", Toast.LENGTH_LONG).show();
} else if (TextUtils.isEmpty(lastname))
{
Toast.makeText(Signup.this, "Enter your last name.", Toast.LENGTH_LONG).show();
} else if (TextUtils.isEmpty(email))
{
Toast.makeText(Signup.this, "Enter your valid email address.", Toast.LENGTH_LONG).show();
}else if (TextUtils.isEmpty(password))
{
Toast.makeText(Signup.this, "Enter your password.", Toast.LENGTH_LONG).show();
} else if (TextUtils.isEmpty(confirmpass)) {
Toast.makeText(Signup.this, "Please write your password again.", Toast.LENGTH_LONG).show();
}else if (password != confirmpass)
{
Toast.makeText(Signup.this, "Password do not match", Toast.LENGTH_LONG).show();
}
答案 0 :(得分:0)
我认为,将结果提供回调用代码的更好方法是使用接口,例如:
interface RequestListener {
public onResultSuccess(JSONArray array);
public onResultFail(String error);
}
private class MyTask extends AsyncTask<String, Void, JSONArray>
{
RequestListener listener = null;
MyTask(RequestListener listener) {
this.listener = listener
}
@Override
protected JSONArray doInBackground(String... urls)
{
try{
URL url = new URL(urls[0]);
HttpURLConnection myConnection =
(HttpURLConnection) url.openConnection();
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader =
new InputStreamReader(responseBody, "UTF-8");
BufferedReader streamReader = new BufferedReader(new InputStreamReader(responseBody, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONArray jsonArray = new JSONArray(responseStrBuilder.toString());
//myConnection.disconnect();
return jsonArray;
} else {
return null;
}
}catch (Exception e){
return null;
}
}
@Override
protected void onPostExecute(JSONArray jsonArray)
{
if (listener != null) {
if (jsonArray != null) {
listener.onResultSuccess(jsonArray);
} else {
listener.onResultFail(your-message);
}
}
}
}
然后,当您实例化RequestListener
对象(可能在MyTask
内)时,您当然必须提供onCreate
接口的实例