Android Studio - 在一个异步任务中从2个URL下载JSON数据

问题描述 投票:2回答:2

我可以使用下面的代码使用downloadJSON类为1 URL下载数据没有问题,但我想获得另一组数据,以便它可以与另一个一起显示。我尝试了几种不同的方法但无济于事。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_json);
    TextView textView = (TextView)findViewById(R.id.JSONTextView);
    textView.setText("Downloading JSON!");
    new downloadJSON().execute("www.exampleURL.com/data1");
   //new downloadJSON().execute(url2??);
}

private class downloadJSON extends AsyncTask<String, String, String>
{
    protected String doInBackground(String... args) {
        String result = "";
        String formattedResult = "";

        try {
            InputStream stream = (InputStream)new URL(args[0]).getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            String line = "";
            while (line != null) {
                result += line;
                line = reader.readLine();
            }

            JSONObject json = new JSONObject(result);
            formattedResult = "Downloadable Puzzles\r\n--------------\r\n";



            JSONArray puzzles = json.getJSONArray("PuzzleIndex");


            for (int i = 0;i < puzzles.length(); ++i) {
                formattedResult += puzzles.get(i) + "\r\n";

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return formattedResult;
    }


    protected void onPostExecute(String pResult) {
        TextView textView = (TextView)findViewById(R.id.JSONTextView);
        textView.setText(pResult);
    }
}

编辑:我的问题不是下面发布的链接的重复,因为我的问题更重要,因为涉及JSON和URL。该链接绝不是我的问题所特有的,并没有帮助这个问题。

java android json parsing
2个回答
1
投票

Async任务不会将控件返回给调用方法。它只在后台线程上完成doInBackground()后在主线程中运行onPostExecute()。

将控制转换回调用方法的一种方法是使用接口。

public class DownloadJSON extends AsyncTask<String, String, String> {

    private AsyncCallback mCallback;

    public DownloadJSON(AsyncCallback callback) {
        mCallback = callback;
    }

    protected String doInBackground(String... args) {
        // process background task
    }


    protected void onPostExecute(String result) {
        if (mCallback != null)
            mCallback.onComplete(result);
    }

    public interface AsyncCallback {
        void onComplete(String result);
    }
}

然后启动asynctask使用

new DownloadJSON(new DownloadJSON.AsyncCallback() {
    @Override
    public void onComplete(String result) {
        textView.setText(result);
    }
}).execute("www.exampleURL.com/data1");

0
投票

我可以建议你放弃从线程池中挑选线程的旧方法,并在后台线程执行这个繁重的操作

看看这个很棒的lib。 RxJava

© www.soinside.com 2019 - 2024. All rights reserved.