2

I have one class that extends Asynctask. In this class I have a method that returns a hash map. How can I get this Hashmap in different class that extends Activity.

Anyone give me some reference code?

Mahesh
  • 66
  • 4
Hardik
  • 1,429
  • 2
  • 19
  • 37

1 Answers1

4

You can create a listener in your Activity, then pass this listener into your AsyncTask. Once the AsyncTask completes you can call the listener to set the Hashmap. So in your AsyncTask create your listener:

    public static interface MyListener {
        void setHashmap(Hashmap myHashmap);
    }

Also, have a function to set your listener:

    public void setListener(MyListener listener) {
        this.listener = listener;
    }

Then in onPostExecute call the function on your listener

    listener.setHashmap(myHashmap);

In your activity implement this listener:

    public class MyActivity extends Activity implements MyListener { ...


    public void setHashmap(Hashmap hashmap) {

        // do stuff here
        this.hash = hashmap
    }

Then finally set your listener and start your AsyncTask:

    AsyncTask task = new MyAsyncTask();
    task.setListener(this);
    task.execute();

Of course you could also just put your AsyncTask in your Activity then you can set the hashmap in onPostExecute.

Nick
  • 6,375
  • 5
  • 36
  • 53