GridView CustomAdapter notifyDataSetChanged方法问题

时间:2015-04-22 11:33:33

标签: android gridview

我有一个片段,使用CustomAdapter(extending BaseAdapter)加载了GridView。从服务器检索数据,因此,我试图在下载完成后调用适配器上的notifyDataSetChanged。但是,GridView在下载后无法加载内容。

以下是我的一些代码段:

GridView gridview;
CustomAdapter mCustomAdapter;
List<Item> listItems = new ArrayList<Item>();

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_main, container, false);
    ....
    ....

    mCustomAdapter = new CustomAdapter(activity, listItems);
    gridview = (GridView) view.findViewById(R.id.gridview);
    gridview.setAdapter(mCustomAdapter);

    // This is the call for retrieving data from Server
    checkRefreshTimeAndGetData();

    return view;

}

获取数据后,我在下面的方法中调用notifyDataSetChanged():

public void checkRefreshTimeAndGetData(){
    ....
    ....

    listItems.clear();

    if (!mMainTableDbAdapter.isTableEmpty(
    prefs.getInt(Const.Prefs.MAIN_INDEX, DEFAULT_VALUE),
    prefs.getInt(Const.Prefs.SUB_INDEX, DEFAULT_VALUE))){
        listItems = mMainTableDbAdapter.getTitles(
        prefs.getInt(Const.Prefs.MAIN_INDEX, DEFAULT_VALUE),
        prefs.getInt(Const.Prefs.SUB_INDEX, DEFAULT_VALUE));
    }

    // At this point, i checked if listItems has values, 
    // and it has 100 items in it. So, its not empty.

    mCustomAdapter.notifyDataSetChanged();
}

CustomAdapter:

public class CustomAdapter extends BaseAdapter {

    private List<Item> items;
    private LayoutInflater vi;
    private List<Boolean> selectedState = new ArrayList<Boolean>();
    String imagepath = "";

    int curPos = 0;

    public CustomAdapter(Context context, List<Item> items) {
        this.items = items;
        vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return items.size();
    }

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

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

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

        ....
        ....

    }
}

我做错了什么?如果需要任何其他数据,请告诉我。

1 个答案:

答案 0 :(得分:5)

这是一条出路

refresh(..)

中制作Adapter
 public void refresh(List<Item> items)
 {
    this.items = items;
    notifyDataSetChanged();
 } 

并像

一样使用它
 listItems.clear();
 mCustomAdapter.refresh(listItems); //pass update list