Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use AsyncTask in android?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 312
    Comment on it

    In the below example I have clearly described how to use  AsyncTask.

    First of all you should know what is AsyncTask ?  
    AsyncTask is an abstract class provided by android which helps us to use the UI thread properly. AsyncTask class allows us to perform backgraund operations and show its result on the UI thread without having to manipulate thread.  


     In below example I have created process to waiting for some period of time instead of doing network operation. Here I have added in activity_main.xml layout a TextView, EditText and button. And In MainActivity I have created AsyncTaskRunner private class and extend with AsyncTask class. You can see below program it clearly describe you How to use AsyncTask in android.

     

    Step(1)-activity_main.xml-

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity" >
    
        <TextView
            android:id="@+id/tv_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10pt"
            android:textColor="#444444"
            android:layout_alignParentLeft="true"
            android:layout_marginRight="9dip"
            android:layout_marginTop="20dip"
            android:layout_marginLeft="10dip"
            android:text="Waiting time:"/>
        <EditText
            android:id="@+id/et_time"
            android:layout_width="150dip"
            android:layout_height="wrap_content"
            android:background="@android:drawable/editbox_background"
            android:layout_toRightOf="@id/tv_time"
            android:layout_alignTop="@id/tv_time"
            android:maxLength="2"
            android:inputType="text|number"
            />
        <Button
            android:id="@+id/btn_do_it"
            android:layout_width="200dip"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="15dip"
            android:layout_marginLeft="260dip"
            android:layout_below="@id/et_time"
            android:text="Run Async task" />
        <TextView
            android:id="@+id/tv_result"
            android:layout_width="400dip"
            android:layout_height="100dip"
            android:textSize="7pt"
            android:layout_alignParentLeft="true"
            android:layout_below="@id/btn_do_it"
            android:layout_marginRight="9dip"
            android:layout_marginTop="15dip"
            android:layout_marginLeft="260dip"
            android:textColor="#AA0000"
            android:text=""/>
    </RelativeLayout>

     

    Step(2)-MainActivity-

    public class MainActivity extends Activity {
        private Button button;
        private EditText time;
        private TextView finalResult;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            time = (EditText) findViewById(R.id.et_time);
            button = (Button) findViewById(R.id.btn_do_it);
            finalResult = (TextView) findViewById(R.id.tv_result);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AsyncTaskRunner runner = new AsyncTaskRunner();
                    String sleepTime = time.getText().toString();
                    runner.execute(sleepTime);
                }
            });
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }
        private class AsyncTaskRunner extends AsyncTask<String, String, String> {
    
            private String resp;
    
            @Override
            protected String doInBackground(String... params) {
                publishProgress("Waiting..."); // Calls onProgressUpdate()
                try {
                    // Do your long operations here and return the result
                    int time = Integer.parseInt(params[0]);
                    // waiting for given time period
                    Thread.sleep(time);
                    resp = "Wait for " + time + " milliseconds";
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    resp = e.getMessage();
                } catch (Exception e) {
                    e.printStackTrace();
                    resp = e.getMessage();
                }
                return resp;
            }
    
            @Override
            protected void onPostExecute(String result) {
                finalResult.setText(result);
            }
    
            @Override
            protected void onPreExecute() {
    
            }
    
    
            @Override
            protected void onProgressUpdate(String... text) {
                finalResult.setText(text[0]);
    
            }
        }
    }

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: