Friday, 16 October 2020

ASYNC TASK DETAILED VIDEO

VIDEO IS ON YOUTUBE/SAEEDISOFT


JAVA CODE : 


 package islamic.soft.saeedi.com.lessons;


import android.os.AsyncTask;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;


import androidx.annotation.Nullable;

import androidx.appcompat.app.AppCompatActivity;


public class MainAct extends AppCompatActivity

{

    class ServiceRoadTask extends AsyncTask

    {

        @Override

        protected Object doInBackground(Object[] objects)

        {

            serviceRoadWork();

            return null;

        }


        @Override

        protected void onPostExecute(Object o)

        {

            super.onPostExecute(o);

            textView.setText("Task Completed");

        }

    }


    TextView textView;

    TextView tvResult;

    Button btn;


    @Override

    public void onCreate(@Nullable Bundle savedInstanceState)

    {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main_act);

        mainRoadWork();

    }


    int counter = 0;


    private void mainRoadWork()

    {

        textView = findViewById(R.id.tv);

        tvResult = findViewById(R.id.tvResult);

        btn = findViewById(R.id.btn);


        btn.setOnClickListener(view ->

        {

            ++counter;

            tvResult.setText(counter + "");

        });


        serviceRoadWork();


        //new ServiceRoadTask().execute();

    }



    private void serviceRoadWork()

    {

        try

        {

            // Downloading Heavy File

            Thread.sleep(10000);

        }

        catch (InterruptedException e)

        {

            e.printStackTrace();

        }

    }

}









XML CODE : 



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="25sp"></TextView>

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="Click Me"></Button>

    <TextView
        android:id="@+id/tvResult"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="25sp"></TextView>
</LinearLayout>

No comments:

Post a Comment