如何使用AssyncTask方法解析来自两个json的数据?

时间:2015-11-21 12:25:13

标签: android json

我已经看到了一个类似的问题,但我无法像他那样解决我的问题。 我在这里从网址获取数据:

public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {

    @Override
    protected void onPreExecute() {
        setProgressBarIndeterminateVisibility(true);
    }

    @Override
    protected Integer doInBackground(String... params) {
        Integer result = 0;
        HttpURLConnection urlConnection;
        try {
            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            int statusCode = urlConnection.getResponseCode();

            // 200 represents HTTP Ok
            if (statusCode == 200) {
                BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    response.append(line);
                }
                parseResult(response.toString());
                result = 1; // Successful
            } else {
                result = 0; //"Failed to fetch data!";
            }
        } catch (Exception e) {
            Log.d(TAG, e.getLocalizedMessage());
        }
        return result; //"Failed to fetch data!";
    }
    @Override
    protected void onPostExecute(Integer result) {
        // Download complete. Let us update UI
        progressBar.setVisibility(View.GONE);

        if (result == 1) {
            giftListAdapter = new GiftListAdapter(GiftsActivity.this, gifts);
            recyclerView.setAdapter(giftListAdapter);
        } else {
            SuperActivityToast.create(GiftsActivity.this, getString(R.string.no_internet_connection),
                    SuperToast.Duration.SHORT, Style.getStyle(Style.RED, SuperToast.Animations.FLYIN)).show();
        }
    }
}

private void parseResult(String result) {
    try {
        JSONObject response = new JSONObject(result);
        JSONArray posts = response.optJSONArray("gifts");
        gifts = new ArrayList<>();

        for (int i = 0; i < posts.length(); i++) {
            JSONObject post = posts.optJSONObject(i);
            GiftItem item = new GiftItem();
            item.setThumbnail(post.optString("image"));
            item.setTitle(post.optString("title"));
            item.setDescription(post.optString("description"));
            item.setSource(getString(R.string.source) + " " + post.optString("source"));
            item.setTotalRating(post.optInt("rating"));
            item.setPrice(post.optDouble("price"));

            gifts.add(item);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

在这里,我正在执行该网址。我现在正在尝试解析第二个网址,并在加载第一个数据后加载所有项目:

new AsyncHttpTask().execute(url_movies);
        new AsyncHttpTask().execute(url_books); // This is the second url i'm trying to get

我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

  

我现在正在尝试解析第二个url并在第一个之后加载所有项目   数据加载:

然后,在第一个url所有项目成功加载后,不要先调用execute方法,而是在onPostExecute方法内调用它。

还在if-else块中添加第二个调用以避免再次执行:

@Override
    protected void onPostExecute(Integer result) {
        // Download complete. Let us update UI
        progressBar.setVisibility(View.GONE);
        ... your code here
        if(params[0].equals(url_movies)){
           new AsyncHttpTask().execute(url_books);
        } 
    }

还要添加

答案 1 :(得分:0)

如果你想要两个url而不是像这样发送它们的String数组

String urls [] = new String [] {&#34; url1&#34; ,&#34; url2&#34;};

new AsyncHttpTask()。execute(urls);

并且在doinbackground方法中执行它们就好了 url1 = params [0]; url2 = params [1];