Using Executer instead of AsyncTask to Get Data From Room Database in Android

Viewed 26

I am new to this concept and trying to follow a YouTube tutorial, in the video, he used AsyncTask to add the note object to the DB and AsyncTask to retrieve the data

He used this code to add the notes to DB

class AddNotesToDatabase extends AsyncTask<Void,Void,Void> {

        @Override
        protected Void doInBackground(Void... voids) {
            NotesDatabase.getDatabase(getApplicationContext())
                                .noteDao()
                                        .insertNote(note);
        }

        @Override
        protected void onPostExecute(Void unused) {
            super.onPostExecute(unused);
            //finish the activity
        }
    }
    new AddNotesToDatabase.execute();

Which I easily replaced with this code after reading an answer on StackOverflow and it's working fine

ExecutorService executor = Executors.newSingleThreadExecutor();
            Handler handler = new Handler(Looper.getMainLooper());
            executor.execute(() -> {

                //adding the note object to the database
                NotesDatabase.getDatabase(getApplicationContext())
                                .noteDao()
                                        .insertNote(note);

                handler.post(() -> {
                    //progressBar.setVisibility(GONE);
                    //finish this activity and go back to my MainActivity
                });
            });

my problem starts when I want to call these notes back from the database. In the tutorial, he used this code

private void getNotes() {

        @SuppressLint("StaticFieldLeak")
        class GetNotesFromDatabaseTask extends AsyncTask<Void,Void,List<Note>> {

            @Override
            protected List<Note> doInBackground(Void... voids) {
                //get the notes list from Room database
                //return that list
                return null;
            }

            @Override
            protected void onPostExecute(List<Note> notes) {
                super.onPostExecute(notes);
                //assign the returned list to my original list
            }
        }

        new GetNotesFromDatabaseTask().execute();
    }

I can't figure out how would I replace this code and use java.util.concurrent instead to return a list of note objects.

Any help would be much appreciated

0 Answers
Related