0

I can parse json from a url in this way:

String link1 = "http://www.url.com/test1.json";
String link2 = "http://www.url.com/test2.json";
private void fetchMovies() {
    String url = link1;
    JsonArrayRequest req = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    if (response.length() > 0) {
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                JSONObject movieObj = response.getJSONObject(i);
                                int rank = movieObj.getInt("rank");
                                String title = movieObj.getString("title");
                                Movie m = new Movie(rank, title);
                                movieList.add(0, m);
                            } catch (JSONException e) {
                            }
                        }
                        adapter.notifyDataSetChanged();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
        }
    });
    MyApplication.getInstance().addToRequestQueue(req);
}

I want to parse my json from multiple url.

I want to parse url1 and url2 at the same time.

How can I do that?

7
  • A option is use AsyncTask for each url that you want read. Commented Jul 18, 2017 at 15:35
  • Hi @VIX I have more than 10 links. I can't use AsyncTask for each url. Commented Jul 18, 2017 at 15:45
  • All json have the same structure? Commented Jul 18, 2017 at 16:00
  • Yes. all json have the same structure just the links are different. @VIX Commented Jul 18, 2017 at 16:14
  • @VIX Do you have any idea about this? Commented Jul 18, 2017 at 17:54

2 Answers 2

2

I created a class MyAsyncTask, this class receive the URL's list and the context activity. Guide yourself with the sample code.

public class MyAsyncTask extends AsyncTask<Void, Void, List<JSONObject>> {

    private Activity activity;
    private List<String> urls;

    public MyAsyncTask(Activity activity, List<String> urls) {
        this.urls = urls;
        this.activity = activity;
    }

    @Override
    protected List<JSONObject> doInBackground(Void... voids) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        List<JSONObject> jsonURls = new ArrayList<>();
        try{
            for (String url : urls) {
                URL link = new URL(url);
                connection = (HttpURLConnection) link.openConnection();
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestMethod("GET");
                connection.connect();

                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String line = null;
                StringBuilder sb = new StringBuilder();

                while ((line = reader.readLine()) != null)
                    sb.append(line);

                reader.close();
                JSONObject jsonResult = new JSONObject(sb.toString());
                jsonURls.add(jsonResult);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Toast.makeText(activity, "URL error", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(activity, "Connection error", Toast.LENGTH_SHORT).show();
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(activity, "JSON Parsing error", Toast.LENGTH_SHORT).show();
        }
        return jsonURls;
    }

    @Override
    protected void onPostExecute(List<JSONObject> jsonObjects) {
        super.onPostExecute(jsonObjects);
        // Process your JSONs
    }
}

For to call it, you should do the following (Within your activity):

List<String> urls = new ArrayList<>();
urls.add("https://jsonplaceholder.typicode.com/posts/1");
MyAsyncTask myAsyncTask = new MyAsyncTask(MyActivity.this, urls);
myAsyncTask.execute();

The processing of the JSONs, you must in the PostExecute method.

Don't forget add internet permissions.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much @VIX
0

you can simple add your urls into the arraylist and parse the urls through a loop.

Arralist<String> arraylist = new Arraylist;
    arraylist.add(link1);
    arralist.add(link2);


 private void fetchMovies() {
        int x = arralist.size();
    for(int i = 0;i<x;i++)
      {  JsonArrayRequest req = new JsonArrayRequest(arralist.get(i),
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        if (response.length() > 0) {
                            for (int i = 0; i < response.length(); i++) {
                                try {
                                    JSONObject movieObj = response.getJSONObject(i);
                                    int rank = movieObj.getInt("rank");
                                    String title = movieObj.getString("title");
                                    Movie m = new Movie(rank, title);
                                    movieList.add(0, m);
                                } catch (JSONException e) {
                                }
                            }
                            adapter.notifyDataSetChanged();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        MyApplication.getInstance().addToRequestQueue(req);
    }}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.