在listview中加载大型数据库

时间:2013-07-26 20:09:34

标签: android database listview large-data

我有一个包含大约12000条记录的数据库,我希望在ListView中加载这些记录。我正在使用BaseAdapter。当我在ListView中加载项目时,它花了这么长时间。
有没有办法减少这个时间,例如我看到一个应用程序只加载有限数量的项目,直到滚动条到达ListView的末尾,然后它再加载更多物品。

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

您应该在列表中设置onScrollListener,并跟踪项目的可见性和偏移量。我在这里给你举个例子:

// Adapter for the custom list
adapter = new Adapter(this, activityList);
setListAdapter(adapter);
registerForContextMenu(getListView());
getListView().setOnScrollListener(new OnScrollListener(){
    public void onScroll(AbsListView lw, final int firstVisibleItem,
    final int visibleItemCount, final int totalItemCount) {

        switch(lw.getId()) {
            case android.R.id.list:     

                // Make your calculation stuff here. You have all your
                // needed info from the parameters of this function.

                // Sample calculation to determine if the last 
                // item is fully visible.
                final int lastItem = firstVisibleItem + visibleItemCount;
                if(lastItem == totalItemCount) {
                    // Last item is fully visible.
                    Log.i("a", "last item fully visible...");

                    try {
                        if(offset > 0){
                            int newLimit;
                            int oldOffset = offset;
                            if(offset >= limit){
                            newLimit = limit;
                            offset = offset - limit;
                        }
                        else{
                            newLimit = length;
                            offset = 0;
                        }
                        for (int i=0; i < newLimit; i++)
                        {
                            JSONObject item = jFeed.getJSONObject(i + length - oldOffset);
                            // Pulling items from the array

                            // Get list info
                            String sInfo = item.getString(TAG_INFO);
                            Log.i(MainActivity.class.getName(), "Info: " + sInfo);

                            // Populate the dynamic custom list
                            HashMap<String, String> map = new HashMap<String, String>();
                            map.put(KEY_INFO, sInfo);

                            activityList.add(map);
                        }
                        adapter.notifyDataSetChanged();

                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
        }
    }

    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // TODO Auto-generated method stub
        if(scrollState == 0) 
            Log.i("a", "scrolling stopped...");
    }
});