【问题标题】:uunable to pass current activity from asynctask无法从 asynctask 传递当前活动
【发布时间】:2014-01-25 17:27:36
【问题描述】:

我正在尝试将当前活动对象传递给自定义列表视图适配器,但由于它是从异步类传递的,因此出现空指针异常。这是我的代码:

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的主要代码sn-ps

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 调用一个函数然后也得到空指针,因为数据没有被插入到 hashmap 中。请帮助!!!

原木猫:

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)

【问题讨论】:

  • 请发布堆栈跟踪。

标签: android android-listview android-asynctask


【解决方案1】:

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

但是,这要求您将 asynctask 嵌套类保持为非静态,这不是一个好主意。非静态嵌套类持有对其父级(在本例中为活动)的引用,并且由于活动和异步任务的生命周期不同,异步任务可能会保持错误活动的时间过长。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      在 doInBackground 方法中,您可以使用 mActivity,但请注意,在您引用 Activity 之前,这个不能死。

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

      【讨论】:

        猜你喜欢
        • 2016-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-28
        • 2017-06-14
        • 1970-01-01
        相关资源
        最近更新 更多