无法从asynctask传递当前活动

时间:2014-01-25 17:27:36

标签: android android-listview android-asynctask

我正在尝试将当前活动对象传递给自定义列表视图适配器,但是从异步类传递时会出现nullpointer异常。这是我的代码:

public class MainActivity extends Activity {

ListView list;
LazyAdapter adapter;

private ProgressDialog pDialog;

// URL to get contacts JSON
private static String url = "http://api.androidhive.info/contacts/";

// JSON Node names

 static final String Events_date = "ev_date";
 static final String TAG_CONTACTS = "contacts";
 static final String TAG_ID = "id";
 static final String TAG_NAME = "name";
 static final String TAG_EMAIL = "email";
 static final String TAG_ADDRESS = "address";
 static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";

// contacts JSONArray
JSONArray contacts = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    contactList = new ArrayList<HashMap<String, String>>();

    // Calling async task to get json
    new GetContacts().execute();        
}

/**
 * Async task class to get json by making HTTP call
 * */
private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                contacts = jsonObj.getJSONArray(TAG_CONTACTS);

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

                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);
                    String email = c.getString(TAG_EMAIL);
                    String address = c.getString(TAG_ADDRESS);
                    String gender = c.getString(TAG_GENDER);

                    // Phone node is JSON Object
                    JSONObject phone = c.getJSONObject(TAG_PHONE);
                    String mobile = phone.getString(TAG_PHONE_MOBILE);
                    String home = phone.getString(TAG_PHONE_HOME);
                    String office = phone.getString(TAG_PHONE_OFFICE);

                    // tmp hashmap for single contact
                    HashMap<String, String> contact = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    contact.put(TAG_ID, id);
                    contact.put(TAG_NAME, name);
                    contact.put(TAG_EMAIL, email);
                    contact.put(TAG_PHONE_MOBILE, mobile);

                    // adding contact to contact list
                    contactList.add(contact);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        list=(ListView)findViewById(R.id.list);

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

这里是adapterclass主要代码片段

public class LazyAdapter extends BaseAdapter {

private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
// public ImageLoader imageLoader; 

public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data=d;
    inflater =     (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   // imageLoader=new ImageLoader(activity.getApplicationContext());
}

public int getCount() {
    return data.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.list_row, null);

    TextView title = (TextView)vi.findViewById(R.id.title); // title
    TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
    TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
    HashMap<String, String> song = new HashMap<String, String>();
    song = data.get(position);

    // Setting all values in listview
    title.setText(song.get(CustomizedListView.KEY_TITLE));
    artist.setText(song.get(CustomizedListView.KEY_ARTIST));
    duration.setText(song.get(CustomizedListView.KEY_DURATION));
 //   imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
    return vi;
}
  }

我知道我应该传递MainActivity的实例。所以,任何人都可以告诉我该怎么做,好像我从postexecute调用一个函数然后也得到nullpointer因为数据没有被插入hashmap.Kindly帮助!!!

Log cat:

01-25 23:08:29.779: D/Response:(607):                 "name": "Clint Eastwood",
01-25 23:08:29.779: D/Response:(607):                 "address": "xx-xx-xxxx,x - street, x - coun
01-25 23:08:30.029: D/AndroidRuntime(607): Shutting down VM
01-25 23:08:30.029: W/dalvikvm(607): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-25 23:08:30.052: E/AndroidRuntime(607): FATAL EXCEPTION: main
01-25 23:08:30.052: E/AndroidRuntime(607):  at info.androidhive.jsonparsing.MainActivity$GetContacts.onPostExecute(MainActivity.java:155)
01-25 23:08:30.052: E/AndroidRuntime(607):  at info.androidhive.jsonparsing.MainActivity$GetContacts.onPostExecute(MainActivity.java:1)

3 个答案:

答案 0 :(得分:0)

使用MainActivity.this引用嵌套类(例如异步任务)中的父类this

但是,这要求你保持asynctask嵌套类非静态,这不是一个好主意。非静态嵌套类保存对其父级的引用(在本例中为活动),并且由于活动和asynctask生命周期不同,asynctask可以保持错误的活动太长时间。

答案 1 :(得分:0)

使用adapter=new LazyAdapter(MainActivity.this, contactList);

只有this将传递asynctask类上下文。

答案 2 :(得分:0)

您可以为AsyncTask创建一个新的构造函数,接受一个Activity作为输入参数

public GetContacts(Activity mActivity){
this.mActivity = mActivity;}

在doInBackground方法中,您可以使用mActivity但要注意,除非您有对Activity的引用,否则这个不会死。

从MainActivity创建AsyncTask时,您可以将其作为输入参数传递,它应该可以正常工作。