0

I'm initializing an adapter with a cursor, and setting the adapter to a listview.

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

When I make the query in dbh.getMoviesTableCursor() method, I run said query in seperate thread

private Cursor getMoviesTableCursor(){

    ...

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

        }
    }.start();

    ...

    return moviesTableCursor;
}

Now my listview does not show anything, versus when I did not run the query in a new thread like so

private Cursor getMoviesTableCursor(){

    ...


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

    ...

    return moviesTableCursor;
}

So I tried updating the cusor using a handler with notifyDataSetChanged()

final Handler handler = new Handler();
private Cursor getMoviesTableCursor(){

    ...

    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.
                    // FragmentMovies.myAdapter.notifyDataSetChanged();

                    MyActivity.myAdapter.notifyDataSetChanged();
                }
            });

        }
    }.start();

    ...

    return moviesTableCursor;
}

But notifyDataSetChanged() does not refresh the cursor in myAdapter

Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79
the_prole
  • 8,275
  • 16
  • 78
  • 163
  • `MyActivity.myAdapter`... static variables are bad – OneCricketeer Nov 09 '16 at 02:20
  • Generally speaking, you want callbacks, like this post addresses (you could also use AsyncTask instead). http://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a – OneCricketeer Nov 09 '16 at 02:23
  • There are several ways to fix this. 1. using AsyncTask. You can put database process in doInBackground function and ui process in onPostExecute. 2. using Handler. After getting moviewTableCursor, you need to send message using handler to main Activity. And in activity, you can call adapter.notifyDataSetChanged() – Yuichi Akiyoshi Nov 09 '16 at 02:38
  • @ZhaoLin I am using a handler. Am I doing it incorrectly? – the_prole Nov 09 '16 at 03:19
  • Hi @the_prole. Can you share you Adapter class source code? – Yuichi Akiyoshi Nov 09 '16 at 12:04

0 Answers0