在单独的线程中进行查询会使列表视图为空

时间:2016-11-09 01:32:35

标签: android

我正在使用游标初始化适配器,并将适配器设置为listview。

DatabaseHelper dbh = new DatabaseHelper(getActivity());
Cursor c = dbh.getMoviesTableCursor();
myAdapter =  new DatabaseAdapter(getActivity(), c, 0);
listView.setAdapter(myAdapter);

当我在dbh.getMoviesTableCursor()方法中进行查询时,我在单独的线程中运行所述查询

private Cursor getMoviesTableCursor(){

    ...

    new Thread() {
        @Override
        public void run() {
            moviesTableCursor = qb.query(db, sqlSelect, null, null, null, null, null);

        }
    }.start();

    ...

    return moviesTableCursor;
}

现在我的listview没有显示任何内容,相比之下我没有在新线程中运行查询

private Cursor getMoviesTableCursor(){

    ...
    moviesTableCursor = qb.query(db, sqlSelect, null, null, null, 
    ...

    return moviesTableCursor;
}

知道为什么吗?

1 个答案:

答案 0 :(得分:0)

是的,它按预期工作。您的query在另一个主题中运行,您的getMoviesTableCursor在UI主题中运行 - >然后getMoviesTableCursor将返回一个空光标。为避免这种情况,您应该重写代码,如:

final Handler handler = new Handler();
new Thread() {
    @Override
    public void run() {
        moviesTableCursor = qb.query(db, sqlSelect, null, null, null, null, null);
        handler.post(new Runnable() {
        @Override
        public void run() {
            // use handler to avoid update UI from none-UI thread.
            //do your update list view adapter here.
        }
    });

    }
}.start();