【问题标题】:Creating an ArrayList from SQLite DB is very slow从 SQLite DB 创建 ArrayList 非常慢
【发布时间】:2013-08-28 08:47:54
【问题描述】:

好的,所以我正在尝试从我的 SQLite DB 创建一个小而轻量级的ArrayList。

代码如下:

public ArrayList<Album> getAlbums()
{
    Cursor cursor = null;
    Cursor cursor2 = null;
    try{
        Log.d(Global.TAG, "STARTING");
        ArrayList<Album> albums = new ArrayList<Album>();
        Album album = new Album();
        db = getOpenDatabase(DBADS);
        String albumQuery = "SELECT * FROM " +albumsTableName + " ORDER BY " +albumIsMain + " DESC"; 
        cursor = db.rawQuery(albumQuery, null);
        if (cursor.moveToFirst()){
            do {
                Log.d(Global.TAG, "IN LOOP");
                album = new Album();
                album.id = cursor.getInt(0);
                album.albumName = cursor.getString(1);
                album.passcode = cursor.getString(2);
                album.isMainAlbum = cursor.getInt(3) == 1 ? true : false;
                albumQuery = "SELECT COUNT(*) FROM " + picturesTableName+" WHERE "+ pictureAlbumId +"="+album.id;
                cursor2 = db.rawQuery(albumQuery, null);
                cursor2.moveToFirst();
                album.photosCount = cursor2.getInt(0);
                cursor2.close();

                albums.add(album);
            }
            while (cursor.moveToNext());
        }
        Log.d(Global.TAG, "RETURNING");
        return albums;
    }
    catch(Exception ex)
    {
        Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
    }
    finally
    {
        if(cursor != null){
            cursor.close();
        }
        if(cursor2 != null){
            cursor2.close();
        }
        if(cursor3 != null){
            cursor3.close();
        }
    }
    return null;

}

以下代码在 8 秒内执行,总共只有 6 个项目!这只是非常缓慢。
这里没有 1000 行,但只有 6 行。 经过一些调试,我发现如果我删除另一个第二个内部光标,它会变得非常快。

这可能是什么原因?

非常感谢。

【问题讨论】:

    标签: java android sqlite android-listview arraylist


    【解决方案1】:

    将第一个 select 语句的结果保存在列表中。然后将它们同时传递给第二个选择调用。现在你正在进行大量的数据库调用

    【讨论】:

    • 我不太明白,请您提供进一步的解释或示例吗?
    • 看count操作需要很多时间。因此,在第一个 do while 循环中列出一张专辑 ID。然后,您可以将所有专辑 ID 一起传递(在 do-while 循环之外),而不是专辑 ID: SELECT albumId FROM " + picturesTableName+" WHERE "+ pictureAlbumId +"in ("+albumIdList + ")";..... ..........现在您需要遍历结果并计算返回特定专辑 ID 的次数。这将需要更多的 java 编码,但会减少 db 调用。
    • 我已经尝试实现你的想法,这里是代码:pastebin.com/d4VUq3TP 但我收到一个错误:sqlite 返回:错误代码 = 1,msg = 没有这样的列:1、2、 3、4、5
    • 感谢您的帮助。
    • 在关联的 PasteBin 中,我忘记在“IN”关键字之前放置一个空格,我在原始代码中修复了它,但我仍然遇到同样的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    • 2013-01-30
    • 2012-02-08
    • 1970-01-01
    • 2021-05-01
    相关资源
    最近更新 更多