在ListView中加载更多json数据

时间:2011-11-24 12:07:57

标签: android json scroll android-listview

当用户向下滚动页面时,是否有人看到Android的示例加载更多json数据?我已经看到了使用静态数组并通过向其添加计数器来生成文本的各种示例,但我正在寻找使用json数据的示例,因此它会加载一些记录,然后当用户向下滚动时会加载更多等等

1 个答案:

答案 0 :(得分:2)

为列表项编写一个适配器,并添加一个附加新结果的方法

public class JsonListAdapter extends BaseAdapter {

   private List<JSONObject> list;

   public void appendList(List<JSONObject>pList) {
       if (list== null) {
           list= new List<JSONObject>();
       }
       if (pList != null) {
           list.addAll(pList);
           notifyDataSetChanged();
       }
   }
...
}

添加滚动侦听器以启动分页请求

private class PagingScrollListener implements OnScrollListener {

    private int lastOffset = 0;


    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        boolean isEndOfListReached = firstVisibleItem + visibleItemCount >= totalItemCount;
        boolean isOffsetRequested = lastOffset >= totalItemCount;

        if (isEndOfListReached && !isOffsetRequested) {
            lastOffset = totalItemCount;
            new PagingRequest(myListAdapter).execute(lastOffset);
        }
    }
...
}

加载下一批数据并更新适配器:

private static class PagingRequest extends AsyncTask<Integer, Void, List<JSONObject> {

   private JsonListAdapter mAdapter;

   public PagingRequest(JsonListAdapter adapter) {
      this.mAdapter = adapter;
   }

    protected ProductList doInBackground(Integer... params) {
        int offset = params[0];
        // PERFORM REQUEST WITH OFFSET
        return newResults;
    }

    protected void onPostExecute(List<JSONObject> result) {
        mAdapter.appendList(result);
    }
 }

免责声明:这只是基本策略,您仍然需要填写空白并适应您的代码。