Android适配器无法更新

时间:2014-09-06 16:40:35

标签: android android-listview

我有一个适配器,我想将数据添加到适配器。这是我的源代码:

private static class Random{
    public  JsonObject randomData=null;
    public  Integer badgeNumber=null;

    private Random(JsonObject randomData,Integer badgeNumber) {
        this.randomData=randomData;
        this.badgeNumber=badgeNumber;
    }
}

private static class Randoms{
    private List<Random> randoms=null;

    public Randoms(List<Random> randoms) {
        this.randoms=randoms;
    }
    public Random get(int position) {
        return randoms.get(position);
    }
    public int size() {
        return randoms.size();
    }
}
private static class RandomsAdapter extends BaseAdapter{
    private Randoms randoms;
    private LayoutInflater inflater;
    private RandomsAdapter(Context context,Randoms randoms) {
        this.randoms=randoms;
        this.inflater = LayoutInflater.from(context);
    }
    public void updateRandoms(Randoms randoms) {
        this.randoms=randoms;
        notifyDataSetChanged();
    }
    @Override
    public int getCount() {
        return randoms.size();
    }
    @Override
    public Random getItem(int position) {
        return randoms.get(position);
    }
    @Override
    public long getItemId(int position) {
        return 0;
    }
    public View getView(int position,View convertView,ViewGroup parent) {
        View view=convertView;

        if (convertView == null) {
            convertView=inflater.inflate(R.layout.random_bars,parent,false);
        }
        Random item=getItem(position);
        Log.w("testt",""+item);
        return convertView;
    }
}

我正在用这段代码定义适配器:

Randoms randoms=new Randoms(randomsList);
randomsAdapter=new RandomsAdapter(this,randoms);
listView = (ListView)findViewById(R.id.list);
listView.setAdapter(randomsAdapter);

当我尝试添加数据时,我正在使用此行

randomsList.add(new Random(result.get(i).getAsJsonObject(),1));

但这不起作用,我无法看到任何日志与&#34; testt&#34;我怎么解决这个问题?

我的意思是getView方法无效。

3 个答案:

答案 0 :(得分:0)

添加

randomsList.add(new Random(result.get(i).getAsJsonObject(),1));

在适配器上调用notifyDataSetChanged()

randomsAdapter.notifyDataSetChanged();

修改

((RandomsAdapter) randomsAdapter)notifyDataSetChanged();

答案 1 :(得分:0)

尝试:

randomsAdapter.invalidate();

OR

((RandomsAdapter) randomsAdapter)).notifyDataSetChanged(); 

如果不起作用,请参阅此主题: stackoverflow.com/questions/4088862/android-list-view-refresh/4088889

答案 2 :(得分:0)

正如其他人所建议的那样,使用

randomsAdapter.notifyDataSetChanged();

如果您收到类似&#34的错误; notifyDataSetChanged() ListAdapter未定义getAdapter()&#34;,我猜是因为您正在通过&#39;来获取您的适配器ListAdapter或此类返回BaseAdapter的方法。在这种情况下,您应该将其投放到RandomsAdapter((RandomsAdapter) randomsAdapter).notifyDataSetChanged(); 。例如,

{{1}}
相关问题