jonesr2017
jonesr2017

Reputation: 15

Android: if statement in AsyncTask doInBackground

I am trying to use an asynctask to display messages in a TextView within a fragment, but I only want it to display if a checkbox is checked. If I add an if statement in doInBackground I receive the error:

1544-1553/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks. java.lang.Throwable: Explicit termination method 'close' not called

Here is my AsyncTask:

class displayMessages extends AsyncTask<Void, String, Void> {
        @Override
        protected void onPreExecute() {


        }

        @Override
        protected Void doInBackground(Void... nothing) {

            for (int i = 0; i < 100; i++) {
                String currentMessage = i + " " + message;
                if (true) {publishProgress(currentMessage);}
                sleepT(500);

            }

            return null;
        }

        @Override
        protected void onProgressUpdate(String... string) {
            super.onProgressUpdate(string);
                messageText.append(string[0] + "\n");


        }

        @Override
        protected void onPostExecute(Void result) {

        }
    }

Upvotes: 1

Views: 896

Answers (1)

k3b
k3b

Reputation: 14755

You cannot access gui elements from the non gui-task. So this will not work.

   @Override
    protected Void doInBackground(Void... nothing) {
       ...
       checkbox.isChecked(); // accessing a gui element

But you can get the required info before you start the background task like this:

new displayMessages(checkbox.isChecked()).execute()

the class will look like this

class displayMessages extends AsyncTask<Void, String, Void> {
    private Boolean shouldPublish;
    public displayMessages(Boolean shouldPublish) {
        this.shouldPublish = shouldPublish;
    }

   @Override
    protected Void doInBackground(Void... nothing) {

        for (int i = 0; i < 100; i++) {
            String currentMessage = i + " " + message;
            if (shouldPublish) {publishProgress(currentMessage);}
            sleepT(500);

        }

        return null;
    }

}

Upvotes: 1

Related Questions