自定义列表适配器和AsyncTask

时间:2015-01-24 06:34:07

标签: android custom-adapter

仅针对ListFragment的自定义适配器出现问题。 AsyncTask将对象数组返回给ListFragment,它实例化一个传递上下文的自定义适配器,要膨胀的布局和数据(对象数组)。 但是在运行时,我在自定义适配器的NullPointerException方法上得到getCount(),因为mData为空。

有谁知道如何处理它?如何"properly"将数据传递给customAdapter

THX!

AsyncTask onPostExecute():

@Override
protected void onPostExecute(Listing[] listings) {
    if (listings != null) {

        ListingFragment.mListings = listings;

    }
}

ListingFragment:

public class ListingFragment extends ListFragment {

public static ItemAdapter mAdapter;
public static Listing[] mListings;

// Constructor
public ListingFragment() {

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    FetchListing task = new FetchListing();
    String query = getArguments().getString("test");
    if (query != null) {
        task.execute(query);
    }

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mAdapter = new ItemAdapter(getActivity(), R.layout.item_row, mListings);
    setListAdapter(mAdapter);

}

ItemAdapter

public class ItemAdapter extends BaseAdapter {
Context mContext;
int mLayoutResourceId;
Listing mData[];

// Constructor
public ItemAdapter(Context context, int layoutResourceId, Listing[] data) {
    this.mContext = context;
    this.mLayoutResourceId = layoutResourceId;
    this.mData = data;
}



@Override
public int getCount() {
    return mData.length;
}

@Override
public Object getItem(int position) {
    return mData[position];
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View listItem = convertView;
    Listing listingItem = mData[position];

    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    listItem = inflater.inflate(mLayoutResourceId, parent, false);

    ImageView listingItemImageView = (ImageView) listItem.findViewById(R.id.listing_item_icon);
    TextView listingItemTextView = (TextView) listItem.findViewById(R.id.listing_item_name);

    listingItemImageView.setImageURI(Uri.parse(listingItem.getUrl()));
    listingItemTextView.setText(listingItem.getTitle());

    return listItem;
}
}

0 个答案:

没有答案