More than 1 different Urls and only One listview
try this one...Actually in this code am using Volley Library for Network Operations.First of all create Application class in your Application to avoid creating new instance of Volley library for network operations.
public class ApplicationController extends Application {public static final String TAG = ApplicationController.class .getSimpleName();private RequestQueue mRequestQueue;private ImageLoader mImageLoader;private static ApplicationController mInstance;@Overridepublic void onCreate() { super.onCreate(); mInstance = this;}public static synchronized ApplicationController getInstance() { return mInstance;}public RequestQueue getRequestQueue() { if (mRequestQueue == null) { mRequestQueue = Volley.newRequestQueue(getApplicationContext()); } return mRequestQueue;} //This function request the volley library to process with tag //where <T> a generic method with an unbound type variable T.You can pass any datatype to functions.for more info About generic method.go through this link:http://docs.oracle.com/javase/tutorial/extra/generics/methods.htmlpublic <T> void addToRequestQueue(Request<T> req, String tag) { // set the default tag if tag is empty req.setTag(TextUtils.isEmpty(tag) ? TAG : tag); getRequestQueue().add(req);} //This function request the volley library to process with tagpublic <T> void addToRequestQueue(Request<T> req) { req.setTag(TAG); getRequestQueue().add(req);}//This function cancel the requested Url those are all in pendingpublic void cancelPendingRequests(Object tag) { if (mRequestQueue != null) { mRequestQueue.cancelAll(tag); }}}
In app build.gradle add this line under dependencies
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
In manifest file add this permission to access network
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
in Application tag mentioned the application class name
<application android:name=".ApplicationController" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> //your activity.... </application>
In Activity onCreate add this line...
progressDialog=new ProgressDialog(MainClass.this); progressDialog.setMessage("Loading..."); progressDialog.show(); //place your code to form urlarray urlarray = new String[5]; //where datas represents the arraylist to store received content from json response.if you want to show more datas add your custom object to arraylist datas=new ArrayList<String>(); adapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1); try { for (int i = 0; i < urlarray.length; i++) { final int j = i; String url=urlarray[i]; JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, url, (JSONObject) null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.e("Response is for " + Integer.toString(j), response.toString()); //Here i assumed received json response is same as of sample json Provided by you. try{ JSONArray jsonArray=response.getJSONArray("posts"); if(jsonArray.length()>0){ JSONObject obj=jsonArray.getJSONObject(0); String content=obj.getString("content"); datas.add(content); } if(j==urlarray.length-1) { progressDialog.dismiss(); adapter= new ArrayAdapter<String>(MainClass.this, android.R.layout.simple_list_item_1, android.R.id.text1,datas); listView.setAdapter(adapter); } }catch(Exception e){ e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("error",error.toString()); if(j==urlarray.length-1) { progressDialog.dismiss(); } } }){ @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); headers.put( "charset", "utf-8"); return headers; } }; objectRequest.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); ApplicationController.getInstance().addToRequestQueue(objectRequest, "JSON"); } } catch (Exception e) { e.printStackTrace(); }
You should be doing every execution in the onBackground method after you get the result of one asynchronous call. This is because the async task executes on a different thread.
ArrayList<HashMap<String,String>> allData;Iterator iterator;ArrayList<String> urlarray = new ArrayList<>();@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bookmark); SqliteController controller= new SqliteController(this); allData = controller.getAllData(); for (int i=0; i<allData.size(); i++){ String url=allData.get(i).get("link"); urlarray.add(url); } iterator = urlarray.iterator(); MyAsyncTask task = new MyAsyncTask(); task.execute();}private class MyAsyncTask extends AsyncTask<Object,Void,ArrayList<String>>{ int urlNumber; ArrayList<String> resultList = new ArrayList<>(); HttpURLConnection connection=null; BufferedReader reader=null; public MyAsyncTask (){ } @Override protected String doInBackground(Object... params) { if(iterator.hasNext()) { try { URL url = new URL(iterator.next()); connection= (HttpURLConnection) url.openConnection(); connection.connect(); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { buffer.append(line); } String json = buffer.toString(); resultList.add(json); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return resultList; } @Override protected void onPostExecute(ArrayList<String> s) { super.onPostExecute(s); //Log.d("TAG",s); if(s.size > 0){ //Your listview processing here. } } }