从Asynctask android分配全局变量

时间:2014-07-16 11:13:10

标签: java android android-asynctask

我有一个全局变量: -

public static List<Stuff> myFinalList = new ArrayList<Stuff>();

我正在AsyncTask中执行某些代码,并希望将结果分配给此&#39; myFinalList&#39;。

这是我的代码: -

private class GetList extends AsyncTask<String, String, List<News>> {
    @Override
    protected void onPostExecute(List<Stuff> result) {
        super.onPostExecute(result);
        myFinalList = result;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected List<News> doInBackground(String... params) {
        //some JSON parsing
        myList.add(new Stuff(title, description));
        return myList;
    }
}

main.java

protected void onCreate(Bundle savedInstanceState) {
    try {
        items = new FetchItems().execute(registerContet).get();
        new GetList().execute(items).get();
        if (myFinalList.size() == 0)    {
            new AlertDialog.Builder(Home.this)
                .setTitle("Something went wrong!")
                .setMessage("")
                .setNegativeButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { 
                        // do nothing
                    }
                 })
            .show();
        }
        Map<String, String> idToColorMap = new HashMap<String, String>();
        int colorIndex = 0;
        for (int i = 0; i < myFinalList.size(); i++) {
            //do SOme stuff  
        }
    }
    catch (...) { ... }
}

我尝试从myFinalList分配onPostExecute(),但在我尝试访问onCreate()时返回myFinalList,我的值为null

我该怎么做?

1 个答案:

答案 0 :(得分:0)

如果两个类都在同一个文件中,那么您可以执行以下操作。并且不使用get方法,因为它会阻止UI线程。

protected void onCreate(Bundle savedInstanceState) 
    {
        try 
        {
            items = new FetchItems().execute(registerContet); // i don't know what is this line
            new GetList().execute(items); // this will call the AsyncTask
        }
        catch (Exception e) {}
    }

  private class GetList extends AsyncTask<String, String, List<News>>
   {
    @Override
    protected void onPostExecute(List<Stuff> result) 
    {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        myFinalList = result;
         // here yo can access your list and this method has access to UI
        for (int i = 0; i < myFinalList.size(); i++) {
        //do SOme stuff  
        }
    }

    @Override
    protected void onPreExecute() 
    {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }

    @Override
    protected List<News> doInBackground(String... params)
    {
        // TODO Auto-generated method stub
        //some JSON parsing
      myList.add(new Stuff(title, description));
            }
        }
        catch (JSONException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return myList;
    }