0

I am trying AsyncTask. I cannot understand how to return the result.I am also confused on doInBackground() has return type Void . Why does it need return null; if I return null how will I get value from this method.

package com.example.shikkok_services;

import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MyTask extends AsyncTask<Void, Integer, Void> {

    //progressBar holo UI te kaj kore tai Context dorkar tai MyTask e construtor decler korlam.Inner class hole eita dorkar silo na

    Context context;
    Handler handler;
    Dialog dialog;
    TextView txtprogrss;
    ProgressBar progress;
    Button btnCancel;

    MyTask(Context context, Handler handler){
        this.context=context;
        this.handler=handler;

    }

    MyTask(Context context){
      this.context=context;
      this.handler=handler;
    }

    //--------------------------------onPreExecute()............................................
    @Override
    protected void onPreExecute() {

        super.onPreExecute();
        // create dialog

        dialog=new Dialog(context);
        dialog.setCancelable(true);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.pogressdialog);
        dialog.show();

        txtprogrss=(TextView) dialog.findViewById(R.id.txtProgress);
        progress=(ProgressBar)dialog.findViewById(R.id.progressBar2);
        btnCancel=(Button)dialog.findViewById(R.id.btnProgress);
        //progress=new ProgressBar(context);

        btnCancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                MyTask.this.cancel(true);
                dialog.dismiss();
            }
        });
        dialog.show();

    }

    //--------------------------------doInBackground()...........................

    @Override
    protected Void doInBackground(Void... arg0) {
     //Kaj hobe backgournd e not UI e
        // do tasks and update msg
        for (int i = 0; i < 10; i++) {
            if(isCancelled()){
            break;
            }else{
            Log.e("In Background","current value;"+ i);
            publishProgress(i);
            //joto bar publishProgress() call hobe toto bar OnProgressUpdate hobe..
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            }

        }

        return null;    
    }

    //------------------------------onProgressUpdate().....................................

    @Override
    protected void onProgressUpdate(Integer... values) {
        //dowonload hole koto percent hosse seita dhore dhore UI te dekhalte parbo

        super.onProgressUpdate(values);
        // update dialog progress

        progress.setProgress(values[0]);
        txtprogrss.setText("progress update"+ values[0]+"%");

    }

    //-----------------------------OonPostExecute()...........................................
    @Override
    protected void onPostExecute(Void result) {
        // jokhon kaj ses hoe jabe tokhon ei method e asben then UI te chole asben
        super.onPostExecute(result);

        // handler.sent message

        dialog.dismiss();
        Toast.makeText(context, "Finished", Toast.LENGTH_LONG).show();

    }





}
codeMagic
  • 44,549
  • 13
  • 77
  • 93
AndyError
  • 561
  • 1
  • 6
  • 10

3 Answers3

4

I am also confuse doInBackground is return type Void .Why it is need return null; if I return null how get value from this method.please tell me.

This is because that is what you have made it. You can return a type you just have to change the class definition ex.

public class MyTask extends AsyncTask<Void, Integer, String> {  // changed last param

With this, doInBackground() will be expected to return a String type to onPostExecute(). Which means you would also have to change that method to

 @Override
protected void onPostExecute(String result) {

You would then obviously change your return statement in doInBackground() to return someString.

I used String as an example but you could change that.

As far as returning value after AsyncTask finishes

See this answer about using an interface. It is really easy to implement and will update your Activity when the task finishes.

Also please read (or re-read) the AsyncTask docs

Community
  • 1
  • 1
codeMagic
  • 44,549
  • 13
  • 77
  • 93
  • thanks @codeMagic bro.If it is onPostExecute(Void result) then doInBacground is need return null? bro i can not understand Android Developer site.What I do please tell me – AndyError Apr 10 '14 at 13:44
  • You can change the param type as I have showed in my answer. It doesn't have to be `Void result`. It can be `int myCrazyVariableName` – codeMagic Apr 10 '14 at 13:45
  • The docs can be confusing but you need to understand the rules of `AsyncTask` and your life will be much easier. When I started with it, I read through them several times and more times since. – codeMagic Apr 10 '14 at 13:46
  • bro i am beginner of android.I am only know java (class , object, Inheritance, abstract, Exception handling, something thread and Generic collection. it will be enough for android? java all think is need?? – AndyError Apr 10 '14 at 13:53
  • If you know Java well then it is a good start. But you still need to understand the Android framework. Read through the docs, find tutorials (vogella.com is usually good) and look through Google's youtube channel (a lot of good videos). But I have shown you how you need to change your `AsyncTask` to `return` the values you want. – codeMagic Apr 10 '14 at 13:55
  • You're welcome. Nah, I'm on here waaaay more than Facebook anyway. – codeMagic Apr 10 '14 at 14:05
  • how contact you bro please tell me?I am serious interested Android apps.I want advise you bro!! – AndyError Apr 10 '14 at 14:11
  • You may contact me by posting a question on SO and if I see it I will try to answer. If I don't, there are many other capable developers here that will be glad to help you. – codeMagic Apr 10 '14 at 14:13
  • 1
    @user3515725 He is not only to help you, there are others also, there is no meaning to share facebook id here, if you have any query in future then ask question on stackoverflow that is how this works – Ajay S Apr 10 '14 at 14:13
1

AsyncTask must return null because you said so declaring this: AsyncTask<Void, Integer, Void>. The third parameter determines what doInBackground() returns and therefore what onPostExecute() gets.

Change this datatype to make it return whetever you want, this way you'll receive it as a parameter in the onPostExecute() method and you can even update Views in the main UI Thread from within this method (you can even update them from anywhere besides doInBackground()).

nKn
  • 13,691
  • 9
  • 45
  • 62
  • This is a bit misleading and wrong, "you can even update Views in the main UI Thread from within this method (but only from here!)". `View`s can be updated from **any** method of `AsyncTask` besides `doInBackground()`. – codeMagic Apr 10 '14 at 13:48
  • @codeMagic You're right! That's something I forgot, updated. Thanks! – nKn Apr 10 '14 at 14:32
-2

For getting value from asynchronous task call it like this:

String result= new MyTask ().execute().get();


class MyTask extends AsyncTask<String, String, String>
        {
        protected String doInBackground(String... params)


                  return somevalue; 
                      }

                }
Trupti
  • 284
  • 5
  • 7
  • 1
    -1, this will **block** the main UI (because of the `.get()`). – nKn Apr 10 '14 at 13:40
  • But i am using this one and its working fine , then give some other solution @ nKn – Trupti Apr 10 '14 at 13:42
  • Trupti, it may be working for your current needs but it is generally bad practice since it *does* block the UI, as nKn has said. It defeats the purpose of using the class. Also, nKn did give some other solution ;) – codeMagic Apr 10 '14 at 13:51