简体   繁体   中英

Android App update view with value from database

So I am currently in the early stages of writing an Android app in Java, using Android Studio. I have the MainActivity, which consists of a TextView and a Button.

The idea is that when I press the button, an entity-objekt is fetched from a Room-Database, a String-Member is extracted from the object and then used to set the new text for the TextView. I would preferably do this in such a way that by pressing the button a new object is fetched from the database and the TextView is updated, all without having to start a new Activity.

The onClick-Method for the button looked something like this in its first version:

private void getFoo() {
    Foo foo = db.fooDao().getRandom();
    String fooName = foo.getFooName();
    textFoo.setText(fooName);
}

The first problem was that I tried fetching the object from database as is, in the main thread, which the compiler was not happy about. Tried to wrap the database interaction into a seperate thread, but then I either had to figure out how to make the value fetched inside the thread to be available outside of it OR I had to nest a call to runOnUiThread in my Thread run() method.

I've had mixed results, with one configuration you could see the new text be displayed on screen, and a split-second after that the app crashed.

Can I make this work as an update of my view within the same Activity or should I instead just start a new one?

Okay I have overlooked a different SO question that perfectly solved my problem. My code for my getFoo now basically looks like this and fulfils the intended function:

private void getFoo() {
    class LoadFooTask extends AsyncTask<Void, Void, Foo> {
        @Override
        protected Foo doInBackground(Void... voids) {
            return db.fooDao().getRandom();
        }

        @Override
        protected void onPostExecute(Foo foo) {
            String FooName = foo.getFooName();
            textFoo.setText(fooName);
        }
    }
    LoadDishTask loadDishTask = new LoadDishTask();
    loadDishTask.execute();
}

The asynchronous task of loading from the database is done inside the doInBackground() method and the UI update is done on the main thread via the onPostExecute() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM