Jan
Jan

Reputation: 13

Run the tasks in background ( AsyncTask )

In NoteInfoactivity I have a code below, but

Note allNote = NoteDatabase.getInstance(getApplicationContext()).noteDao().getAllNoteId(noteID);

is executed in main thread. How can i execute it in background? what is the best way?

public class NoteInfoActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_note_info);

    TextView textViewTitle = findViewById(R.id.textViewNoteTitle);
    TextView textViewPriority = findViewById(R.id.textViewPriority);

    Intent intent = getIntent();

    if (intent != null && intent.hasExtra("NoteID")) {
        long noteID = intent.getIntExtra("NoteID", -1);

        Note allNote = NoteDatabase.getInstance(getApplicationContext()).noteDao().getAllNoteId(noteID);

        String title = allNote.getTitle();
        int priority = allNote.getPriority();

        textViewTitle.setText(title);
        textViewPriority.setText(String.valueOf(priority));
        
    } else {
        Toast.makeText(getApplicationContext(), R.string.empty_not_saved, Toast.LENGTH_SHORT).show();
    }
}

}

Upvotes: 1

Views: 176

Answers (1)

Ilya Gazman
Ilya Gazman

Reputation: 32231

You can put it in a thread and then call for a handler to do the UI changes on the main thread.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_note_info);

    TextView textViewTitle = findViewById(R.id.textViewNoteTitle);
    TextView textViewPriority = findViewById(R.id.textViewPriority);

    Intent intent = getIntent();
    Handler handler = new Handler();

    if (intent != null && intent.hasExtra("NoteID")) {
        long noteID = intent.getIntExtra("NoteID", -1);
        
        new Thread(new Runnable() {
            @Override
            public void run() {
                Note allNote = NoteDatabase.getInstance(getApplicationContext()).noteDao().getAllNoteId(noteID);
                handler.post((Runnable) () -> {
                    String title = allNote.getTitle();
                    int priority = allNote.getPriority();

                    textViewTitle.setText(title);
                    textViewPriority.setText(String.valueOf(priority));
                });
            }
        }).start();
    } else {
        Toast.makeText(getApplicationContext(), R.string.empty_not_saved, Toast.LENGTH_SHORT).show();
    }
}

Upvotes: 1

Related Questions