首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >按条件从doinBackground中途退出异步任务

按条件从doinBackground中途退出异步任务
EN

Stack Overflow用户
提问于 2015-06-29 14:26:31
回答 4查看 580关注 0票数 0

我正在从异步任务中加载数据。在doinBackground()中,我想检查返回的JSON字符串是否包含错误,如果是,我想停止asynctask并显示文本视图,如果没有错误,我想继续执行异步任务。这是我的密码。

代码语言:javascript
复制
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 "";
        }

我添加了这个片段

代码语言:javascript
复制
` if (json.contains("error")) {
     TextView textView = (TextView) findViewById(R.id.nobetstxtbox);
     textView.setVisibility(View.VISIBLE);
            }`

以检查错误,但我不确定此时如何退出异步任务,如果错误为真,并且在此语句之后不执行任何代码。使用doesn将无法工作,因为它会干扰try catch语句,而使用catch也不起作用。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2015-06-29 14:33:28

您可以在if条件下调用cancel()方法,在doInBackground()中调用cancel()将取消AsyncTask,而onCancelled()将被调用而不是onPostExecute()

如下所示:

代码语言:javascript
复制
 if (json.contains("error")) {
       cancel(true);
       return "";  
 }
票数 4
EN

Stack Overflow用户

发布于 2015-06-29 14:38:22

你可以在你的doInBackground()中做这样的事情

代码语言:javascript
复制
if (json.contains("error")) {
    return "error";
}

在你的onPostExecute()

代码语言:javascript
复制
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
    }
}
票数 2
EN

Stack Overflow用户

发布于 2015-06-29 14:28:13

您只需在条件中放置一个返回语句,它将以与退出任何方法相同的方式退出该方法(在本例中,它将退出到onPostExecute()方法)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31118267

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档