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 ?

4

1 回答 1

8

您可以使用onPostExecute在 UI 线程中运行并在doInBackground完成后调用的方法。您可以Fragment像这样覆盖它:

new myAsyncTask() {

        @Override
        protected void onPostExecute( Result result ) {

            super.onPostExecute( result );
            // Do something with result here
        }
    }.execute(value1);
于 2013-06-05T19:49:16.057 回答