-2

How to use asynctask to show listview from json how to put

onPreExecute()

onPostExecute()

doInBackground()

onProgressUpdate()

MainActivity.java

list = (ListView) activity.findViewById(R.id.listView1);
        ArrayList<HashMap<String, String>> followingList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(URL);

        try {
            // Getting Array of Following
            following = json.getJSONArray(KEY_FOLLOWING);

            // looping through All Following
            for(int i = 0; i < following.length(); i++){
                JSONObject c = following.getJSONObject(i);

                // Storing each json item in variable
                String nama = c.getString(KEY_NAMA);
                String instansi = c.getString(KEY_INSTANSI);
                String status = c.getString(KEY_STATUS);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(KEY_NAMA, nama);
                map.put(KEY_INSTANSI, instansi);
                map.put(KEY_STATUS, status);
                // adding HashList to ArrayList
                followingList.add(map);

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


        // Getting adapter by passing xml data ArrayList
        adapter1=new LazyAdapter(this, followingList);
        list.setAdapter(adapter1);

How to implementation asycntask to show list view?

DashboardTask

package net.drieanto.lagidimana;

import net.drieanto.lagidimana.library.DatabaseHandler;
import net.drieanto.lagidimana.library.JSONParser;
import net.drieanto.lagidimana.library.UserFunctions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

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

    private ProgressDialog progressDialog;
    private DashboardActivity activity;

    ListView list1;
    LazyAdapter adapter1;
    private ListView list;

    // All static variables
    static final String URL = "http://git.drieanto.net/LagiDimanaAPI/index.php/user/get_following/XX3";
    // JSON node keys
    private int responseCode = 0;
    static final String KEY_FOLLOWING = "following";
    static final String KEY_NAMA = "nama"; // parent node
    static final String KEY_INSTANSI = "instansi";
    static final String KEY_STATUS = "status";
    private static String KEY_SUCCESS = "success";
    private static String KEY_ERROR = "error";

    // following JSONArray
    JSONArray following = null;

    public DashboardTask(DashboardActivity activity,
            ProgressDialog progressDialog) {
        this.activity = activity;
        this.progressDialog = progressDialog;
    }

    @Override
    protected void onPreExecute() {
        progressDialog.show();
    }

    @Override
    protected Integer doInBackground(String... arg0) {
        // check for login response
        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(URL);
        try {
            if (json.getString(KEY_SUCCESS) != null) {
                String res = json.getString(KEY_SUCCESS);

                if (Integer.parseInt(res) == 1) {
                    responseCode = 1;

                } else {
                    responseCode = 0;
                    // Error in login
                }
            }

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

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

        return responseCode;
    }

    @Override
    protected void onPostExecute(Integer responseCode) {
        if (responseCode == 1) {
            progressDialog.dismiss();
            ArrayList<HashMap<String, String>> followingList = new ArrayList<HashMap<String, String>>();

            // Creating JSON Parser instance
            JSONParser jParser = new JSONParser();

            // getting JSON string from URL
            JSONObject json = jParser.getJSONFromUrl(URL);

            try {
                // Getting Array of Following
                following = json.getJSONArray(KEY_FOLLOWING);

                // looping through All Following
                for (int i = 0; i < following.length(); i++) {
                    JSONObject c = following.getJSONObject(i);

                    // Storing each json item in variable
                    String nama = c.getString(KEY_NAMA);
                    String instansi = c.getString(KEY_INSTANSI);
                    String status = c.getString(KEY_STATUS);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(KEY_NAMA, nama);
                    map.put(KEY_INSTANSI, instansi);
                    map.put(KEY_STATUS, status);
                    // adding HashList to ArrayList
                    followingList.add(map);

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

            // Getting adapter by passing xml data ArrayList
            adapter1 = new LazyAdapter(activity, followingList);
            list.setAdapter(adapter1);
        } else {
            progressDialog.dismiss();
            activity.showDashboardError(responseCode);

        }

    }

}

But contain error whats wrong?

1 Answers1

0

You can use the following

    ProgressDialog pd; 
    LazyAdapter adapter1;  
    ListView list; 
    String URL; 
    HashMap<String, String> map = new HashMap<String, String>();
    ArrayList<HashMap<String, String>> followingList = new ArrayList<HashMap<String, String>>();

In your activity onCreate()

    setContentView(R.layout.activity_main);
    list = (ListView)findViewById(R.id.listView1);    
    pd = new ProgressDialog(ActivityName.this);
    pd.setTitle("Processing..."); 
    URL ="your url";  
    new TheTask().execute();

Define Asynctask as a inner class in your activity class

    class extends AsyncTask<Void,Void,Void>
    {
    @Override
    protected void onPreExecute() {
    super.onPreExecute();
    pd.show();
     }

   @Override
    protected Void doInBackground(Void... params) {
             // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(URL);

    try {
        // Getting Array of Following
        following = json.getJSONArray(KEY_FOLLOWING);

        // looping through All Following
        for(int i = 0; i < following.length(); i++){
            JSONObject c = following.getJSONObject(i);

            // Storing each json item in variable
            String nama = c.getString(KEY_NAMA);
            String instansi = c.getString(KEY_INSTANSI);
            String status = c.getString(KEY_STATUS)

            // adding each child node to HashMap key => value
            map.put(KEY_NAMA, nama);
            map.put(KEY_INSTANSI, instansi);
            map.put(KEY_STATUS, status);
            // adding HashList to ArrayList
            followingList.add(map);

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

    return null;
   }

   @Override
   protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    pd.dismiss();
    adapter1=new LazyAdapter(ActivityName.this, followingList);
    list.setAdapter(adapter1);
  }  
  } 

Exaplanation

AsyncTask is invoked on the UI thread.

onPreExecute() invoked on UI Thread. display progress dialog

doInBackground() invoked on the background thread. do some operation. Do not update UI here

OnPostExecute() invoked on UI thread. dismiss dialog and update ui here.

For more info check the doc

http://developer.android.com/reference/android/os/AsyncTask.html

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • you are doing network related operation in onPostExecute. onPostExecute in invoked on the UI thread. Do all network related operation in doInBackground(). return result in doInBackground(). The returned result is a parameter to onPostExecute() dimiss the dialog and update ui .Pls check the topic under The 4 steps in the link posted in the answer – Raghunandan May 10 '13 at 08:33
  • 05-10 15:32:03.240: E/AndroidRuntime(21098): android.os.NetworkOnMainThreadException 05-10 15:32:03.240: E/AndroidRuntime(21098): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099) 05-10 15:32:03.240: E/AndroidRuntime(21098): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84) 05-10 15:32:03.240: E/AndroidRuntime(21098): at libcore.io.IoBridge.connectErrno(IoBridge.java:127) 05-10 15:32:03.240: E/AndroidRuntime(21098): at libcore.io.IoBridge.connect(IoBridge.java:112) 05-10 15:32:03.240: E/AndroidRuntime(21098): at java. – Edwin Andrianto May 10 '13 at 08:42
  • @EdwinAndrianto read the above comment onPostExecute in invoked on the UI thread. you cannot get json from url in onPostExecute. This will cause NetworkOnMainThreadException Move that part of the code to doInBackground(). display listview in adapter in onPostExecute() – Raghunandan May 10 '13 at 08:47
  • list.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(activity, "hae", Toast.LENGTH_SHORT).show(); } }); – Edwin Andrianto May 11 '13 at 15:06
  • use this Toast.makeText(ActivityName.this, "clickded", 1000).show(); where ActivityName is the name of your activity class – Raghunandan May 11 '13 at 15:07
  • how to add action click in list view using asynctask – Edwin Andrianto May 11 '13 at 15:27
  • i try add click action in DashboardTask but forced close – Edwin Andrianto May 11 '13 at 15:28
  • 05-11 22:02:39.539: E/AndroidRuntime(2350): java.lang.RuntimeException: Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead – Edwin Andrianto May 11 '13 at 15:29
  • @EdwinAndrianto you can have click listeners for listview check the link here http://stackoverflow.com/questions/7645880/list-view-with-on-item-click-listener-android – Raghunandan May 11 '13 at 16:07
  • maybe you can help http://stackoverflow.com/questions/16505499/how-to-get-one-paramater-from-list-view thanks – Edwin Andrianto May 12 '13 at 08:26