Android 异步类与 setListAdapter
我有一个 Activity 类,其中有一个扩展 AsyncTask 的内部受保护类。当我单击按钮时,我试图让 AsyncTask 在后台加载数据,然后显示基于该数据的列表。
这是我的 setListAdapter 代码:
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_row,
R.id.rowtextview, testArr.toArray(test2)));
问题是我不能只将 setListAdapter 粘贴到 AsyncTask 类中,因为它需要外部类的上下文,并且它唯一可以去的地方是外部 Activity 中的 onCreate() 内部班级。如果它在 onCreate 内部,则只能使用一次并且不是动态的。我不确定每次单击按钮并搜索新内容时如何重新加载列表。
I have an Activity Class with an inner protected class that extends AsyncTask. I am trying to have the AsyncTask load data in background when I click a button and then display a list based on that data.
here is my code for the setListAdapter:
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_row,
R.id.rowtextview, testArr.toArray(test2)));
the problem is that I can't just stick setListAdapter into the AsyncTask class because it needs a context for the outer class, and the only place it can go is inside the onCreate() in the outer Activity class. If its inside the onCreate, it can only be used once and isnt dynamic. I am not sure how I would go about making the list re-load every time I click a button and search for something new.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的自定义内部 AsyncTask 未标记为静态,对吧?这意味着它实际上保存了对父类(即您的 Activity)的引用。所以你可以使用:
Your custom inner AsyncTask is not marked as static right? That means that it actually holds reference to the parent class, which is you Activity. So you can use:
很简单,让适配器成为一个实例变量并扩展它(很简单)以添加自定义
updateData(newData)
方法。在此方法中,您更新数据并调用notifyDatasetChanged()
。你就完成了!这样,您只需设置适配器一次,并在AsyncTask
返回时调用updateData()
即可。Easy, make the adapter an instance variable and extend it (trivial) to add your custom
updateData(newData)
method. In this method you update your data AND callnotifyDatasetChanged()
. And you're done! That way you only need to set the adapter once and just callupdateData()
when theAsyncTask
comes back.