In some way I do understand the Handler, but I'm not sure what to do with the params and how to let the code wait until the job is done in the background. I want the UI to be normally working and in the background I want to do an exchange rate calculation.
I have the following:
I call new getOnlineExchangeRate().execute(""); //Get Exchange Rate in BG
After that I want to have a result=amount*exchangerate, but the code is not waiting for the result.
Can somebody tell me how the calculation waits till we have an exchangerate. Do I have to send some params and how would that look?
.
.
.
.
.
public double getYahooExchangeRate(String ER){
double exchangerate=0;
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+ER+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
//s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
exchangerate=Double.parseDouble(exResult);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ALS.Toast(myContext.getString(R.string.conversionerror), false);
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ALS.Toast(myContext.getString(R.string.conversionerror), false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ALS.Toast(myContext.getString(R.string.conversionerror), false);
}
return exchangerate;
}
public String getJson(String url)throws ClientProtocolException, IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
public class getOnlineExchangeRate extends AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
ALS.Toast(myContext.getString(R.string.exchangeratesupdated), true);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// perform long running operation operation
getYahooExchangeRate(USDEUR);
return null;
}
I think your problem is in this line:
#Override
protected String doInBackground(String... params) {
getYahooExchangeRate(USDEUR);
return null;
You want to return the result of getYahooExchangeRate and not null :)
So change this and the return-value should be a double. So change this to:
#Override
protected Double doInBackground(String... params){
return getYahooExchangeRate(USDEUR);
}
You also have to change your class header:
public class getOnlineExchangeRate extends AsyncTask<String, Void, Double> {
AsyncTask<Params, Progress, Result>
The generic part tells the AsyncTask which Informationstypes are handled.
The first is the type for the params of doInBackground(Params... )
The second is the type of the progress-Information
The last explains which type is returned by doInBackground(), so it changes the method-header from
protected Result doInBackground(Params... params){ };
to
protected double doInBackground(Params... params){};
To bring back the Result i would use and Observer oder Callback-Pattern.
Edit: changed double to Double, because primitives cannot be used for Generics.
the code is not waiting for the result. Can somebody tell me how the calculation waits till we have an exchangerate. Do I have to send some params and how would that look?
You could use AsyncTask#get() to force the code to wait, but this blocks the main thread until the AsyncTask completes which defies the purpose of using an asynchronous task.
It is best to design your Activity to proceed without the exchange rate, just like my mail app loads allowing me to compose messages and read old messages while the new messages are being fetched. When the asynchronous data loads then you can update your UI with the new information. (I believe this is what you are trying to do.)
To add on to user1885518 code, you should use your AsyncTask as a subclass in your Activity like this:
public class MainActivity extends Activity {
private class getOnlineExchangeRate extends AsyncTask<Void, Void, Double> {
#Override
protected Double doInBackground(Void... params) {
return getYahooExchangeRate(params[0]);
}
#Override
protected void onPostExecute(Double rate) {
// Do something with rate
}
}
...
}
Once you know which exchange rate you want, call:
new getOnlineExchangeRate().execute(USDEUR); //Get Exchange Rate in BG
Now when you have gotten the rate from online, the code calls onPostExecute() with your desired rate. Inside on onPostExceute() you can call whatever method you want in your ACtivity to calculate result=amount*exchangerate and display result wherever it is appropriate.
Related
I am beginner in Android and I need some help. So, I have a procedure with sub-procedures inside. How can I finish one before starting a new one. Here is a code to better understand:
public void onCellLocationChanged(CellLocation lokacija) {
super.onCellLocationChanged(lokacija);
location = (GsmCellLocation) Phone.getCellLocation();
textCellId.setText(String.valueOf(location.getCid() % 65536));
textCellLac.setText(String.valueOf(location.getLac()));
String JSON_URL_string=JSON_URL + "?cellid=" + String.valueOf(location.getCid()%65636);
getJSON(JSON_URL_string);
myJSONString = textCellNameSakriven.getText().toString();
ParseJSON(myJSONString);
}
Problem is that myJSONString is empty, cause textCEllNameSkriven is also empty. That textView textCellNameSkriven is made when getJSON(JSON_URL_string) is finished. If I run debugger and go step by step, app goes directly from getJSON(JSON_URL_string) row to the next one and the next etc
Edit: Maybe the problem is that onPostExecute is not finished before starting ParseJSON. Here is also a code for getJSON:
private void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait...", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
textCellNameSakriven.setText(s);
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
Since you are running a async task it practically runs on a different thread, so your getJson method need not wait for post execute and can return after starting the async task, so you can never be sure in this way that parseJson gets executed after textView is populated. You are running into classic race condition issue.
Your issue could be easily solved, if you have a callback which is called after postExecute is done, and you can handle parseJson there
So, something simple like , create interface MyCallback
public interface MyCallback {
public OnReadJsonDone();
}
Let your activity implement this MyCallback
public MainActivity implements MyCallback
{
...........
#Override
public OnReadJsonDone(){
parseJson();
}
Now change signature of getJson to
getJSON(string json, final MyCallback callback) {
Now in onpostexecute
//call OnReadJsonDone
callback.OnReadJsonDone()
So, all you now need is while calling getJSon pass this as second param
getJSON(JSON_URL_string,this);
Haven't tested this but you get the idea
I'm trying to see how works an Asynctask class in android. In particular i want reveal in real time the status of the class for see when it is running and when it has finished. For do this, i have created a class that extend the main activity and another class that is the asynctaks class.
This is my main class:
public class PhotoManagement extends Activity{
private String numberOfSelectedPhotos;
private Bitmap currentImage;
private String initConfiguration = "http://www.something.com";
private String response;
private ArrayList<String> formatPhotoList = new ArrayList<String>(); //create a list that will contains the available format of the photos downloaded from the server
private ArrayList<String> pricePhotoList = new ArrayList<String>(); //create a list that will contains the available price for each format of the photos
DownloadWebPageTask webPage = new DownloadWebPageTask();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume(){
super.onResume();
webPage.execute(initConfiguration);
if(webPage.getStatus() == AsyncTask.Status.PENDING){
Log.i("STATUS","PENDING");
}
if(webPage.getStatus() == AsyncTask.Status.RUNNING){
Log.i("","RUNNING");
}
if(webPage.getStatus() == AsyncTask.Status.FINISHED){
Log.i("","FINISHED");
}
}
}
As you can see i want only see the passages of the status with a simple log.
And here there is the asynctask class.
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient(); //create a new http client
HttpGet httpGet = new HttpGet(url); //create a new http request passing a valid url
try {
HttpResponse execute = client.execute(httpGet); //try to execute the http get request
InputStream content = execute.getEntity().getContent(); //prepare the input stream to read the bytes of the request
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s; //until is present a line to read, the response variable store the value of the lines
}
} catch (Exception e) {
Log.i("MyApp", "Download Exception : " + e.toString()); //Print the error if something goes wrong
}
}
return response; //return the response
}
#Override
protected void onPostExecute(String result) {
result = doInBackground(initConfiguration); //take the result from the DownloadWebPageTask class
result = result.replace("null", "");
Log.i("RESULT",""+result);
//find the price and format value from the result using XmlPullParser
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader ( result ) );
int attributeNumber = xpp.getAttributeCount();
int eventType = xpp.getEventType();
String currentTag = null;
while(eventType != XmlPullParser.END_DOCUMENT){
if(eventType == XmlPullParser.START_TAG) {
currentTag = xpp.getName();
if (currentTag.equals("product")){
xpp.getAttributeValue(null, "name");
formatPhotoList.add(xpp.getAttributeValue(null, "name"));
Log.i("FORMAT PHOTO",""+xpp.getAttributeValue(null, "name"));
}
}
eventType = xpp.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
Log.i("","ERROR XML PULL PARSER");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("","ERROR IOEXCEPTION");
}
}
}
}
As you can see i have implemented also the method onPostExecute that should be called when the asynctask method has finished to execute the instructions right?
So at this point i don't understand why my log RUNNING and my log FINISHED never appear on the log cat.
What i'm doing wrong?
I'm tried to follow this topic Android, AsyncTask, check status? but in my case it isn't working.
Thanks
Problem :
You are creating object like
DownloadWebPageTask webPage = new DownloadWebPageTask();
But you are calling asynctask on different object,
new DownloadWebPageTask().execute(initConfiguration);
Solution :
It should be like
webPage.execute(initConfiguration);
#Override
protected void onResume(){
super.onResume();
new DownloadWebPageTask().execute(initConfiguration);
here do like this
#Override
protected void onResume(){
super.onResume();
webPage.execute(initConfiguration);
You didn't implement webPage.execute(), add it
Most probably the task hasn't finished or even started yet. As you probably know the AsyncTask is doing it's (background) work on a different thread, so your onResume is running in parallel with it. You can either use the task's get() method to wait for it to finish and get the result of the doInBackground() method and then query for it's status or notify your activity from the task's onPostExecute() method to let it know (and log) that it has finished. I don't recommend you the first option because it will actually block the UI thread and will make your usage of AsyncTask pointless.
As mentioned I get the above error which I know is because my application is doing networking in UI thread. I went through a lot of stackoverflow questions which advise to use AsyncTask for this purpose. From what I understand asynctask is asynchronous and will run independently in the background. But I need to fetch the data from http and display on the main thread. So basically my UI thread should be blocked till I have the JSON fetched so that I can display it.
My questions are
1) Since I need to run http networking in another thread how do I do it?
2) Do I use an async thread?
3) How do I block my UI thread for the async thread to fetch the result?
4) How do I pass the result from async thread back to UI thread?
This is the current JSON parser class that I use.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONfromURL(String url) {
// initialize
InputStream is = null;
String result = "";
JSONArray jArray = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
return null;
}
// convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("log_tag", "JSON data" + result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
return null;
}
// try parse the string to a JSON object
try {
jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
return null;
}
return jArray;
}
}
And this is my MainActivity where I call JSONparser to fetch some data that I need to display
JSONArray json = jParser.getJSONfromURL(temp);
if (json == null) {
return -1;
}
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
// Getting Array of Contacts
// Storing each json item in variable
asr_iq = c.getString("lMAsr");
sunrise_iq = c.getString("lMSunrise");
fajr_iq = c.getString("lMFajr");
isha_iq = c.getString("lMIsha");
dhuhr_iq = c.getString("lMDhuhr");
maghrib_iq = c.getString("lMMaghrib");
} catch (JSONException e) {
e.printStackTrace();
}
}
Load your asynctask on the UI thread.
If you cannot do any network related operation on the UI Thread Honeycomb and later. You will get a NetworkOnMainThread Exception.
new MyTask(url).execute();// can pass parameter to class constructor
// can also pass url to doInBackground.
Async task
class MyTask extends AsyncTask<Void,Void,Void>
{
String url;
public MyTask(String url)
{
this.url =url
}
#Override
protected Void doInBackground(Void... params) {
// all your network related operation
// invoked on the background thread
// all code from getJSONfromURL(param)
// do not update ui here
return null;
}
#Override
protected void onPostExecute(Void result) { // invoked on the ui thread
// TODO Auto-generated method stub
super.onPostExecute(result);
// dismiss progress dialog
// update ui here
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// display progress dialog
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
}
Detailed information # http://developer.android.com/reference/android/os/AsyncTask.html
Edit:
Use a Handler. Return result in doInBaCkground().
Example in onPostExecute()
Message msg=new Message();
msg.obj=result.getProperty(0).toString();
mHandler.sendMessage(msg);
In your activity onCreate()
Handler mHandler = new Handler() {
#Override public void handleMessage(Message msg) {
//ArrayList s=(ArrayList)msg.obj;
SoapObject s =(SoapObject) msg.obj;
tv.setText("Result = "+s.toString());
}
};
You can also use runonuithread to update ui from doInBackGround()
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
_tv.setText("update from doinbackground");
}
});
Using Core Java,
Have your getJson execution logic in a Runnable/Callable(Java concurrency class), submit it via executors so that its an Asynch call.
Then with in your Runnable/Callable once json is retrived call the class which will have logic to display the json, this clas can be designed as a listener and you may publish an even after getting json response
I am getting the exception android.os.NetworkOnMainThreadException when I tried to use the following codes:
public class CheckServer extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Runnable runn = null;
HttpTask.execute(runn);
}
private class HttpTask extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpURLConnection urlConnection = null;
URL theURL = null;
try {
theURL = new URL("http://192.168.2.8/parkme/Client/clientquery.php?ticket=66t");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
urlConnection = (HttpURLConnection) theURL.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String response = null;
try {
response = readInputStream(urlConnection.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
private String readInputStream(InputStream is) {
// TODO Auto-generated method stub
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return total.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}}
If possible can someone tell me how to use it inside an Async Task and get the output? I tried but can't seem to get anywhere.
NetworkOnMainThread Exception occurs because you are running a network related operation on the main UI Thread.This is only thrown for applications targeting the Honeycomb SDK or higher
You should be using asynctask.
http://developer.android.com/reference/android/os/AsyncTask.html
In onCreate()
new TheTask().execute();
You can also pass parameters like url to the constructor of AsyncTask and use the same in doInBackground()
class TheTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{ super.onPreExecute();
//display progressdialog.
}
protected void doInBackground(Void ...params)//return result here
{
//http request. do not update ui here
return null;
}
protected void onPostExecute(Void result)//result of doInBackground is passed a parameter
{
super.onPostExecute(result);
//dismiss progressdialog.
//update ui using the result returned form doInbackground()
}
}
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
Ok, lets do it step by step ...
1) create private class extending AsyncTask
private class HttpUrlConnectionTask extends AsyncTask {
2) Override the doInBackground() method, this will do the heavy load
#Override
protected Object doInBackground(Object... params) {
// your HttpUrlConnection code goes here
return response;
3) Once the job is done and returns, the onPostExecute() method will be called. The result parameter contains the return value of doInBackground() - so response.
#Override
protected void onPostExecute(Object result) {
Within this method you can update your UI.
4) Finally lets have a look onto the HttpUrlConnection code
HttpURLConnection urlConnection = null;
URL theURL = new URL(url);
urlConnection = (HttpURLConnection) theURL.openConnection();
String response = readInputStream(urlConnection.getInputStream());
return response;
Hope this helps. Happy coding!
#Raghunandan comes with a really good explanation of how AsyncTask works
Here you go:
public static class InitializeTask extends MyAsyncTask<String, String, String> {
private Activity activity;
private ProgressDialog dialog;
public InitializeTask(Activity activity) {
this.activity = activity;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(activity, result, Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://192.168.2.8/localhost/parkme/Client/clientquery.php?ticket=");
try {
HttpResponse response = httpclient.execute(httpget);
if(response != null) {
String line = "";
InputStream inputstream = response.getEntity().getContent();
return convertStreamToString(inputstream);
} else {
return "Unable to complete your request";
}
} catch (ClientProtocolException e) {
return "Caught ClientProtocolException";
} catch (IOException e) {
return "Caught IOException";
}
}
private String convertStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (Exception e) {
return "Stream Exception";
}
return total.toString();
}
}
A little side note, it is generally considered bad code to catch just Exception, since this will catch anything, and you are not accounting for what it is.
To use the AsyncTask in the Activity do this:
InitializeTask task = new InitializeTask(this)
task.execute()
Exactly as it says, network activity isn't allowed on the thread the activity ran in. Moving your code to an Asynctask is the way to do it properly. Though if you're just trying to get your concept working still you can do this...
//lazy workaround with newer than gingerbread
//normally UI thread can't get Internet.
if(Build.VERSION.SDK_INT >= 9){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
And then the UI thread actually can. I wouldn't release anything like this however, I haven't even tried infact. It's just my lazy debugging move I use a lot.
I'm trying to use the HTTPClient to get the html code of a website using an AsyncTask and passing back the code to my main Activity.
I used this code in order to (try to) do that :
public class AsyncTaskGet extends AsyncTask<String, String, String>{
String result;
InputStream in;
protected String doInBackground(String... params) {
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet("http://www.google.fr");
HttpResponse response = httpClient.execute(httpRequest);
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(null, result), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
if (response != null) {
in = response.getEntity().getContent();
}
in.close();
result = sb.toString();
}catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
}catch(IOException e){
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
//Here is one of my problem, I don't know how to get the returned value result as a string.
}
}
This is my AsyncTaskGet, since I tried lots of fruitless attempts, I erased all my code in the main activity except this part.
new AsyncTaskGet().execute();
So basically, What i'd like to do is getting the result back on my main activity as a string to display it in a TextView.
For now I want my app to be simple so I can understand the basics of using AsyncTasks, I didn't check for internet conectivity or stuff like that, I add the permission on the manifest to use internet (obviously
(Please be a little indulgent since it is one of my first apps)
One last thing, please excuse my poor english, i'm unfortunately not a native english speaker as you must have seen.
In advance, thanks a lot !
Sincerely :)
The easiest thing is to pass the calling activity via a constructor to your AsyncTask and create a method that will take the result as a parameter in the activity itself.
private Activity mActivity;
public AsyncTaskGet(Activity activity) {
mActivity = activity;
}
protected void onPostExecute(String result) {
mActivity.takeItBack(result);
}
There are some limitations: the current code just works with a 1 to 1 relationship between AsyncTask and Activity, means the private member variable type must be the activity from which you call it. If you don't want that you need to implement an interface:
// interface
public interface AsyncTaskCallback {
void takeItBack(String result);
}
// activity
public MyActivity implements AsyncTaskCallback {
#Override
public void takeItBack(String result) {
// do something
}
}
// AsyncTask
public class AsyncTaskGet extends AsyncTask<String, String, String> {
private AsyncTaskCallback mCallback;
public AsyncTaskGet(AsyncTaskCallback callback) {
mCallback= callback;
}
protected void onPostExecute(String result) {
mCallback.takeItBack(result);
}
}
You are already passing result to onPostExecute() as a String. If your AsyncTask is an inner class of your Activity then you can set result to a field variable in your Activity. Otherwise, you can call a function in your Activity from onPostExecute() to do what you want with the data.
Also, your poor English is really not bad at all :)