1

我有一个清单,每2秒钟通过Handler postDelayed()方法刷新。Android - 清单更新后返回顶部

每2秒的AsyncTask运行,使一个HTTP GET请求,变成JSON到对象的列表,然后设置ListAdapter:

MyListAdapter adapter = new MyListAdapter(someObjects); 
setListAdapter(adapter); 

我的问题是,每次任务完成(所以,大约每两秒钟),即使我已经滚动到列表的中间或底部,我的列表仍会跳回顶部。这对最终用户来说是非常烦人的,所以我需要在后台更新列表,因为它正在进行,但是列表的当前视图不会在完成AsyncTask时跳回顶部。

我可以包含任何更多所需的代码。我对android开发有点新,所以我不确定对别人有什么帮助。

其他信息

从hacksteak25考虑的建议,我能够得到的地方,我尝试从适配器删除所有的数据点,则一次添加回一个对象。这不是最终的解决方案,因为这可能仍然会导致屏幕跳跃,但我试图用它来证明我如何在某些时候合并数据。

我的问题是,我叫下面的代码:

MyListAdapter adapter = (MyListAdapter)getListAdapter(); 
adapter.clear(); 
for(MyObject myObject : myObjects) 
{ 
    adapter.add(myObject); 
} 

第一个电话后,以“增加(myObject的)”的MyListAdapter的getView()方法被调用。自定义适配器的私有内部ArrayList在此处为空,或者是因为我在onCreate()中设置了没有myObjects的适配器,或者因为我在适配器上调用了clear(),所以我不确定。无论哪种方式,这会导致getView失败,因为ArrayList中没有对象从中获取视图。

getView()看起来是这样的:

public View getView(int position, View convertView, ViewGroup parent) 
{ 
ViewHolder holder; 
LayoutInflater mInflater = getLayoutInflater(); 

if (convertView == null) 
{ 
    convertView = mInflater.inflate(R.layout.myObject, null); 

    holder = new ViewHolder(); 
    holder.someProperty = (TextView)convertView.findViewById(R.id.someProperty); 
    holder.someOtherProperty = (TextView)convertView.findViewById(R.id.someOtherProperty); 
    holder.someOtherOtherProperty = (TextView)convertView.findViewById(R.id.someOtherOtherProperty); 

    convertView.setTag(holder); 
} 
else 
{ 
    holder = (ViewHolder)convertView.getTag(); 
} 

// Bind the data efficiently with the holder. 
holder.someProperty.setText(mObjects.get(position).getSomeProperty()); 
... 

最后一行是导致IndexOutOfBoundsException异常的人。

我应该如何处理这种情况,我在那里得到我想要的数据而不会导致列表跳转?

回答

2

我认为首选的方法是更新适配器本身,而不是取代它。也许您可以编写一种方法,使用适配器insert()remove()方法合并新旧数据。我认为这应该保持你的立场。

添加信息:

我使用以下作为基本结构。也许它有帮助。


public class PlaylistAdapter extends ArrayAdapter<Playlist> { 

    private ArrayList<Playlist> items; 

    public PlaylistAdapter(Context context, int textViewResourceId, ArrayList<Playlist> items) { 
     super(context, textViewResourceId, items); 
     this.items = items; 
    } 

} 
+0

我试图看看我是否可以在尝试合并数据之前轻松工作。但是,此代码: MyListAdapter adapter =(MyListAdapter)getListAdapter(); adapter.clear(); (object object:objects) { adapter.add(object); } 产生一个java.lang。UnsupportedOperationException java.util.AbstractList.add 这很奇怪,因为MyListAdapter扩展了ArrayAdapter,它应该有可用的add方法。 – twilbrand 2010-09-07 19:55:53

+0

“java.util.AbstractList.add中的java.lang.UnsupportedOperationException”:你如何初始化超类?当我将适配器数据设置为数组(例如类型MyObject [])时,我遇到了同样的问题。尝试使用列表(例如类型ArrayList )。数组不能调整大小,但列表可以。这应该解决你的UnsupportedOperationException。 – hacksteak25 2010-09-08 01:11:26

+0

我试图将我的实现从使用MyObject []更改为ArrayList 。这需要一点重构,因为我使用的扩展ArrayAdapter 的自定义ListAdapter。在构造函数中,我使用ArrayList .toArray()来满足超级构造函数,因为找不到合适的ArrayAdapter替代品。无论哪种情况,我的应用程序都会运行,但数据现在不会显示。我可以显示哪些代码会有帮助? – twilbrand 2010-09-08 13:57:48