1.一开始这样的:
case R.id.scann_button:
//发送扫描生成音乐列表广播
Intent broadcast_scann = new Intent();
broadcast_scann.setAction(Constant.DB_SCANNMUSIC);
sendBroadcast(broadcast_scann);
//通知adapter数据更新
adapter.notifyDataSetChanged();
break;
错误原因:发送广播之后,系统立即执行的是下一句:adapter.notifyDataSetChanged();而此时adapter绑定的data并无更新。
2.处理完data之后再广播回activity,再调用adapter.notifyDataSetChanged();依然失效,代码如下:
public void onReceive(Context context, Intent intent) {
try
{
if (Constant.LISTVIEW_REFRESH.equals(intent.getAction()))
{
System.out.print(Constant.data);
adapter.notifyDataSetChanged();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
更新data相关代码:
public void query()
{
Constant.data = new ArrayList<Map<String, Object>>();
Map<String, Object> oneline = null;
Cursor cursor = db.rawQuery("select name,author,time,path from music_info", null);
while (cursor.moveToNext())
{
String name = cursor.getString(0); //获取第一列的值,第一列的索引从0开始
String author = cursor.getString(1);//获取第二列的值
String time = cursor.getString(2);//获取第三列的值
String path = cursor.getString(3);//获取第三列的值
oneline = new HashMap<String, Object>();
oneline.put("name", name);
oneline.put("author", author);
oneline.put("time", time);
oneline.put("path", path);
Constant.data.add(oneline);
}
}
原因:
其实adapter.notifyDataSetChanged();并不是对数据data本身的监听,而是对对原始数据源的监听;什么意思呢?就是说如果你是将原始data怎么add、remove、clear都可以,只要data还是对应的那块保存数据的内存;一旦你data = new 了一个新对象指向其他内存,你对新对象的任何改动都不会触发监听。例如上面的代码:
更新data使用了Constant.data = new ArrayList<Map<String, Object>>();
应此将此句改为Constant.data.clear(); 即可。