Search code examples
androidmultithreadingandroid-asynctaskbackground-thread

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();
    }
}

}


Solution

  • 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();
        }
    }