如何将数据从异步任务的活动传递到片段

时间:2015-04-04 11:04:29

标签: android android-fragments android-asynctask

在活动中我使用异步任务从Web服务获取数据,在解析了如何将数据从活动发送到片段后,我尝试使用bundle但没有运气。如果它直接来自activity,那么bundle工作正常{{3 }} 但是如何将数据从异步任务从活动传递到片段 这是我的异步任务

/**
 * Async task class to get json by making HTTP call
 * */
private class GetQuotes extends AsyncTask<Void, Void, Void> {

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

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
        System.out.println(jsonStr);
        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {

                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                pages = jsonObj.optJSONArray(TAG_PAGES);

                System.out.println(pages);
                JSONObject c = pages.getJSONObject(0);
                caption0 = c.getString(TAG_CAPTION);     
                quote0 = c.getString(TAG_QUOTE);
                System.out.println("obj1" + caption0 + quote0);

                JSONObject c1 = pages.getJSONObject(1);
                caption1 = c1.getString(TAG_CAPTION);
                quote1 = c1.getString(TAG_QUOTE);
                System.out.println("obj2" + caption1 + quote1);

                JSONObject c2 = pages.getJSONObject(0);
                caption2 = c2.getString(TAG_CAPTION);
                quote2 = c2.getString(TAG_QUOTE);
                System.out.println("obj3" + caption2 + quote2);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog

    }

}

1 个答案:

答案 0 :(得分:2)

通过捆绑包传递您的数据 :

Bundle bundle = new Bundle();
bundle.putString("CAPTION", caption0);
bundle.putString("QUOTE", quote0);
data.setArguments(bundle);
getFragmentManager().beginTransaction().add(R.id.frameLayout, fragmentName)
                    .commit();

在片段类中从bundle中检索数据:

Bundle bundle = getArguments();
String caption0 = bundle.getString("CAPTION");
String quote0 = bundle.getString("QUOTE");
相关问题