Reputation: 253
In activity i am using async task to get data from web service and after parsing how to send data from activity to fragment,i have tried using bundle but no luck.If it is directly from activity then bundle works fine Reference but how to pass data from async task from activity to fragment here is my async task
/**
* 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
}
}
Upvotes: 1
Views: 1376
Reputation: 488
Pass your data through bundle :
Bundle bundle = new Bundle();
bundle.putString("CAPTION", caption0);
bundle.putString("QUOTE", quote0);
data.setArguments(bundle);
getFragmentManager().beginTransaction().add(R.id.frameLayout, fragmentName)
.commit();
And In fragment class retrieve data from bundle:
Bundle bundle = getArguments();
String caption0 = bundle.getString("CAPTION");
String quote0 = bundle.getString("QUOTE");
Upvotes: 2