如何从AsyncTask类返回变量

时间:2013-10-28 11:52:26

标签: android android-asynctask fragment

我有一个Fragment类的实现。该类应该返回使用来自远程服务器的数据动态绘制的图表的view。一切正常。但是现在我想要实现一个AsyncTask类来提高app的响应能力。问题是如何将ArrayList返回给调用类。我似乎无法从互联网上找到一个好的例子。 这是我创建并返回视图的方法:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.newfragment, container, false);
    sharename = getArguments().getString(EXTRA_SHARENAME);
    // performance = getPerformance(sharename);
    // new GraphSharePerformance().execute();

    new GraphSharePerformance() {
        @Override
        protected void onPostExecute(ArrayList<SharePerformance> param) {
            super.onPostExecute(param);
            ArrayList<SharePerformance> results = param;
            performance = param;
            // USE THE RESULT here
        }
    }.execute();

    LinearLayout layout = (LinearLayout) v.findViewById(R.id.chart);
    layout.addView(displayLineChart(performance));
    return v;
}

这是我的AsyncTask课程:

protected class GraphSharePerformance extends
            AsyncTask<GraphFragment, Void, ArrayList<SharePerformance>> {
        ArrayList<SharePerformance> shareperformance = new ArrayList<SharePerformance>();

        protected void onPreExecute() {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("loading");
            progressDialog.show();
            super.onPreExecute();
        }

        @Override
        protected ArrayList<SharePerformance> doInBackground(
                GraphFragment... params) {
            shareperformance = getPerformance(sharename);
            return shareperformance;
        }

        protected void onPostExecute(ArrayList<SharePerformance> param) {
            progressDialog.dismiss();

        }

    }

现在我如何获得返回的ArrayList?我已经尝试使用全局变量来保存arraylist但是这不起作用,即使它总是在其他类中工作。图没有绘制任何价值。我会很感激这方面的帮助。谢谢。

5 个答案:

答案 0 :(得分:0)

试试这个

protected class GraphSharePerformance extends
    AsyncTask<GraphFragment, Void, GraphFragment> {
ArrayList<SharePerformance> shareperformance = new ArrayList<SharePerformance>();

protected void onPreExecute() {
    progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMessage("loading");
    progressDialog.show();
    super.onPreExecute();
}

@Override
protected GraphFragment doInBackground(GraphFragment... params) {
    shareperformance = getPerformance(sharename);
    //return your object here. like below.
    //create object
    GraphFragment f=new GraphFragment();
    //some processing...
    //return object 
    return f;
}

protected void onPostExecute(GraphFragment param) {
    progressDialog.dismiss();
}

}

答案 1 :(得分:0)

这是 ONE 方式:

protected class GraphSharePerformance extends
        AsyncTask<GraphFragment, Void, ArrayList<SharePerformance>> {

    protected void onPreExecute() {
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("loading");
        progressDialog.show();
        super.onPreExecute();
    }

    @Override
    protected ArrayList<SharePerformance> doInBackground(GraphFragment... params) {
        return getPerformance(sharename);
    }

    protected void onPostExecute(ArrayList<SharePerformance> param) {
        progressDialog.dismiss();
    }

}

最后,当您使用AsyncTask时:

new GraphSharePerformance() {
   @Override
   protected void onPostExecute(ArrayList<SharePerformance> param) {
      super.onPostExecute(param);
      ArrayList<SharePerformance> results = param;
      //USE THE RESULT here
   }
}.execute();

答案 2 :(得分:0)

使用Application类在整个应用中存储值。然后你可以随处检索它。

示例:

您必须按如下方式声明此类:

<强>清单:

    <application
    android:name="MyApplication"
    android:icon="@drawable/graph"
    android:label="@string/app_name"
    android:theme="@style/Theme.Mytheme" >

.....

 </application>

MyApplication类:

public class MyApplication extends Application{

private ArrayList<SharePerformance> arrayList;

public void setArrayPerf(ArrayList<SharePerformance> ap){
arrayList = ap;
}

public ArrayList<SharePerformance> getArrayPerf(){

 return arrayList;
}
}

在您的Activity类中:

 MyApplication app = (MyApplication) getApplicationContext();

 app.setArrayPref(sharePerformance);

 ArrayList<SharePerformance> arrayList = app.getArrayPerf();

答案 3 :(得分:0)

您可以将返回类型定义为:

public class GraphSharePerformance extends AsyncTask<Void, Void, ArrayList<yourObject>> 

您可以在doInBackground中返回该ArrayList。

在接收方,你需要写:

 ArrayList<yourObject> result = new GraphSharePerformance(args.....).get();

答案 4 :(得分:0)

**
* How to return the ArrayList from a calling class.
**

public class AsyncTaskReturnArrayListActivity extends Activity implements
    OnClickListener {

/** Button. */
private Button button;

/** listArrayList. */
private ArrayList<String> listArrayList;

/**
 * On Create.
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_async_task_return_array_list);

    button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(this);

}

/**
 * On Button On Click, call AsyncTask.
 */
@Override
public void onClick(View v) {
    /**
     * Call Async Task. Pass Calling Class Reference to Async Task. so that
     * once AsyncTask is complete it return result to calling class.
     */

    new SampleAsyncTask(this).execute();
}

/**
 * Async Task.
 */
public class SampleAsyncTask extends
        AsyncTask<Void, Void, ArrayList<String>> {
    private final AsyncTaskReturnArrayListActivity reference;

    /**
     * Constructor. Get the reference of Calling Class.
     *
     * @param reference
     */
    public SampleAsyncTask(AsyncTaskReturnArrayListActivity reference) {
        this.reference = reference;
    }

    /**
     * Pre Execute.
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        System.out.println("Pre Execute");
    }

    /**
     * Do In Background
     */
    @Override
    protected ArrayList<String> doInBackground(Void... params) {
        ArrayList<String> listArrayList = reference.getArrayList();
        return listArrayList;
    }

    /**
     * On Post Execute.
     */
    @Override
    protected void onPostExecute(ArrayList<String> result) {
        super.onPostExecute(result);
        // On Complete send result to Calling Class.
        reference.onComplete(result);
    }
}

/**
 * Get Array List.
 *
 * @return
 */
public ArrayList<String> getArrayList() {
    ArrayList<String> listArrayList = new ArrayList<String>();
    listArrayList.add("String 1");
    listArrayList.add("String 2");
    listArrayList.add("String 3");
    return listArrayList;
}

/**
 * On Complete. Get's Result From Async Task.
 *
 * @param listArrayList
 */
private void onComplete(ArrayList<String> listArrayList) {
    this.listArrayList = listArrayList;
    System.out.println(this.listArrayList);
}}