1

First of all, some info about my project:

I have an application that consists of several fragments. (I have one class that extends FragmentActivity and another one that extends FragmentPagerAdapter.) So actually my code is running inside the Fragments.

I call an asynctask inside one of the fragments to do some calculations. The asyncTask is a seperate file and the class is not located inside the Fragment class.

So 1 file is the asynctask and another one the fragmet (variables from the fragment are not accessible direct by the asynctask!!!).

I can display the result of the asyncTask by using ProgressDialog. However I want to be able to return the data (result of the asynctask) back to a variable that I have in my fragment. What I have tried so far is:

  1. Using get() from asyncatask.execute()

I tried to do it like this:

I used the following code that was called after a button click.

mytask1 = new myAsyncTask(this);
        String result =mytask1.execute(value1).get();

However this results in the main thread to get stuck and wait for the asynctask to complete.

2.Using loginSharePreferens

loginPreferences = getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
            loginPrefsEditor = loginPreferences.edit();
            loginPrefsEditor.putString("result", result);
            loginPrefsEditor.commit();

This gave me errors.

3.I tried also this
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext() );

That was similar with the 2nd method.

4.I tried to create a method in my fragment that would just set the value and I tried to call it inside the fragment

MyFrragment1.this.setRestult(1); // is called in the onPostExecute of the asyncTask

public void setRestult(int result){
        this.test1=result; ///inside of the fragment
    }

This gave me error: "No enclosing instance of the type MyFragment1 is accessible in scope"

I don't know what else to try. Any ideas ?

malcolm the4
  • 347
  • 2
  • 5
  • 15
  • http://stackoverflow.com/questions/16627492/how-to-return-an-object-to-the-fragment-from-a-nested-static-asynctask/ similar question – Raghunandan Jun 05 '13 at 18:53
  • 1
    @Raghunandan I think the link you gave me does the other way around. I want to retrieve the result of the asynctask back to my fragment – malcolm the4 Jun 05 '13 at 19:19
  • 1
    Also, my situation is different, I have NOT the asynctask inside the fragment but seperate – malcolm the4 Jun 05 '13 at 19:30

1 Answers1

9

You can use the onPostExecute method which runs in the UI thread and is called after doInBackground finishes. You can override it in your Fragment like this:

new myAsyncTask() {

        @Override
        protected void onPostExecute( Result result ) {

            super.onPostExecute( result );
            // Do something with result here
        }
    }.execute(value1);
James McCracken
  • 15,488
  • 5
  • 54
  • 62