在片段中执行异步任务

时间:2014-02-08 18:28:45

标签: android asynchronous android-fragments android-asynctask

我尝试在将活动转换为片段后在片段中执行异步任务。当我从活动中调用异步任务时,我必须使用它传递'this',以便允许异步任务在收到信息后更改文本和内容。关于如何用碎片做这一切,我有点困惑。这是我到目前为止所得到的:

我用:

执行asynck任务
new GetYourTopTasteBeers(this).execute(url);

异步任务的代码是:

public class GetYourTopTasteBeers extends AsyncTask<String, Void, String> {

    Context c;
    private ProgressDialog Dialog;

    public GetYourTopTasteBeers (Context context)
    {
        c = context;
        Dialog = new ProgressDialog(c);
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        return readJSONFeed(arg0[0]);
    }

    protected void onPreExecute() {
        Dialog.setMessage("Getting beers");

        Dialog.setTitle("Loading");
        Dialog.setCancelable(false);
        Dialog.show();
    }

    protected void onPostExecute(String result){
        //decode json here
        try{
            JSONArray jsonArray = new JSONArray(result);


            //acces listview
            ListView lv = (ListView) ((Activity) c).findViewById(R.id.topTasteBeers);

            //make array list for beer
            final List<ShortBeerInfo> tasteList = new ArrayList<ShortBeerInfo>();



            for(int i = 0; i < jsonArray.length(); i++) {

                String beer = jsonArray.getJSONObject(i).getString("beer");
                String rate = jsonArray.getJSONObject(i).getString("rate");
                String beerID = jsonArray.getJSONObject(i).getString("id");
                String breweryID = jsonArray.getJSONObject(i).getString("breweryID");


                int count = i + 1;

                beer = count + ". " + beer;


                //create object
                ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID , breweryID);

                //add to arraylist
                tasteList.add(tempTaste);


                //add items to listview
                ShortBeerInfoAdapter adapter1 = new ShortBeerInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
                lv.setAdapter(adapter1);

                //set up clicks
                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int arg2, long arg3) {
                        ShortBeerInfo o=(ShortBeerInfo)arg0.getItemAtPosition(arg2);

                        String tempID = o.id;
                        String tempBrewID = o.brewery;

                        Toast toast = Toast.makeText(c, tempID, Toast.LENGTH_SHORT);
                        toast.show();

                        //todo: change fragment to beer page

                        Intent myIntent = new Intent(c, BeerPage2.class);
                        myIntent.putExtra("id", tempID);
                        myIntent.putExtra("breweryID", tempBrewID);
                        c.startActivity(myIntent);


                    }
                });




            }

        }
        catch(Exception e){

        }

        Dialog.dismiss();

    }

    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {
                Log.d("JSON", "Failed to download file");
            }
        } catch (Exception e) {
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }
        return stringBuilder.toString();
    }

}

我的问题是我不能从片段中传递'this'...

奖金问题:

另外,你可以看到我没有完成转换我的代码片段。我需要更改它以加载片段而不是更改活动:

//todo: change fragment to beer page
                        Intent myIntent = new Intent(c, BeerPage2.class);
                        myIntent.putExtra("id", tempID);
                        myIntent.putExtra("breweryID", tempBrewID);
                        c.startActivity(myIntent);

我可以在片段之间传递值,就像我在上面代码中的活动之间所做的那样吗?

2 个答案:

答案 0 :(得分:2)

由于Fragment不承认this,您可以拨打getActivity(),而不是提供执行AsyncTask所需的上下文。

但要小心,因为在AsyncTask内投放Fragment可能会导致结果返回到您{{1}时已被销毁的来电者Activity结束了它的过程。有必要采取额外的预防措施,并始终检查AsyncTask是否尚未被销毁。这可以使用Fragment中的this.isAdded()来完成。

一个好的做法是取消FragmentAsyncTask方法中的onStop()。如果onPause()不再处于活动状态(getActivity()将返回null),这将使onPostExecute()不执行代码。

答案 1 :(得分:1)

您无法通过this,因为在这种情况下this引用您的片段,但不会延伸Context。但您需要Context(您的GetYourTopTasteBeersContext作为参数):

public GetYourTopTasteBeers (Context context)

相反,传递你的Activity,如此:

new GetYourTopTasteBeers(getActivity()).execute(url);