Skip to content
Fix Code Error

AsyncTask Android example

March 13, 2021 by Code Error
Posted By: Anonymous

I was reading about AsyncTask, and I tried the simple program below. But it does not seem to work. How can I make it work?

public class AsyncTaskActivity extends Activity {

    Button btn;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener((OnClickListener) this);
    }

    public void onClick(View view){
        new LongOperation().execute("");
    }

    private class LongOperation extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            for(int i=0;i<5;i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed");
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }
}

I am just trying to change the label after 5 seconds in the background process.

This is my main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical" >
    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:padding="10dip">
    </ProgressBar>
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Progress" >
    </Button>
    <TextView android:id="@+id/output"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Replace"/>
</LinearLayout>

Solution

Ok, you are trying to access the GUI via another thread. This, in the main, is not good practice.

The AsyncTask executes everything in doInBackground() inside of another thread, which does not have access to the GUI where your views are.

preExecute() and postExecute() offer you access to the GUI before and after the heavy lifting occurs in this new thread, and you can even pass the result of the long operation to postExecute() to then show any results of processing.

See these lines where you are later updating your TextView:

TextView txt = findViewById(R.id.output);
txt.setText("Executed");

Put them in onPostExecute().

You will then see your TextView text updated after the doInBackground completes.

I noticed that your onClick listener does not check to see which View has been selected. I find the easiest way to do this is via switch statements. I have a complete class edited below with all suggestions to save confusion.

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;

public class AsyncTaskActivity extends Activity implements OnClickListener {

    Button btn;
    AsyncTask<?, ?, ?> runningTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = findViewById(R.id.button1);

        // Because we implement OnClickListener, we only
        // have to pass "this" (much easier)
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        // Detect the view that was "clicked"
        switch (view.getId()) {
        case R.id.button1:
            if (runningTask != null)
                runningTask.cancel(true);
            runningTask = new LongOperation();
            runningTask.execute();
            break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Cancel running task(s) to avoid memory leaks
        if (runningTask != null)
            runningTask.cancel(true);
    }

    private final class LongOperation extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // We were cancelled; stop sleeping!
                }
            }
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed"); // txt.setText(result);
            // You might want to change "executed" for the returned string
            // passed into onPostExecute(), but that is up to you
        }
    }
}
Answered By: Anonymous

Related Articles

  • Android adding simple animations while…
  • Android Layout Animations from bottom to top and top…
  • How to implement HorizontalScrollView like Gallery?
  • Auto-fit TextView for Android
  • How to pass values between Fragments
  • ListView inside ScrollView is not scrolling on Android
  • Android + Pair devices via bluetooth programmatically
  • MaterialCardView is in front of NavigationView. How…
  • Android ListView headers
  • Unable to run Robolectric and Espresso with a…
  • How to set dropdown arrow in spinner?
  • Button is null object reference (Android Studio)
  • Adding gif image in an ImageView in android
  • how to show progress bar(circle) in an activity…
  • Android : Fragment doesn't fit into Fragment Container
  • Fragment Not Showing in the Activity
  • Android app unable to start activity componentinfo
  • How to implement a ViewPager with different…
  • Moving from one activity to another Activity in Android
  • Android - How to download a file from a webserver
  • Constraint Layout Vertical Align Center
  • Android "gps requires ACCESS_FINE_LOCATION" error,…
  • Couldn't load memtrack module Logcat Error
  • java.lang.NullPointerException: Attempt to invoke…
  • Getting duplicated cardviews using SwipeRefresh Layout
  • Error inflating class android.support.v7.widget.Toolbar?
  • Failed linking file resources
  • java.lang.IllegalStateException: Can not perform…
  • How to use ScrollView in Android?
  • Play sound on button click android
  • onClick for buttons on custom CardView
  • Playing HTML5 video on fullscreen in android webview
  • How to filter a RecyclerView with a SearchView
  • SecurityException: Permission denied (missing…
  • Google Maps Android API v2 - Interactive InfoWindow…
  • Draw in Canvas by finger, Android
  • Add Items to ListView - Android
  • Item position in RecyclerView only changing when…
  • android.view.InflateException: Binary XML file line…
  • Programmatically Hide/Show Android Soft Keyboard
  • java.lang.RuntimeException: Unable to start activity…
  • How to get the current location latitude and…
  • Remove Text from the edit text when edit text is focused
  • Download a file with Android, and showing the…
  • ViewPager and fragments — what's the right way to…
  • How to store image in SQLite database
  • How to retrieve data from sqlite database in android…
  • How to set timer in android?
  • Android activity life cycle - what are all these…
  • How to get the result of OnPostExecute() to main…
  • Duplicate ID, tag null, or parent id with another…
  • Running multiple AsyncTasks at the same time -- not…
  • For loops print only last value
  • Creating a SearchView that looks like the material…
  • Fragment Inside Fragment
  • Custom Listview Adapter with filter Android
  • How can I handle a click event in Listview?
  • Unable to move from one fragment to another
  • How to receive serial data using android bluetooth
  • Failed to load AppCompat ActionBar with unknown…
  • Integrate ZXing in Android Studio
  • Gridview with two columns and auto resized images
  • android: how to change layout on button click?
  • Same Navigation Drawer in different Activities
  • Handling InterruptedException in Java
  • DatePicker onDateSet method not running
  • Android Studio: Database search functions fine but…
  • How to get current location in Android
  • Vue js vuecli3 application does not work in ie11…
  • image are not showing in image view after selecting…
  • How to download and save an image in Android
  • Percentage width in a RelativeLayout
  • Android App crashes on animated gradient background
  • Android - setOnClickListener vs OnClickListener vs…
  • Android getting value from selected radiobutton
  • Is there an addHeaderView equivalent for RecyclerView?
  • Fragment not showing properly
  • How to create a number picker dialog?
  • How to customize listview using baseadapter
  • OnClickListener in Android Studio
  • How to open a second activity on click of button in…
  • Null pointer Exception on .setOnClickListener
  • Android: How to Programmatically set the size of a Layout
  • Login button need to be clicked twice in order to login
  • Multiple Buttons' OnClickListener() android
  • Error inflating class…
  • How to create a Custom Dialog box in android?
  • android.content.res.Resources$NotFoundException:…
  • Android Studio : java.lang.NullPointerException:…
  • RecyclerView - Get view at particular position
  • Getting wrong position on RecyclerView
  • Text size and different android screen sizes
  • Converting TableLayout to RecyclerView
  • Simple Android grid example using RecyclerView with…
  • Android Room - simple select query - Cannot access…
  • How to Intialize the Binding Properties in the…
  • Setting Custom ActionBar Title from Fragment
  • How to generate JAXB classes from XSD?
  • How to center the content inside a linear layout?
  • GridLayout and Row/Column Span Woe

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to convert comma-separated String to List?

Next Post:

How do I link a JavaScript file to a HTML file?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error