i want to get the value returns by asynctask after it's been completed. this is my code :
class asyncGet extends AsyncTask<Void, String, String> {
Boolean goterror = false;
#Override
protected String doInBackground(Void... params) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response;
try {
request.setHeader("Cache-Control", "no-cache");
request.setHeader("Cache-Control", "no-store");
response = client.execute(request);
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line);
}
in.close();
return str.toString();
} catch (Exception e) {
goterror = true;
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
if (result != null && goterror == false) {
}
}
The async is in another class , I want to show the result when it's done .
How can I return the result from the async ?
thanks
if you want to keep it asynchronous then it is already implemented in your code,
use onPostExecute method, "result" contains the returned data.
Or if you want it to return data synchronously then use the extended asynctask like below:
try {
String result = new asyncGet().execute().get();
} catch (InterruptedException e) {
e.printStackTrace(); //handle it the way you like
} catch (ExecutionException e) {
e.printStackTrace();//handle it the way you like
}
You can create an interface, as follows:
public interface OnStringListener {
void onStringCompleted(String s);
void onStringError(String error);
}
and you will have to create the constructor of your AsyncTask with OnStringListener as parameter:
class asyncGet extends AsyncTask<Void, String, String> {
Boolean goterror = false;
private final OnStringListener mListener;
public asyncGet(OnStringListener listener) {
mListener = listener;
}
//The rest of your code
And in your onPostExecute method you can return the String sending it by the method onStringCompleted:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
if (result != null && goterror == false) {
}
if (mListener != null) {
mListener.onStringCompleted(result);
}
}
Of course, your methods onStringCompleted and onStringError have to be created in the Activity that you want to get the result of your AsyncTask. From there, you will be able to use your result in your other class.
I expect it will be helpful to you!
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)
So the philosophy is you override doInBackground and when the doInBackground finishes its task it passes the result to onPostExecute which result is available in your main thread.
Read the Full usage here
and if you still want synchronous execution call get() as explained by #meghraj27
You can implement an interface to an Activity or class where you want the result of the AsynTask and trigger that interface from the AsynTask.
You can refer this post
How to handle return value from AsyncTask
Related
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.
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 have to download huge amount of data from server. It is taking minimum 10 seconds to download. Here is my code to download using asyntask class. And I want to cancel the downloading operation unconditionally if the user clicks on home button while downloading operation is going on. The problem is... I'am executing cancel() method but it is not cancelling the downloading operation. I'am seeing that operation is running in background in logcat view even i came out of application. I just want to stop the execution of doInBackground() method. Please guide/help me.
on click of download button :
dwnldTask = new DownloadTask ();
dwnldTask.execute(SERVER_URL);
And here is Asynctask class :
class DownloadTask extends AsyncTask<String, Void, Object>{
private Object response = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
displaying progress dialog on UI
}
#Override
protected Object doInBackground(String... params) {
try{
DataConnection dc = new DataConnection();
this.response = dc.connectToServer(params[0]);
if(isCancelled()){
return null;
}
}catch (Exception e) {
if(isCancelled()){
return null;
}
e.printStackTrace();
showToastMSG(e.getMessage());
}
return this.response ;
}
#Override
protected void onPostExecute(Object response) {
super.onPostExecute(response);
if(response != null ){
successfully downloaded... go to next activity
}
cancel progress dialog here
}
}
Inside onPause()..
#Override
protected void onPause() {
super.onPause();
if(dwnldTask != null && dwnldTask.getStatus() == AsyncTask.Status.RUNNING){
dwnldTask.cancel(true);
}
cancel the progress dialog if it is showing
}
Here is the method located in another class named DataConnection...
public Object connectToServer(String url) throws Exception{
HttpGet request = new HttpGet(url);
request.addHeader("accept","application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity httpEntity = response.getEntity();
InputStream responseInputStream = httpEntity.getContent();
return myUtilObject.convertInputStreamToString(responseInputStream);
}
I agree with Ran - you didn't write the code of:
myUtilObject.convertInputStreamToString
but im guessing you loop there over the inputstream with a buffer you predefined its size (maybe with BufferedReader?) - in this loop you should check the stop condition of your async thread - isCancelled() is a good example.
The loop should stop if the thread is canceled, i.e.:
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is), 1024);
while ((line = rd.readLine()) != null && !isCancelled())
{
total.append(line);
}
You are checking the isCancelled() method after you perform the download, so there's no reason it would get cancelled in the middle.
Usually you do something like this:
while (!isCancelled()) {
// Download next buffer..
}
In this case, the loop will stop once a cancel request has been made.
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 :)
I am looking to insert userdata to database by calling URL link to webservice on server:
ex:
this is the link:
http://mydomain.com/AndroidWebService.asmx/nInsertInfo?id=12&lat=23.2222&log=12322
So I want to call this url in hidden mode.
Use android android AsyncTask to post data. It work in android background when application is open.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
Like
AsyncTask
AsyncTask
AsyncTask
Thanks.
Thanks all for your valuable solutions.
i have did it by creating WebView
WebView myWebView = (WebView) findViewById(R.id.view1);
myWebView.loadUrl(urll);
then i can manage my WebView as i want: hide it, alignment as error or result returns.
Maybe this example will help you :
public class URLConnectionTask <Result> extends AsyncTask<URL, Void, InputStream> {
#Override
protected InputStream doInBackground(URL... params) {
InputStream is;
HttpUriRequest request;
URI uri;
HttpResponse response;
if (params.length == 0)
return null;
is = null;CredentialsProvider credProvider = new BasicCredentialsProvider();
if (userName != null && userName.length() > 0 && password != null && password.length() > 0)
credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(userName, password));
//
DefaultHttpClient http = new DefaultHttpClient();
http.setCredentialsProvider(credProvider);
//
uri = URI.create(params[0].toString());
if (isPost)
request = new HttpPost(uri);
else
request = new HttpGet(uri);
try {
response = http.execute(request);
is = response.getEntity().getContent();
//Log.d(TAG, "doInBackground() response: "+EntityUtils.toString(response.getEntity()));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (processingHandler != null && is != null)
processingResult = processingHandler.processResponse(is);// processingHandler is an instance which implements ProcessingHandler interface (ex. VizMarket). processResponse() is implemented on this class.
return is;
}
#Override
protected void onPostExecute (InputStream result) {
input = result;
if (result == null)
return;
//instruction for inserting data on db ....
try {
result.close();
} catch (IOException e) {
}
}
}
You should call URL in AsyncTask. For instance: Return data from AsyncTask class
U have to use a thread to fetch data from server and insert into to DB or in android you can use AsyncTask.
You can have a search :ClickableSpan
And put your insert code into the OnClick body~
Just like:
String yourTextStr;
SpannableString sp = new SpannableString(yourTextStr);
int start;//the start of your url in the text;
int end ;//the end of your url in the text;
sp.setSpan(new ClickableSpan() {
#Override
public void onClick(View widget) {
//Your Insert Code
}
}, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);