How to use AsyncTask - java

AsyncTask question
I've followed some tutorials but it still isn't clear to me. Here's the code I currently have with some questions below the code. MainActivity calls SomeClassWithHTTPNeeds, which then calls the JSONParser (AsyncTask<>)
MainActivity:
String station = SomeClassWithHTTPNeeds.getInstance().getStation(123);
SomeClassWithHTTPNeeds:
getStation {
JSONParser = new JSONParser();
JSONObject station = parser.getJSONFromUrl("https://api....");
return JSONObject.getString("station");
}
JSONParser (AsyncTask< String, Void, String >)
protected String doInBackground(); ==> Seperate thread
protected void onPostExecute(); ==> On GUI thread
I was thinking:
--- Put the HTTPRequest in doInBackground();
Problem is I'm not sure how to:
get the JSONParser to return the JSONObject to the getStation method?
What I need to know
=> Where should I return the JSONObject: in background or execute?
=> How do I use the JSONParser once it's an AsyncTask? Will the execute() function return the value?
=> AsyncTask< String, Void, String > ==> How does this work? It's the return type?
Thanks a lot!

FAQs and general explaination of the usage of AsyncTask
=> Where should I do network operations? Where should I return my aquired values?
In general, you should do Network Operations in a Seperate Thread -> doInBackground(); since you do not want your UI to freeze when a Network Operation takes its time. So you should connect to your Service or .php script or wherever you get the Data from inside the doInBackground() method. Then you could also parse the data there and return the parsed data from the doInBackground() method by specifying the return type of doInBackground() to your desires, more about that down there. The onPostExecute() method will then receive your returned values from doInBackground() and represent them using the UI.
=> AsyncTask< String, Integer, Long> ==> How does this work?
In general, the AsyncTask class looks like this, which is nothing more than a generic class with 3 different generic types:
AsyncTask<Params, Progress, Result>
You can specify the type of Parameter the AsyncTask takes, the Type of the Progress indicator and the type of the result (the return type
of doInBackGround()).
Here is an Example of an AsyncTask looking like this:
AsyncTask<String, Integer, Long>
We have type String for the Parameters, Type Integer for the Progress and Type Long for the Result (return type of doInBackground()). You can use any type you want for Params, Progress and Result.
private class DownloadFilesTask extends AsyncTask<String, Integer, Long> {
// these Strings / or String are / is the parameters of the task, that can be handed over via the excecute(params) method of AsyncTask
protected Long doInBackground(String... params) {
String param1 = params[0];
String param2 = params[1];
// and so on...
// do something with the parameters...
// be careful, this can easily result in a ArrayIndexOutOfBounds exception
// if you try to access more parameters than you handed over
long someLong;
int someInt;
// do something here with params
// the params could for example contain an url and you could download stuff using this url here
// the Integer variable is used for progress
publishProgress(someInt);
// once the data is downloaded (for example JSON data)
// parse the data and return it to the onPostExecute() method
// in this example the return data is simply a long value
// this could also be a list of your custom-objects, ...
return someLong;
}
// this is called whenever you call puhlishProgress(Integer), for example when updating a progressbar when downloading stuff
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
// the onPostexecute method receives the return type of doInBackGround()
protected void onPostExecute(Long result) {
// do something with the result, for example display the received Data in a ListView
// in this case, "result" would contain the "someLong" variable returned by doInBackground();
}
}
=> How to use AsyncTask? How can I "call" it? How can I "execute" it?
In this case, the AsyncTask takes a String or String Array as a Parameter which will look like this once the AsyncTask is called: (The specified parameter is used in the execute(param) method of AsyncTask).
new DownloadFilesTask().execute("Somestring"); // some String as param
Be aware, that this call does not have a return value, the only return value you should use is the one returned from doInBackground(). Use the onPostExecute() method do make use of the returned value.
Also be careful with this line of code: (this execution will actually have a return value)
long myLong = new DownloadFilesTask().execute("somestring").get();
The .get() call causes the UI thread to be blocked (so the UI freezes if the operation takes longer than a few millisecons) while the AsyncTask is executing, because the execution does not take place in a separate thread. If you remove the call to .get() it will perform asynchronously.
=> What does this notation "execute(String... params)" mean?
This is a method with a so called "varargs" (variable arguments) parameter. To keep it simple, I will just say that it means that the actual number of values you can pass on to the method via this parameter is not specified, and any amount of values you hand to the method will be treated as an array inside the method. So this call could for example look like this:
execute("param1");
but it could however also look like this:
execute("param1", "param2");
or even more parameters. Assuming we are still talking about AsyncTask, the parameters can be accessed in this way in the doInBackground(String... params) method:
protected Long doInBackground(String... params) {
String str1 = params[0];
String str2 = params[1]; // be careful here, you can easily get an ArrayOutOfBoundsException
// do other stuff
}
You can read more about AsyncTask here: http://developer.android.com/reference/android/os/AsyncTask.html
Also take a look at this AsyncTask example: https://stackoverflow.com/a/9671602/1590502

