there is any way that I can get the return data from execute action?
for example I have the next line that calls to the execute function - googlePlacesReadTask.execute(toPass); and the googlePlacesReadTask return some parser data to me. So how can I get this data that the action return to me ?
AsyncTask -
public class PlacesDisplayTask extends AsyncTask<Object, Integer, List<HashMap<String, String>>> {
JSONObject googlePlacesJson;
GoogleMap googleMap;
#Override
protected List<HashMap<String, String>> doInBackground(Object... inputObj) {
List<HashMap<String, String>> googlePlacesList = null;
Places placeJsonParser = new Places();
try {
googlePlacesJson = new JSONObject((String) inputObj[1]);
googlePlacesList = placeJsonParser.parse(googlePlacesJson);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
if(String.valueOf(googlePlacesList) != "[]"){
//Find the place
}
else{
//No place found
}
return googlePlacesList;
}
}
second AsyncTask -
public class GooglePlacesReadTask extends AsyncTask<Object, Integer, String> {
String googlePlacesData = null;
GoogleMap googleMap;
#Override
protected String doInBackground(Object... inputObj) {
try {
googleMap = (GoogleMap) inputObj[0];
String googlePlacesUrl = (String) inputObj[1];
Http http = new Http();
googlePlacesData = http.read(googlePlacesUrl);
} catch (Exception e) {
Log.d("Google Place Read Task", e.toString());
}
return googlePlacesData;
}
#Override
protected void onPostExecute(String result) {
PlacesDisplayTask placesDisplayTask = new PlacesDisplayTask();
Object[] toPass = new Object[2];
toPass[0] = googleMap;
toPass[1] = result;
placesDisplayTask.execute(toPass);
}
}
Thanks.
Based on Which type of data you want to get from that method. If that method returns String data then save it in String variable.
For example :
In your case if googlePlacesReadTask returns String type of data then store it in string variable like :
String data = googlePlacesReadTask.execute(toPass);
Hope it will help
Use the onPostExecute method of your AsyncTask, there you have the response from the service (sent by the background process), handle it as you need.
If you need the data back in your class, you can send the AsyncTask a reference to it and call one class method from your AsyncTask sending it the required data
Just one way of doing it, there are more.
Dummy example:
public class MyAsyncTask extends AsyncTask<Void, Void, String> {
private MyClass myClass;
public MyAsyncTask(MyClass myClass) {
this.myClass = myClass;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
return something;
}
#Override
protected void onPostExecute(String something) {
super.onPostExecute(something);
if(myClass != null){
myClass.thereYouGo(something);
}
}
}
From your class (MyClass):
new MyAsyncTask(this).execute();
Receiver method in MyClass:
public void thereYouGo(String something){
// do what you want
}
Related
I have an issue with AsyncTask
String latlong = "lat=48.8534100&lon=2.3488000";
city = "Paris";
getWeather w = new getWeather(latlong,this);
w.execute();
This gs.alerter() should be executed after the onpostexecute, but it's execued before
gs.alerter("thiss" + currentWeather); //This is a Log.i function
gs.cities.add(new City(city, currentWeather + "°", image));
initializeAdapter();
The AsyncTask class is :
public class getWeather extends AsyncTask<Void, Void, JSONObject> {
String latlong;
MainActivity obj;
JSONParser jParser = new JSONParser();
JSONObject json;
public getWeather(String latlong,MainActivity obj)
{
this.latlong = latlong;
this.obj = obj;
}
#Override
protected JSONObject doInBackground(Void... params) {
// TODO Auto-generated method stub
String URL = "http://api.openweathermap.org/data/2.5/weather?" +
latlong +
"&appid=APIKEY" +
"&units=metric";
json = jParser.getJSONFromUrl(URL);
return json;
}
#Override
protected void onPostExecute(JSONObject result) {
this.obj.setWeather(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
The setweather code is on the activity class :
public void setWeather(JSONObject obj){
try {
JSONObject main = obj.getJSONObject("main");
Double initWeather = new Double(main.getString("temp"));
int finalWeather = (int)Math.round(initWeather * 1) / 1;
this.currentWeather = Integer.toString(finalWeather);
This gs.alerter() should be executed just right after the .execute()
gs.alerter(this.currentWeather);
} catch (JSONException e) {
e.printStackTrace();
}
}
So the problem is that the code just after .execute() is executed after onpostexecute(). I want to execute it in this order :
.execute()
onpostexecute() to affect the currentWeather variable
And then add City ...
Any help is needed.
Thank you all
PS : I am a beginner in Android development :)
put this code into a method:
public void methodName() {
gs.alerter("thiss" + currentWeather); //This is a Log.i function
gs.cities.add(new City(city, currentWeather + "°", image));
initializeAdapter();
}
and now:
#Override
protected void onPostExecute(JSONObject result) {
this.obj.setWeather(result);
obj.methodName();
}
Create Interface
public interface OnTaskCompleted{
void onTaskCompleted();
}
Your Activity Code will look like
class YourActivity implements OnTaskCompleted {
void someFunctionToExecute()
{
String latlong = "lat=48.8534100&lon=2.3488000";
city = "Paris";
getWeather w = new getWeather(latlong,this);
w.execute();
}
// this code will be called after postExecute
void OnTaskCompleted(){
gs.alerter("thiss" + currentWeather);
gs.cities.add(new City(city, currentWeather + "°", image));
initializeAdapter();
}
}
Your AsyncTask Code Will look like
public class getWeather extends AsyncTask<Void, Void, JSONObject> {
String latlong;
MainActivity obj;
JSONParser jParser = new JSONParser();
JSONObject json;
public getWeather(String latlong,MainActivity obj)
{
this.latlong = latlong;
this.obj = obj;
}
#Override
protected JSONObject doInBackground(Void... params) {
// TODO Auto-generated method stub
String URL = "http://api.openweathermap.org/data/2.5/weather?" +
latlong +
"&appid=APIKEY" +
"&units=metric";
json = jParser.getJSONFromUrl(URL);
return json;
}
#Override
protected void onPostExecute(JSONObject result) {
this.obj.setWeather(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
obj.OnTaskCompleted(); // calling after postexecute
}
}
I'm still NEW, i repeat, NEW in android studio and I'm trying to display place name,vicinity,lat and long using listview. I already got listview ready but I couldnt get the string from the OnPostExecute. I tried using this https://stackoverflow.com/a/12575319/5776859 but It did not work at all, or maybe I didnt do it correctly. I hope anyone could help me or show me the proper way to get the string and double from the OnPostExecute.
public class PlacesDisplayTask extends AsyncTask<Object, Integer,
List<HashMap<String,String>>> {
JSONObject googlePlacesJson;
GoogleMap googleMap;
#Override
public List<HashMap<String, String>> doInBackground(Object... inputObj) {
List<HashMap<String, String>> googlePlacesList = null;
Places placeJsonParser = new Places();
try {
googleMap = (GoogleMap) inputObj[0];
googlePlacesJson = new JSONObject((String) inputObj[1]);
googlePlacesList = placeJsonParser.parse(googlePlacesJson);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return googlePlacesList;
}
#Override
protected void onPostExecute(List<HashMap<String,String>> list) {
for (int i = 0; i < 3; i++) {
HashMap<String, String> googlePlace = list.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
}
}
}
Use interfaces like this
public class PlacesDisplayTask extends AsyncTask<Object, Integer,
List<HashMap<String,String>>> {
public AsyncResponse delegate = null;
JSONObject googlePlacesJson;
GoogleMap googleMap;
#Override
public List<HashMap<String, String>> doInBackground(Object... inputObj) {
List<HashMap<String, String>> googlePlacesList = null;
Places placeJsonParser = new Places();
try {
googleMap = (GoogleMap) inputObj[0];
googlePlacesJson = new JSONObject((String) inputObj[1]);
googlePlacesList = placeJsonParser.parse(googlePlacesJson);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return googlePlacesList;
}
#Override
protected void onPostExecute(List<HashMap<String,String>> list) {
delegate.processFinish(list);
}
}
and your activity should handle the response by implementing the interface's method
public class MainActivity implements AsyncResponse{
PlacesDisplayTask asyncTask =new PlacesDisplayTask ();
#Override
public void onCreate(Bundle savedInstanceState) {
//this to set delegate/listener back to this class
asyncTask.delegate = this;
//execute the async task
asyncTask.execute();
}
//this override the implemented method from asyncTask
void processFinish(List<HashMap<String,String>> list){
//Here you will receive the result fired from async class
//of onPostExecute(result) method.
for (int i = 0; i < 3; i++) {
HashMap<String, String> googlePlace = list.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
}
}
}
Create an interface like this
public interface AsyncResponse {
void processFinish(List<HashMap<String,String>> list);
}
A less tedious way to accomplish what you're trying to do is to perform whatever task that requires the returned value within onPostExecute(). You can input most references like context using a constructor and store them as global variables to use.
Another way can be to set the return type in the signature of the class to List<HashMap<String, String>> and you can call <PlacesDisplayTask object>.execute().get() method. But this will make the background process synchronous i.e. it will block the UI thread, waiting on the result.
The last alternative that I can think of involves the use of a delegate as described in the link you've already posted.
I'm trying to learn how to work with AsyncTask. I have code in the doInBackground that returns a String array, and a callback that invokes an interface to return it to the MainActivity. I am successfully executing the AsyncTask.
The problem is: trying to return the array via onPostExecute I'm getting an arguments error; it won't accept the array. How do I use the onPostExecute method to return the value feeds? I have tried to change the result of doInBackground but that wouldn't accept an array either.
Here is the interface called in MainActivity:
interface DownloadFinishedListener {
void notifyDataRefreshed(String[] feeds);}
Here is the callback:
try {
mCallback = (DownloadFinishedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement DownloadFinishedListener");
}
and here is the AsyncTask:
public class DownloaderTask extends AsyncTask<Integer, Void, String> {
#Override
protected String doInBackground(Integer... params) {
downloadTweets(params);
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mCallback.notifyDataRefreshed(s); //trying to send back feeds
}
// Simulates downloading Twitter data from the network
private String[] downloadTweets(Integer resourceIDS[]) {
final int simulatedDelay = 2000;
String[] feeds = new String[resourceIDS.length];
try {
for (int idx = 0; idx < resourceIDS.length; idx++) {
InputStream inputStream;
BufferedReader in;
try {
// Pretend downloading takes a long time
Thread.sleep(simulatedDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
inputStream = mContext.getResources().openRawResource(
resourceIDS[idx]);
in = new BufferedReader(new InputStreamReader(inputStream));
String readLine;
StringBuffer buf = new StringBuffer();
while ((readLine = in.readLine()) != null) {
buf.append(readLine);
}
feeds[idx] = buf.toString();
if (null != in) {
in.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return feeds;
}
}
The problem is: trying to return the array via onPostExecute I'm
getting an arguments error; it won't accept the array
You need to pass String Array as last generic argument to AsyncTask which is return type of doInBackground and argument type of onPostExecute.
Do following changes :
1. extend AsyncTask as:
public class DownloaderTask extends AsyncTask<Integer, Void, String[]>
2. Change doInBackground method return type from String to String[] :
#Override
protected String[] doInBackground(Integer... params) {
downloadTweets(params);
return downloadTweets(params);
}
3. Change onPostExecute paramter type from String to String[] :
protected void onPostExecute(String[] s) {
super.onPostExecute(s);
mCallback.notifyDataRefreshed(s); //trying to send back feeds
}
You should pass String[] as last argument in your AsyncTask not just String as you are doing and your AsyncTask should look like similar to this:
public class DownloaderTask extends AsyncTask<Integer, Void, String[]> {
#Override
protected String[] doInBackground(Integer... params) {
return downloadTweets(params);;
}
#Override
protected void onPostExecute(String[] s) {
super.onPostExecute(s);
mCallback.notifyDataRefreshed(s); //trying to send back feeds
}
}
Hello so I have already an expirience with AsyncTask so I can manage to get some data with PHP scripts from an SQL Server and parsed them with JSON. Now what I would want is to know how can I use the AsyncTask in order to load images to some activities. Also is there anyway that I can call the AsyncTask before the app starts? because that would be really helpful too.
I don't have any adapters I am just using this for the AsyncTask:
// The definition of our task class
private class PostTask extends AsyncTask<String, Integer, String> {
private String postName;
private JSONObject jsonvar = new JSONObject();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
this.postName = params[0];
String status = "";
List<NameValuePair> values = new ArrayList<NameValuePair>();
values.add( new BasicNameValuePair( "username", this.postName ) );
final AndroidHttpClient client = AndroidHttpClient.newInstance( "" );
HttpResponse response = HttpHelper.postResponse( client, Register.phpUrl, values );
String data = HttpHelper.getData( response );
try {
jsonvar = new JSONObject(data);
status=jsonvar.getString("status");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
client.close();
return status;
}
// #Override
// protected void onProgressUpdate(Integer... values) {
// super.onProgressUpdate(values);
// }
#Override
protected void onPostExecute(String status) {
String session = "", status_message = " ";
try {
status_message = jsonvar.getString("status_message");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
super.onPostExecute(status);
}
}
}
As i can tell with information provided, supposing that what you read from your server is the image URL and obtain it in JSON format, what i would do is writing a listener to your AsyncTask, calling it in onPostExecute method, and loading it in your Activity using PicassoImagesLoader
Something like:
private class PostTask extends AsyncTask<String, Integer, String> {
public interface onLoadFinishedListener {
public void onLoadFinished(JSONObject response)
}
protected JSONObject onPostExecute(JSONObject response){
onLoadFinished(response);
}
}
And in your Activity:
public myActivity extends Activity implements PostTask.onLoadFinishedListener {
#Override
onLoadFinished(JSONObject response){
Picasso.with(this).load(response.getString("url")).into(imageView);
}
}
Something like this would help :)
I currently have multiple activity that needs to perform an asynctask for http post and I wish to make the asynctask as another class file so that the different activity can call the asynctask to perform the http post request and onPostExecute, call the method httpResult(result) in the activity that called the asynctask. I have tried to pass the activity in but I am unable to call the method in onPostExecute. How can I do that?
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_MyActivity);
//logic here...
AsyncHttpPost asyncHttpPost = new AsyncHttpPost("someContent", this, dialog);
JSONObject data = new JSONObject();
data.put("key", "value");
try {
asyncHttpPost.execute(data);
}
catch (Exception ex){
ex.printStackTrace();
}
}
public static void httpResult(String result) {
//this method has to get called by asynctask to make changes to the UI
}
}
AsyncHttpPost.java
public class AsyncHttpPost extends AsyncTask<JSONObject, String, String> {
String recvdjson;
String mData="";
private ProgressDialog dialog;
private Activity activity;
public AsyncHttpPost(String data, Activity activity, ProgressDialog dialog) {
mData = data;
this.activity = activity;
this.dialog = dialog;
}
protected void onPreExecute()
{
dialog.show();
}
#Override
protected String doInBackground(JSONObject... params) {
//logic to do http request
return "someStringResult";
}
protected void onPostExecute(String result) {
dialog.dismiss();
activity.httpResult(result); //This line gives me error : The method httpResult(String) is undefined for the type Activity
}
}
Create an Interface called HttpResponseImpl in a seperate file and add the required method httpResult
interface HttpResponseImpl{
public void httpResult(String result);
}
Now implement this interface by you Activity class
public class MyActivity extends Activity implements HttpResponseImpl{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_MyActivity);
//logic here...
AsyncHttpPost asyncHttpPost = new AsyncHttpPost("someContent", this, dialog);
JSONObject data = new JSONObject();
data.put("key", "value");
try {
asyncHttpPost.execute(data);
}
catch (Exception ex){
ex.printStackTrace();
}
}
public void httpResult(String result){
//this method has to get called by asynctask to make changes to the UI
}
}
And your AsyncHttpPost class would be.
public class AsyncHttpPost extends AsyncTask<JSONObject, String, String> {
String recvdjson;
String mData="";
private ProgressDialog dialog;
private HttpResponseImpl httpResponseImpl;
public AsyncHttpPost(String data, HttpResponseImpl httpResponseImpl, ProgressDialog dialog) {
mData = data;
this.httpResponseImpl = httpResponseImpl;
this.dialog = dialog;
}
protected void onPreExecute()
{
dialog.show();
}
#Override
protected String doInBackground(JSONObject... params) {
//logic to do http request
return "someStringResult";
}
protected void onPostExecute(String result) {
dialog.dismiss();
httpResponseImpl.httpResult(result);
}
}
Implements this HttpResponseImpl interface with all you Activity class from which you want to do HttpRequest.
Generic AsyncTask Example
Call it like
new RetrieveFeedTask(new OnTaskFinished()
{
#Override
public void onFeedRetrieved(String feeds)
{
//do whatever you want to do with the feeds
}
}).execute("http://enterurlhere.com");
RetrieveFeedTask.class
class RetrieveFeedTask extends AsyncTask<String, Void, String>
{
String HTML_response= "";
OnTaskFinished onOurTaskFinished;
public RetrieveFeedTask(OnTaskFinished onTaskFinished)
{
onOurTaskFinished = onTaskFinished;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls)
{
try
{
URL url = new URL(urls[0]); // enter your url here which to download
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null)
{
// System.out.println(inputLine);
HTML_response += inputLine;
}
br.close();
System.out.println("Done");
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return HTML_response;
}
#Override
protected void onPostExecute(String feed)
{
onOurTaskFinished.onFeedRetrieved(feed);
}
}
OnTaskFinished.java
public interface OnTaskFinished
{
public void onFeedRetrieved(String feeds);
}