我正在从异步任务加载数据。在doinBackground()
中,我想检查返回的JSON字符串是否包含错误,如果是,我想停止AsyncTask并显示textview,如果没有错误,我想继续执行asynctask。这是我的代码。
protected String doInBackground(String... args) {
// Building Parameters
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url_all_open_bets);
List<NameValuePair> params = new ArrayList<NameValuePair>();
post.setHeader("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36");
params.add(new BasicNameValuePair("email", name));
params.add(new BasicNameValuePair("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36"));
try {
post.setEntity(new UrlEncodedFormEntity(params));
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
HttpResponse response = client.execute(post);
Log.d("Http Post Response:", response.toString());
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
JSONObject jObj = null;
String json = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("<", 0)) {
if (!line.startsWith("(", 0)) {
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
json = json.substring(json.indexOf('{'));
if (json.contains("error")) {
TextView textView = (TextView) findViewById(R.id.nobetstxtbox);
textView.setVisibility(View.VISIBLE);
}
Log.d("sb", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
Log.d("json", jObj.toString());
try {
allgames = jObj.getJSONArray(TAG_BET);
Log.d("allgames", allgames.toString());
ArrayList<BetDatabaseSaver> listofbets = new ArrayList<>();
// looping through All Products
for (int i = 0; i < allgames.length(); i++) {
JSONObject c = allgames.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String user = c.getString(TAG_USER);
String returns = c.getString(TAG_RETURNS);
String stake = c.getString(TAG_STAKE);
String status = c.getString(TAG_STATUS);
String Teams = c.getString(TAG_TEAMS);
Log.d("id", id);
Log.d("user", user);
Log.d("returns", returns);
Log.d("stake", stake);
Log.d("status", status);
Log.d("teams", Teams);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TEAMS, Teams);
map.put(TAG_USER, user);
map.put(TAG_RETURNS, returns);
map.put(TAG_STAKE, stake);
map.put(TAG_STATUS, status);
useroutcomes.put(id.substring(0, 10), Teams);
boolean contains = false;
for (int a = 0; a < listwriter.size(); a++) {
if (listwriter.get(a).getId().equals(id)) {
listwriter.add(a, new BetDisplayer(user, id, Integer.parseInt(stake), Integer.parseInt(returns), status, "", "", Teams));
contains = true;
}
}
if (!(contains)) {
listwriter.add(i, new BetDisplayer(user, id, Integer.parseInt(stake), Integer.parseInt(returns), status, "", "", Teams));
}
// adding HashList to ArrayList
bet.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return "";
}
我添加了这个片段
` if (json.contains("error")) {
TextView textView = (TextView) findViewById(R.id.nobetstxtbox);
textView.setVisibility(View.VISIBLE);
}`
检查错误,但是我不知道如果错误是真的并且在此语句之后没有执行任何代码,此时如何退出asynctask。使用else不会起作用,因为它会干扰try catch语句,使用break也行不通。
答案 0 :(得分:4)
您可以在if条件中调用cancel()
方法,在cancel()
中调用doInBackground()
将取消AsyncTask
,onCancelled()
将调用onPostExecute()
而不是{{} 1}}
像这样:
if (json.contains("error")) {
cancel(true);
return "";
}
答案 1 :(得分:1)
你可以在条件中放置一个return语句,它将以退出任何方法的方式退出方法(在这种情况下它会退出到onPostExecute()方法)。
答案 2 :(得分:1)
您可以在doInBackground()
:
if (json.contains("error")) {
return "error";
}
在onPostExecute()
void onPostExecute(String message)
{
if(message.equals("error"))
{
//You cannot access UI thread in doInBackground(). So, you need to do all the UI related tasks over here.
TextView textView = (TextView) findViewById(R.id.nobetstxtbox);
textView.setVisibility(View.VISIBLE);
}
else
{
//your code for the positive results
}
}
答案 3 :(得分:0)
您可以致电cancel(boolean mayInterruptIfRunning)
请参阅:http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean)
请参阅此问题Usage of mayInterruptIfRunning to cancel ASyncTask - Function call order -
关于如何使用mayInterruptIfRunning标志。