package com.example.jsontest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.util.Log;
public class HttpClient {
private static final String TAG = "HttpClient";
public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
StringEntity se;
se = new StringEntity(jsonObjSend.toString());
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
httpPostRequest.setHeader("Accept-Encoding", "gzip");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
String resultString= convertStreamToString(instream);
instream.close();
resultString = resultString.substring(0,resultString.length()-1);
JSONObject jsonObjRecv = new JSONObject(resultString);
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
return jsonObjRecv;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Log.e("JSON", ""+line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Asynctask:
public class callCarWeb extends AsyncTask {
#Override
protected void onPreExecute() {
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Please wait...");
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setIndeterminate(true);
mDialog.setCancelable(false);
mDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
JSONObject jsonObjSend = new JSONObject();
jsonObjSend.put("username", username);
jsonObjSend.put("password", passwd);
Log.e("SEND", jsonObjSend.toString());
JSONObject json = HttpClient.SendHttpPost("http://10.0.2.2/json/login.php", jsonObjSend);
String status = json.getString("status");
if(status.equalsIgnoreCase("pass")){
String id = json.getString("user_id");
Log.e("id", id);
String name = json.getString("name");
Log.e("name", name);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
mDialog.cancel();
}
}
## Heading ##

I think you can execute your HTTPRequest in your doInBackground of the Async task. And JSONParser at onPostExecute.

do read some generics.
now, when you write your async task JSONParser here params is of type String, progress is of type Void and result is of type String. Read this.
generally people overrides two methods doInBackground() and onPostExecute(), the first one takes params and returns a result and second one takes that result. These are protected methods you can't call em directly. Then you might ask how to send param to doInBackground(), look at execute() API.
doInBackground() runs on background thread, its not a blocking call!!
don't do this,
JSONParser = new JSONParser();
JSONObject station = parser.getJSONFromUrl("https://api....");
return JSONObject.getString("station");
instead write on interface in JSONParser or somewhere else like,
public interface OnParseCompleteListener {
void onParseComplete(JSONObject obj);
}
now your JSONParser class will something like,
public class JSONParser extends AsyncTask<String, Void, String> {
private OnParseCompleteListener mOnParseCompleteListener;
public void setOnParseCompleteListener(OnParseCompleteListener listener) {
mOnParseCompleteListener = listener;
}
protected String doInBackground(String... params) {
/*
* do http request and return a result
*/
}
protected void onPostExecute(String... result) {
/*
* parse the resulting json string or you can parse same string in
* doInBackground and can send JSONObject as a result directly.
* at this stage say you have a JSONObject obj, follow
*/
if (mOnParseCompleteListener != null) {
mOnParseCompleteListener.onParseComplete(obj);
}
}
}
when you create an object of JSONParser set OnParseCompleteListener.
JSONParser parser = new JSONParser();
parser.setOnParseCompleteListener(listener);
parse.execute("may be an url");
now you decide from where to pass or create your own listener.

Related

Android exit AsyncTask issue

I want to ask if this that looks like an issue to me is problem.
I have a class of AsyncTask to get data from a json file and a doInBackground method with pre-execute and post-execute methods.
At onCreate method of my MainActivity I call the class of AsyncTask with name.execute(). The problem is that the program stuck into the post execute method, is that a problem? There is a way to return to the OnCreate method or should I continue with my code from post execute method?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new LoadAllProducts().execute();
txtView=(TextView) findViewById(R.id.txtV);
}
class LoadAllProducts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading questions. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All questions: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
questions = json.getJSONArray(TAG_QUESTIONS);
// looping through All Products
for (int i = 0; i < questions.length(); i++) {
JSONObject c = questions.getJSONObject(i);
// Storing each json item in variable
int id = c.getInt(TAG_QID);
String questionPron = c.getString(TAG_QUESTION);
String answer1 = c.getString(TAG_ANSWER_1);
String answer2 = c.getString(TAG_ANSWER_2);
String answer3 = c.getString(TAG_ANSWER_3);
String answer4 = c.getString(TAG_ANSWER_4);
int level = c.getInt(TAG_LEVEL);
int correctIs = c.getInt(TAG_CORRECT_IS);
// String updatedAt = c.getString(TAG_UPDATED_AT);
dokimi = questionPron;
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
//ArrayList<eachQuestion> qArray = new ArrayList<eachQuestion>();
eachQuestion ea = new eachQuestion();
ea.setId(id);
ea.setQuestionPron(questionPron);
ea.setAnswer1(answer1);
ea.setAnswer2(answer2);
ea.setAnswer3(answer3);
ea.setAnswer4(answer4);
ea.setLevel(level);
ea.setCorrectIs(correctIs);
// adding each child node to HashMap key => value
//map.put(TAG_PID, id);
//map.put(TAG_NAME, name);
qArray.add(ea);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
}
});
}
}
"The problem is that the program stuck into the post execute method, is that a problem?" I can only guess what that was supposed to mean but I will try to answer your question. The reason why AsyncTask even exists is that its code is run on a separate thread (cpu). The main thread (cpu) is making another cpu execute given code.
That is why method call of execute() returns almost immediately, most probably even before any line of given code for another cpu executes. You are not able to predict when exactly (if ever) this code will execute. This depends on your OS's scheduler and current runtime session, in computer science we describe such behaviour as undeterministic.

