Friday, August 31, 2018

Async Task example Counter

package net.samaysoftware.listviewdemo;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class DemoThreading extends AppCompatActivity {

    TextView tvCounter;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo_threading);
        tvCounter = (TextView) findViewById(R.id.tvCounter);

        // call asynctask
        MyTask t = new MyTask();
        t.execute(10);


    }
    class MyTask extends AsyncTask<Integer, Integer, String>{

        @Override        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override        protected String doInBackground(Integer... arr) {
            int value = arr[0];
            for(int i =0; i<value;i++){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                publishProgress(i+1);
            }
            return "Done";
        }



        @Override        protected void onPostExecute(String s) {
            super.onPostExecute(s);


        }

        @Override        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            int v = values[0];
            tvCounter.setText(v+"");
        }
    }
}

No comments:

Post a Comment

Near by App

https://drive.google.com/file/d/0B2ag35s4X53Eb2pSQVI1SzNudE0/view