Skip to content Skip to sidebar Skip to footer

Having Trouble With Async And Listadapter Can You Help Out?

package com.example.simpleasync; import java.util.ArrayList; import java.util.HashMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; i

Solution 1:

Maybe you can try this:

package com.example.simpleasync;

import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

publicclassProgressTaskextendsAsyncTask<String, Void, Void> {
 private ProgressDialog dialog;
 private ListActivity activity;
 private Context context;

 ArrayList<HashMap<String, String>> jsonlist = newArrayList<HashMap<String, String>>();
 ListView lv ;

 privatestaticStringurl="http://api.cartperk.com/v1/supportedoperator";

 privatestaticfinal String OPCODE="code";
 privatestaticfinal String OPNAME="name";

 publicProgressTask(ListActivity activity) {
     this.activity = activity;
     context = activity;
     dialog = newProgressDialog(context);
 }

 protectedvoidonPreExecute() {
     this.dialog.setMessage("Progress start");
     this.dialog.show();
 }

@Overrideprotected Void doInBackground(final String... args) {
    JSONParserjParser=newJSONParser();
    JSONArrayjson= jParser.getJSONFromUrl(url);

    for (inti=0; i < json.length(); i++)
    {
        try {
            JSONObjectc= json.getJSONObject(i);
            Stringopcode= c.getString(OPCODE);
            Stringopname= c.getString(OPNAME);

            HashMap<String, String> map = newHashMap<String, String>();

            map.put(OPCODE,opcode);
            map.put(OPNAME,opname);
            jsonlist.add(map);
        }
        catch(JSONException e)
        {
            e.printStackTrace();
        }
    }

    returnnull;
}

@OverrideprotectedvoidonPostExecute(final Boolean success) {
  if (dialog.isShowing()) {
    dialog.dismiss();
  }

  ListAdapteradapter=newSimpleAdapter(context, jsonlist,
        R.layout.list_item, newString[] { OPCODE, OPNAME}, newint[] {
        R.id.opcode, R.id.opname});

  activity.setListAdapter(adapter);

  // select single ListView item
  lv = activity.getListView();
}

You need to use activity object to setListAdapter and getListView. And if you don't want doInBackground(...) return a Boolean, you can use Void and return a null.

Post a Comment for "Having Trouble With Async And Listadapter Can You Help Out?"