Android NotifyDatasetChanged未显示我的列表
这是我的密码 我想在listview中显示我的事件,但它不显示任何内容 这是我的密码Android NotifyDatasetChanged未显示我的列表,android,Android,这是我的密码 我想在listview中显示我的事件,但它不显示任何内容 这是我的密码 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_events_by_date); Intent i = getIntent();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_events_by_date);
Intent i = getIntent();
dateString = i.getExtras().getString("Date");
elist = (ListView) findViewById(R.id.eventList);
arraylist = new ArrayList<YourEvent>();
adapter = new CustomAdapter(ShowEventsByDateActivity.this, arraylist);
getEvents();
elist.setAdapter(adapter);
}
private void getEvents() {
for(int a=0;a<StaticVariables.eventIds.size(); a++){
if(StaticVariables.eventDates.get(a).equals("6-12-2015")){
eId.add(StaticVariables.eventIds.get(a));
eTitle.add(StaticVariables.eventTitles.get(a));
eDetail.add(StaticVariables.eventDetails.get(a));
eType.add(StaticVariables.eventTypes.get(a));
eDate.add(StaticVariables.eventDates.get(a));
eTime.add(StaticVariables.eventTimes.get(a));
eLocation.add(StaticVariables.eventLocations.get(a));
eChoice.add(StaticVariables.eventChoices.get(a));
}
}
arraylist.clear();
for (int i = 0; i < eId.size(); i++) {
YourEvent ye = new YourEvent(eId.get(i), eTitle.get(i),
eType.get(i), eDetail.get(i), eDate.get(i),
eTime.get(i), eLocation.get(i), eChoice.get(i));
arraylist.add(ye);
}
adapter.notifyDataSetChanged();
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity按日期显示事件);
Intent i=getIntent();
dateString=i.getExtras().getString(“日期”);
elist=(ListView)findViewById(R.id.eventList);
arraylist=新的arraylist();
adapter=新的CustomAdapter(ShowEventsByDateActivity.this,arraylist);
getEvents();
elist.setAdapter(适配器);
}
私有void getEvents(){
对于(int a=0;a只需交换这两行:
getEvents(); //this would come after setAdapter
elist.setAdapter(adapter);
到
问题在于适配器中的以下行:
this.arraylist = new ArrayList<YourEvent>();
this.arraylist.addAll(yeList);
this.arraylist=new arraylist();
this.arraylist.addAll(yeList);
这会将原始值从列表(为空)复制到仅位于适配器内部的新列表
然后,在活动中添加值时,将它们添加到原始列表中,该列表与适配器中的列表不同
执行.addAll()时,两个列表之间的引用将丢失,因为它会按值复制,而不是按引用复制
要解决此问题,只需:
1) 将arraylist
重构为列表,而不是arraylist
2) 设置this.arraylist=yeList
,而不是我上面发布的两行
这将正确地保持两个列表之间的引用,因此当您在活动中向列表添加新元素并调用
notifyDataSetChanged()时
,它将在列表中显示它们。getCount无法返回0。简直不敢相信我犯了这么愚蠢的错误:/浪费了3个小时,以为我在其他地方遇到了问题-u-非常感谢先生:)希望我能对你的答案投上一票,但这只是一条评论。我尝试了这个,没有奏效,或者我得了第2分,但没有得到第1分,为什么你不呢让我这么做?@blackbelt的回答解决了我的问题,我在getcount中返回了0-\uz-愚蠢的错误:/但是也谢谢你的解决方案:)
elist.setAdapter(adapter);
getEvents();
this.arraylist = new ArrayList<YourEvent>();
this.arraylist.addAll(yeList);