我将在列表视图中加载更多数据。我可以加载更多数据,但它会删除以前的数据。
如何在列表视图中附加数据?
这是我的源代码:
MainActivity类中的OnCreate方法
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recentposts);
lv = (ListView) findViewById(R.id.list);
//LoadContent();
lv.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
final int lastItem = firstVisibleItem + visibleItemCount;
if (chkLoad == true) {
if(lastItem == totalItemCount) {
chkLoad = false;
LoadContent();
}
}
}
});
}
MainActivity方法中的LoadContent()方法:
public void LoadContent(){
lv = (ListView) findViewById(R.id.list);
Post p = new Post(theCounter);
theCounter+=20;
if (p.GetLatestPosts(lv,MainActivity.this))
{
//"true"
}
}
帖子类中的GetLatestPosts方法
public boolean GetLatestPosts(ListView lv, Activity a) {
AsyncLatestPostTaskCompleteListener<String> mycb = new AsyncLatestPostTaskCompleteListener<String>();
final CallLatestPost task = new CallLatestPost(counter,a,mycb,lv);
task.execute("executer");
return true;
}
AsyncLatestPostTaskCompleteListener(),我将在Asynctask Compeleted之后调用。
public class AsyncLatestPostTaskCompleteListener<T> {
private PostAdapter adapter;
public void onTaskComplete(String result,ListView _list, Activity _activity) {
String tmpStr = result;
JSONArray ja_arr = null;
try {
if (tmpStr != "ERROR") {
ja_arr = new JSONArray(tmpStr);
JSONObject jo = null;
HashMap<String, String> map = new HashMap<String, String>();
for (int i=0; i < ja_arr.length(); i++){
jo = ja_arr.getJSONObject(i);
map = new HashMap<String, String>();
map.put("name", jo.getString("name"));
map.put("postid", jo.getString("IdPost"));
map.put("title", jo.getString("Title"));
map.put("date", jo.getString("Date"));
map.put("photo", jo.getString("photo"));
map.put("url", jo.getString("linkurl"));
map.put("desc", jo.getString("Description"));
jo.getString("Title") != null){
PostList.add(map);
}
adapter = new PostAdapter(_activity, PostList);
adapter.notifyDataSetChanged();
if ( pa == null ) {
pa = adapter;
} else {
// I Think, I shoud update Adapter Here...!
}
pa.notifyDataSetChanged();
_list.setAdapter(pa);
} else {
// ERROR
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("@@@==ERR", e.toString());
}
}
}
那么,我怎样才能解决我的问题。
答案 0 :(得分:0)
我不知道你在哪里实例化&#39; pa&#39;但问题是你每次都要创建一个新的适配器,然后覆盖&#39; pa&#39;。您需要从以下位置移开逻辑:
adapter = new PostAdapter(_activity, PostList);
adapter.notifyDataSetChanged();
if ( pa == null ) {
pa = adapter;
} else {
// I Think, I shoud update Adapter Here...!
}
pa.notifyDataSetChanged();
_list.setAdapter(pa);
要
if ( pa == null ) {
adapter = new PostAdapter(_activity, PostList);
pa = adapter;
}else{
pa.append(PostList); //You would need to create this method.
}
pa.notifyDataSetChanged();
_list.setAdapter(pa);