json array value from volley into hashmap string, string

i have a request to build slider image from jsonArray using volley, i don't know how to put value of jsonArray to hashmap<string, string> .. it keep saying null object
error message
Attempt to invoke virtual method 'java.lang.Object
java.util.HashMap.put(java.lang.Object, java.lang.Object)' on a null object reference
JSON array value
[
{"cPID":"62001002280293829",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/rsch.jpg"},
{"cPID":"62001002020254584",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/penang.jpg"},
{"cPID":"62001002050264258",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/guardian.jpg"}
]
and then i wanna put that value like this into hashmap<string, string> inside onCreate()
HashMap<String,String> url_maps = new HashMap<>();
url_maps.put("Hannibal", "http://static2.hypable.com/wp-content/uploads/2013/12/hannibal-season-2-release-date.jpg");
url_maps.put("Big Bang Theory", "http://tvfiles.alphacoders.com/100/hdclearart-10.png");
url_maps.put("House of Cards", "http://cdn3.nflximg.net/images/3093/2043093.jpg");
url_maps.put("Game of Thrones", "http://images.boomsbeat.com/data/images/full/19640/game-of-thrones-season-4-jpg.jpg");
it gonna use for adding picture to my slider(slideshow) inside onCreate()
for(String name : url_maps.keySet()){
DefaultSliderView DefaultSliderView = new DefaultSliderView(getContext());
// initialize a SliderLayout
DefaultSliderView
.image(url_maps.get(name))
.setScaleType(BaseSliderView.ScaleType.Fit)
.setOnSliderClickListener(this);
//add your extra information
DefaultSliderView.bundle(new Bundle());
DefaultSliderView.getBundle()
.putString("extra",name);
mDemoSlider.addSlider(DefaultSliderView);
}
and i don't know how to put values from volley JsonArray, and this is my request but error saying null.
private void getSlider(){
String tag_string_req = "sliderList";
// Showing progress dialog before making http request
JsonArrayRequest mostReq = new JsonArrayRequest(AppConfig.URL_Slider, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < 5; i++) {
JSONObject jObj = response.getJSONObject(i);
url_maps.put(jObj.getString("cPID"), jObj.getString("image"));
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + "Error Data Occured!!" + error.getMessage());
Toast.makeText(getContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) ;
AppController.getInstance().addToRequestQueue(mostReq, tag_string_req);
}
the values request was accepted on volley, it show on Logcat .. but null on hashmap .. tell me if i got mistake in my code, sorry just newbie and still study
You are iterating thru just the keys... You need to iterate through the keys and values...
for (url_maps.Entry<String, String> url_map : url_maps.entrySet()) {
String key = url_map.getKey();
String value = url_map.getValue();
// ...
}
ANOTHER WAY TO ATTEMPT THIS IS...
to deserialize your Json into a java object...
ObjectMapper mapper = new ObjectMapper();
string StringJson = "[
{"cPID":"62001002280293829",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/rsch.jpg"},
{"cPID":"62001002020254584",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/penang.jpg"},
{"cPID":"62001002050264258",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/guardian.jpg"}
]";
// For the following line to work you will need to make a URLMaps Class to hold the objects
URLMaps urlMaps = mapper.readValue(StringJson , URLMaps.class);
The URLMaps Class might look like this.
public class URLMaps{
public string name = "";
public string image = "";
//constructor
public URLMaps(string a, string b) {
name = a;
image = b;
}
public string getName() {
return name;
}
public string getImage() {
return image;
}
}
Then to utilize the class you can go with:
urlMaps.getName(), or urlMaps.getValue() in your DefaultSliderView.image()
Also to note, since this is a class you can store an array of them or a list of them, so you can re-purpose your for loop...
For (URLMap urlmap : UrlMaps[]) // where URLMaps is your object that holds multiple instances of URLMaps.
Lastly, it has been a long time since I have coded in Java, so this code is untested, but should help you come to a solution.

How does one correctly override AsyncTask onPostExecute() method? [duplicate]

This question already has answers here:
What does "String... params" mean if passed as a parameter? [duplicate]
(3 answers)
Closed 7 years ago.
I am using AsyncTask to make an API call. My AsyncTask is supposed to send two images to a facial recognition service and return a Double contained in the JSON response from the service.
However, I keep getting this error regarding onPostExecute():
Error:(44, 5) error: method does not override or implement a method from >a supertype
I don't understand why I get this error.
Here is my AsyncTask subclass:
public class KairosManager extends AsyncTask<Bitmap, Void, JSONObject> {
// MainActivity Context
private Context mContext;
public KairosManager(Context context){
mContext = context;
}
// Call Kairos API and return JSONObject response to doInBackground()
public JSONObject compareImages(Bitmap bm1, Bitmap bm2){
// Kairos Call here!
return jsonResponse;
}
// Take both images in the array and call compareImages which calls the service.
#Override
protected JSONObject doInBackground(Bitmap... params){
Bitmap bm1 = params[0];
Bitmap bm2 = params[1];
return compareImages(bm1, bm2);
}
// Parse JSONObject response and return 'confidence' value to MainActivity
#Override
protected Double onPostExecute(JSONObject result){
try{
JSONArray TwoImages = result.getJSONArray(IMAGES);
JSONObject image = TwoImages.getJSONObject(0);
JSONObject subimage = image.getJSONObject(TRANSACTION);
Double confidence = subimage.getDouble(CONFIDENCE);
Log.d("Percent: ", confidence.toString());
return confidence;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here is my MainActivity:
Bitmap bm1 = ((BitmapDrawable) image1.getDrawable()).getBitmap();
Bitmap bm2 = ((BitmapDrawable) image2.getDrawable()).getBitmap();
KairosManager myKairosManager = new KairosManager(this);
myKairosManager.execute(bm1, bm2);
Your doInBackground method should return an object of type Double.

Return Value In Runnable

I have a custom adapter that buttons and TextView, the TextView is changed on a button click within listview and it after sending and receiving feedback from http Post via Json response, I tried using runnable and assynctask but no success. In the runnable, I can not return a value from the method.
What I wanted is to send http request to the server and return json results, based on the returned results, the TextView will change.
What is the best approach to use to achieve this.
If any one can help point me to a resource that will help me to achieve this will be highly welcome.
Thanks in advance!
Here is my code..
public String getStatus(final String id, final String user){
final String[] resp = {"0/0/0"};
new Thread(new Runnable() {
#Override
public void run() {
// Building Parameters
final List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", user));
params.add(new BasicNameValuePair("id", id));
Log.d("Nay Params", "" + params);
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(NAY_URL, "POST",
params);
// check your log for json response
// json success tag
try {
Log.d("Nay Response", ""+ json);
success = json.getBoolean(TAG_SUCCESS);
yeaSt = json.getBoolean(TAG_E_STATUS);
naySt = json.getBoolean(TAG_A_STATUS);
yeaC = json.getInt(TAG_YEA);
nayC = json.getInt(TAG_NAY);
if (success){
resp[0] = yeaS + "/" + naySt + "/" + yeaC + "/" + nayC;
return resp[0];
//Can not return return value within void method that is; Class void run()
}
} catch (JSONException e) {
e.printStackTrace();
//return resp[0];
}
}
}).start();
//Can not acces json result outside the try catch block
Log.d("sux", ""+success);
// Log.d("Rest1", resp[0]);
return resp[0];
}
You could use Callable interface in order to run a thread and get the thread's result.
Here's the Callable documentation.
And Jakob explains how to use it here.
Hope that helped, if you need a concrete example I recently used this approach in my project, and I'll be happy to provide you with a sample.
Edit:
Here is a simple example of using callable, I changed a little bit my code so it is more clear:
public class Test {
ExecutorService executor;
public Test() {
/* I used an executor that creates a new thread every time creating a server requests object
* you might need to create a thread pool instead, depending on your application
* */
executor = Executors.newSingleThreadExecutor();
}
private JSONObject doTheWork() {
// init
Callable<JSONObject> callable;
Future<JSONObject> future;
JSONObject jsonResult = null;
try {
// create callable object with desired job
callable = new Callable<JSONObject>() {
#Override
public JSONObject call() throws Exception {
JSONObject jsonResult = new JSONObject();
// connect to the server
// insert desired data into json object
// and return the json object
return jsonResult;
}
};
future = executor.submit(callable);
jsonResult = future.get();
} catch(InterruptedException ex) {
// Log exception at first so you could know if something went wrong and needs to be fixed
} catch(ExecutionException ex) {
// Log exception at first so you could know if something went wrong and needs to be fixed
}
return jsonResult;
}
}
Another approach would be creating a class that implements Callable. Whatever of these approaches you choose depends on your application, and maybe person's taste :).
Happy that I helped.

Sending JSON object from activity to Fragment

Heyo guys
I've been searching for an answer for this for hours now. Could you please help. It's really important.
So what I am trying to do is to get a JSON object in an Asynctask in the Login activity and then sending this object to a Fragment where I will parse it.
Here's the Login activity's Asynctask where I try to send the JSON (which i get as a retrun from postrequest() ) :
#Override
protected Void doInBackground(Void... params)
{
String JSON = null;
try
{
JSON = new String(postrequest());
Bundle bundle = new Bundle();
bundle.putString("jString", JSON);
Timetable fragobj = new Timetable();
fragobj.setArguments(bundle);
}
catch (IOException e)
{
e.printStackTrace();
}
}
And here's my Fragment (Timetable.class) where I try to get the JSON in onCreatView
String jsonString = getArguments().getString("jString");
JSONObject jsonObject = new JSONObject(jsonString);
My problem with all that is that I always get a NullPointerException when I try to get the jsonString with getArguments.
Any help would be appreciated. Cheers
P.S. I hope my post isn't too chaotic XD
Rather than passing the variables from AsyncTask to Fragment use an interface and then pass it back...
In your AsyncTask do the following:
public interface WebServiceResult {
void OnWebService(int type, String result);
}
That is how I have it set up so I can use the same web service for multiple different calls.
In your AsyncTask, create a constructor and have it state the interface:
WebServiceResult listener;
public WebService(Context c, WebServiceResult listener, JSONObject jObject,
int typeofCall) {
this.c = c;
this.typeofCall = typeofCall;
this.listener = listener;
this.jObject = jObject;
}
Code from my own App.
Then after the call is complete pass by your json from the doInBackground to Your onPostExecute
if (result != null) {
if (listener != null)
listener.OnWebService(typeofCall, result);
} else {
//Do Else Statement
}
This passes the variable back to your activity which you can send to the fragment using the getArguments.

Categories