AsyncTask - onPostExecute is not called - android

I'm working on one project and I need to call one AsyncTask, but the onPostExecute method is not called.
This is my class:
public class WebService extends AsyncTask<String, String, String> {
private ArrayList<SimpleObserver> listeners;
private int responseCode;
private String message;
private String response;
private String URL;
public WebService() {
listeners = new ArrayList<SimpleObserver>();
}
public void addListener(SimpleObserver obs) {
listeners.add(obs);
}
public void removeListener(SimpleObserver obs) {
listeners.remove(obs);
}
public void notifyListener(String s) {
for (SimpleObserver listener : listeners)
listener.onChange(s);
}
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
#Override
protected void onPreExecute() {
//notifyListener("A calcular");
}
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
HttpParams my_httpParams = new BasicHttpParams();
final String proxyHost = android.net.Proxy.getDefaultHost();
final int proxyPort = android.net.Proxy.getDefaultPort();
if(proxyPort != -1)
{
my_httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort));
}
DefaultHttpClient client = new DefaultHttpClient(my_httpParams);
HttpGet httpGet = new HttpGet(url);
Log.d("URL serviço HttpGet", url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
Log.d("RESPOSTA do web service", response);
} catch (Exception e) {
e.printStackTrace();
response = e.getMessage();
Log.e("ERRO de respota", e.getMessage());
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
Log.d("onPostExecute Serviço", result);
notifyListener(result);
}
}
I have created this method:
public void executeService(String param) {
try {
Log.d("Entrar", "no serviço");
s.execute(new String [] {URL+param});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Erro ao aceder ao web service", e.getMessage());
}
}
to call the task.
these are the results of Log
08-28 17:47:21.936: D/URL serviço HttpGet(2055): http://192.168.56.1:8080/pt.Agile21.Acerola.WebService/rest/acerola?id=g;ana#eu.com
08-28 17:47:22.456: D/RESPOSTA do web service(2055): ana;ana#eu.com;pass;0
08-28 17:47:22.456: D/RESPOSTA do web service(2055): ana;ana#eu.com;pass;0
As you can see I have all the results of doInBackground(). :S
Someone can help me to understand which is the problem?
Something that I saw now looking for the Log files.. my onPostExeute method returns when I finish my app on purpose.. it is not normal.. :S can someone help me?

Related

Return JSON String from AsyncTask Android

Normally I create classes for every web service call that extends with the AsyncTask and it's so hard to maintain the code. So I think to create the One class and get the OUTPUT Json string according to the parameters.
how do I return the JSON string?
UPDATE
Here what I tried
public class WebCallController extends AsyncTask<Void,Void,String>
{
String PassPeram = "";
JSONStringer JSonRequestString;
String URL;
String JSonResponseString;
public WebCallController(String PerameterPass, JSONStringer JSonRequestString, String URL) {
PassPeram = PerameterPass;
this.JSonRequestString = JSonRequestString;
this.URL = URL;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
post.setHeader("Content-type", "application/json");
try {
StringEntity entity = new StringEntity(JSonRequestString.toString());
post.setEntity(entity);
}
catch (Exception Ex)
{
}
try {
HttpResponse response = client.execute(post);
StatusLine status = response.getStatusLine();
int statusCode = status.getStatusCode();
if(statusCode == 400)
{
Log.d("Error", "bad request");
}
else if(statusCode == 505)
{
Log.d("Error","Internal server error");
}
else
{
InputStream jsonStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(jsonStream));
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine()) != null)
{
builder.append(line);
}
JSonResponseString = builder.toString();
}
}
catch (IOException Ex)
{
}
return JSonResponseString;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
}
}
this may be what you are looking for(get string as result and parse it to json):
YourAsycTask yat=new YourAsycTask();
yat.execute();
String result=yat.get().toString();
I am assuming that you need to write one AsyncTask which can be reusable for every webservice call. You can do something like below example ,
Step-1: Create a abstract class
public abstract class HttpHandler {
public abstract HttpUriRequest getHttpRequestMethod();
public abstract void onResponse(String result);
public void execute(){
new AsyncHttpTask(this).execute();
}
}
2. Sterp-2: Write your AsyncTask code
public class AsyncHttpTask extends AsyncTask<String, Void, String>{
private HttpHandler httpHandler;
public AsyncHttpTask(HttpHandler httpHandler){
this.httpHandler = httpHandler;
}
#Override
protected String doInBackground(String... arg0) {
//do your task and return the result
String result = "";
return result;
}
#Override
protected void onPostExecute(String result) {
httpHandler.onResponse(result); // set it to the onResponse()
}
}
Step-3: Write your Activity code
public class MainActivity extends Activity implements OnClickListener {
private Button btnRequest;
private EditText etResponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnRequest = (Button) findViewById(R.id.btnRequest);
etResponse = (EditText) findViewById(R.id.etRespose);
//check isConnected()...code is on github
btnRequest.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new HttpHandler() {
#Override
public HttpUriRequest getHttpRequestMethod() {
return new HttpGet("http://hmkcode.com/examples/index.php");
// return new HttpPost(url)
}
#Override
public void onResponse(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
etResponse.setText(result);
}
}.execute();
}
// public boolean isConnected(){}
}
reference
http://hmkcode.com/android-cleaner-http-asynctask/
https://github.com/hmkcode/Android/tree/master/android-clean-http-async-task
Try out below code and put it in separate class from where it returns json string to your activity.
Only pass your url to this method and get the response in a string formate.
public static final String GetConnectionInputStream(String strUrl) {
String line = null;
String response = null;
try {
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is
// established.
// The default value is zero, that means the timeout is not used.
HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(httpParameters, 30000);
// This is the default apacheconnection.
HttpClient mHttpClient = new DefaultHttpClient(httpParameters);
// Pathe of serverside
HttpGet mHttpGet = new HttpGet(strUrl);
// get the valu from the saerverside as response.
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
HttpEntity mHttpEntity = mHttpResponse.getEntity();
try {
// convert response in to the string.
if (mHttpEntity.getContent() != null) {
BufferedReader mBufferedReader = new BufferedReader(
new InputStreamReader(mHttpEntity.getContent(),
HTTP.UTF_8), 8);
StringBuilder mStringBuilder = new StringBuilder();
while ((line = mBufferedReader.readLine()) != null) {
mStringBuilder.append(line + "\n");
}
response = mStringBuilder.toString();
// mInputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return response;
}
Change your doInBackground method as below:
private class GetParsedResponse extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... params) {
String response=null;
response=GetConnectionInputStream(URL);
return response;
}
#Override
protected void onPostExecute(String result) {
//your response parsing code.
}
}
private class MyAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return "Executed";
}
#Override
protected String onPostExecute(String result) {
return "json String";
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}

JSON POST request for download image from server in android

I need to download image and set it in to imageview . for parsing i use JSON POST request and for this i use base64 . I got base64 type data for the image tag in to log but the problem is that how t separate the value of that image and convert it in to string and then display it in to list view ??is there any alternative way without using base64 to display image then please suggest us.
For parsing of data i use JSON parser with HttpPost .
Now how to get the value of image from response JSON format that i display above that the confusion ??
Thanks in advance ..
You can do like this.
Create folder in server. put images in that folder. get the URL of the image and insert in to db.
then get the JSON value of that url
add this method and pass that url to this method.
Bitmap bitmap;
void loadImage(String image_location) {
URL imageURL = null;
try {
imageURL = new URL(image_location);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection = (HttpURLConnection) imageURL
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);// Convert to
// bitmap
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
Try below code:
JSONObject res = jsonObj.getJSONObject("root");
JSONObject data = jsonObj.getJSONObject("data");
JSONArray imgs= jsonObj.getJSONArray ("images");
for(int i=0;i<imgs.length();i++){
JSONObject Ldetails = Ldtls.getJSONObject(i);
String img= Ldetails.getString("image");
byte[] decodedString = Base64.decode(img,Base64.NO_WRAP);
InputStream inputStream = new ByteArrayInputStream(decodedString);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imagevw.setImageBitmap(bitmap);
}
where imagevw is your ImageView.
Use a Gson Parser and then parse the base64 image string to a byte array and apply on the image.
Your model classes will be as follows:
public class JsonWrapper
{
private Root root ;
public Root getroot()
{
return this.root;
}
public void setroot(Root root)
{
this.root = root;
}
}
public class Root
{
private Response response ;
public Response getresponse()
{
return this.response;
}
public void setresponse(Response response)
{
this.response = response;
}
}
public class Response
{
private Message message ;
public Message getmessage()
{
return this.message;
}
public void setmessage(Message message)
{
this.message = message;
}
private Data data ;
public Data getdata()
{
return this.data;
}
public void setdata(Data data)
{
this.data = data;
}
}
public class Message
{
private String type ;
public String gettype()
{
return this.type;
}
public void settype(String type)
{
this.type = type;
}
private String message ;
public String getmessage()
{
return this.message;
}
public void setmessage(String message)
{
this.message = message;
}
}
import java.util.ArrayList;
public class Data
{
private ArrayList<Image> images ;
public ArrayList<Image> getimages()
{
return this.images;
}
public void setimages(ArrayList<Image> images)
{
this.images = images;
}
private String last_synchronized_date ;
public String getlast_synchronized_date()
{
return this.last_synchronized_date;
}
public void setlast_synchronized_date(String last_synchronized_date)
{
this.last_synchronized_date = last_synchronized_date;
}
}
public class Image
{
private String web_id ;
public String getweb_id()
{
return this.web_id;
}
public void setweb_id(String web_id)
{
this.web_id = web_id;
}
private String blob_image ;
public String getblob_image()
{
return this.blob_image;
}
public void setblob_image(String blob_image)
{
this.blob_image = blob_image;
}
}
Once you have the json parse using Gson as follows:
JsonWrapper jsonWrapper = new JsonWrapper();
Gson gsonParser = new Gson();
jsonWrapper = gsonParser.fromJson(data, jsonWrapper.getClass());
Next you can iterate through all the images
ArrayList<Image> images = jsoinWrapper.getRoot().getResponse().getData().getImages();
for(Image image : images)
{
byte[] decodedString = Base64.decode(image.getblob_image(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
if (decodedString != null) {
imageViewtype.setImageBitmap(decodedByte);
}
}
public class SingleContactActivity extends Activity implements OnClickListener {
private static final String TAG_ImageList = "CatList";
private static final String TAG_ImageID = "ID";
private static final String TAG_ImageUrl = "Name";
private static String url_MultiImage;
TextView uid, pid;
JSONArray contacts = null;
private ProgressDialog pDialog;
String details;
// String imagepath = "http://test2.sonasys.net/Content/WallPost/b3.jpg";
String imagepath = "";
String imagepath2;
Bitmap bitmap;
ImageView image;
SessionManager session;
TextView myprofileId;
TextView pending;
TextView Categories, visibleTo;
int count = 0;
ImageButton btn;
// -----------------------
ArrayList<HashMap<String, String>> ImageList;
JSONArray JsonArray = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
url_MultiImage = "http://test2.sonasys.net/Android/GetpostImg?UserID=1&PostId=80";
new MultiImagePath().execute();
ImageList = new ArrayList<HashMap<String, String>>();
}
private class MultiImagePath extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url_MultiImage,
ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JsonArray = jsonObj.getJSONArray(TAG_ImageList);
if (JsonArray.length() != 0) {
for (int i = 0; i < JsonArray.length(); i++) {
JSONObject c = JsonArray.getJSONObject(i);
String Img_ID = c.getString(TAG_ImageID);
String Img_Url = c.getString(TAG_ImageUrl);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ImageID, Img_ID);
contact.put(TAG_ImageUrl, Img_Url);
// adding contact to contact list
ImageList.add(contact);
}
}
Log.e("JsonLength", "length is ZERO");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
AutoGenImgBtn();
}
}
#SuppressWarnings("deprecation")
public void AutoGenImgBtn() {
int count = ImageList.size();
LinearLayout llimage = (LinearLayout) findViewById(R.id.llimage);
ImageButton[] btn = new ImageButton[count];
for (int i = 0; i < count; i++) {
btn[i] = new ImageButton(this);
btn[i].setId(Integer.parseInt(ImageList.get(i).get(TAG_ImageID)));
btn[i].setOnClickListener(this);
btn[i].setTag("" + ImageList.get(i).get(TAG_ImageUrl));
btn[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
btn[i].setImageDrawable(getResources().getDrawable(drawable.di1));
btn[i].setAdjustViewBounds(true);
// btn[i].setTextColor(getResources().getColor(color.white));
llimage.addView(btn[i]);
}
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
btn = (ImageButton) v;
String s = btn.getTag().toString();
new ImageDownloader().execute(s);
}
private class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... param) {
// TODO Auto-generated method stub
return downloadBitmap(param[0]);
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
pDialog = new ProgressDialog(SingleContactActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.setTitle("In progress...");
// pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setIcon(android.R.drawable.stat_sys_download);
pDialog.setMax(100);
// pDialog.setTitle("Post Details");
pDialog.show();
}
#Override
protected void onPostExecute(Bitmap result) {
Log.i("Async-Example", "onPostExecute Called");
if (bitmap != null) {
btn.setImageBitmap(bitmap);
}
if (pDialog.isShowing())
pDialog.dismiss();
}
private Bitmap downloadBitmap(String url) {
// initilize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();
// forming a HttoGet request
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
// check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode
+ " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that
// android understands
bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for
// IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while"
+ " retrieving bitmap from " + url + e.toString());
}
return null;
}
}
# Add Service Handler Class#
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
*
* */
public String makeServiceCall(String url, int method,List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}

AsyncTask read and return data from URL

I've been having a lot of problems making this code work.
My main activity uses ZXing to scan a barcode, and then I want to take the result of that scan and query my API with it. I know I have to use an AsyncTask to do this, but I've never used one before and I'm having a lot of trouble with it. My goal is to query the API within the AsyncTask, and then update my upcTxt TextView element with the resulting JSON String. What am I supposed to do next in my ReadJSON code?
Here's my main activity code:
public class Barcode extends Activity implements OnClickListener {
private Button scanBtn;
private TextView formatTxt, contentTxt, upcTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode);
scanBtn = (Button)findViewById(R.id.scan_button);
formatTxt = (TextView)findViewById(R.id.scan_format);
contentTxt = (TextView)findViewById(R.id.scan_content);
upcTxt = (TextView)findViewById(R.id.upc);
scanBtn.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.barcode, menu);
return true;
}
public void onClick(View v){
//respond to clicks
if(v.getId()==R.id.scan_button){
//scan
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanResult = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanResult);
new ReadJSON().execute(new String[] {scanResult});
} else {
Toast toast = Toast.makeText(getApplicationContext(), "No scan data received!", Toast.LENGTH_LONG);
toast.show();
}
}}
And here is my ReadJSON code:
public class ReadJSON extends AsyncTask<String, Void, Void> {
private String content;
private TextView upcTxt;
private String url;
#Override
protected Void doInBackground(String... scanResult) {
url = "REDACTED";
content = "";
HttpClient Client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url + scanResult[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
content = Client.execute(httpget, responseHandler);
// Update upcTxt here
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Thank you in advance.
Update: Whenever I try to run the code on my phone, I can scan the barcode just fine but then the program crashes once it tries to access the URL.
LogCat:
01-18 17:26:44.731: E/AndroidRuntime(24876): at com.peter.barcodetest.ReadJSON.doInBackground(ReadJSON.java:30)
01-18 17:26:44.731: E/AndroidRuntime(24876): at com.peter.barcodetest.ReadJSON.doInBackground(ReadJSON.java:1)
01-18 17:26:46.473: D/CrashAnrDetector(376): processName: com.peter.barcodetest
01-18 17:26:46.473: D/CrashAnrDetector(376): broadcastEvent : com.peter.barcodetest data_app_crash
01-18 17:26:46.913: D/PackageBroadcastService(26662): Received broadcast action=android.intent.action.PACKAGE_REPLACED and uri=com.peter.barcodetest
01-18 17:26:55.122: I/ActivityManager(376): Process com.peter.barcodetest (pid 24876) (adj 13) has died.
I changed your code to this:
Edited ReadJSON only
AsyncTask (edited)
public class ReadJSON extends AsyncTask<String, Integer, String> {
private String content;
private TextView upcTxt;
private String url;
private static final String TAG = "ReadJSON";
String s = "";
Context context;
ReadJSONCallBack callback;
public ReadJSONTask (Context context, ReadJSONCallBack cb) {
super();
this.callback = cb;
this.context = context;
}
#Override
protected String doInBackground(String... scanResult) {
url = "REDACTED";
HttpClient Client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url + scanResult[0]);
try {
HttpResponse response = Client.execute(httpget);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream in = response.getEntity().getContent();
Log.d(TAG, "Got response");
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
Log.d(TAG, "Content: " + stringBuilder.toString());
return stringBuilder.toString();
// Update upcTxt here
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
protected void onPostExecute(String result) {
callback.setString(s);
}
// method for parsing JSON object
public String parseJSONObject(String output) {
try {
JSONArray jArray = new JSONArray(output);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String id = jObject.getString("id");
String customer = jObject.getString("name");
String description = jObject.getString("description");
Long time = (Long) jObject.get("timeAsDate");
// do something
}
} catch (JSONException e) {
}
return description;
}
}

Rest with Android 4.0

Folks, I have an web service running on my PC, recently I changed my application from 2.2. for 4.0, and after that I cant connect to my WS anymore.
I'm looking for answers and found nothing.
My application refers the URL like thishttp://10.0.2.2:8080 ... But it dosn't work.
Heres my code:
private static final String URL_WS = "http://10.0.2.2:8080/WS_TaxiShare/)";
public String login(String email, String password) throws Exception {
String[] resposta = new WSClient().get(URL_WS + "login/login/?login="+ email +"&password="+ password);
String saida = resposta[1];
if (resposta[0].equals("200")) {
return saida;
} else {
return saida;
}
}
Now the WSClient
public class WSClient {
public final String[] get(String url) {
String[] result = new String[2];
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
Log.i("Get taxi", "Url -> " + url);
response = HttpClientSingleton.getHttpClientInstace().execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
result[0] = String.valueOf(response.getStatusLine().getStatusCode());
InputStream instream = entity.getContent();
result[1] = toString(instream);
instream.close();
Log.i("get", "Result from post JsonPost : " + result[0] + " : " + result[1]);
}
} catch (Exception e) {
Log.i("Exception no get WS taxi", "Exception ->" + e);
result[0] = "0";
result[1] = "Falha de rede!";
}
return result;
}
Well, i can solve my problem. Android 4.0 (I dont know when it begin), you cant call webservices on the main thread. And all you need to do is create a async method to do what you need in a separeated thread.
Here is my method
private class loginTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
try {
WSTaxiShare ws = new WSTaxiShare();
response = ws.login(login, password);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String strJson) {
}
and here is the call button
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
loginTask task = new loginTask();
task.execute(new String[] { "" });
}
});
}

Getting results from several AsyncTasks

Hi and thanks for your help.
I have a method that calls an AsyncTask to retrieve some data from the net.
The method is called several times in sequence and therefore launches several AsyncTasks.
From each launch of the method I need to get back the correct result from the relative AsyncTask (and not from some other AsyncTask which was called before or after).
Any help very much appreciated.
EDIT EDIT EDIT EDIT
Added rest of code.
Please Note: the whole process runs inside a Service.
public static class UpdateService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int[] appWidgetIds = intent.getIntArrayExtra("widgetsids");
final int N = appWidgetIds.length;
AppWidgetManager manager = AppWidgetManager.getInstance(this);
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
Log.e("","i="+Integer.toString(i)+ " di "+Integer.toString(N));
RemoteViews view = buildUpdate(getApplicationContext(),
appWidgetIds);
manager.updateAppWidget(appWidgetId, view);
}
return (START_NOT_STICKY);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
private static RemoteViews buildUpdate(Context ctxt, int[] appWidgetIds) {
RemoteViews updateViews = new RemoteViews(ctxt.getPackageName(),
R.layout.widget);
updateViews.setTextViewText(R.id.price1, getPrice(list.get(0)
.getSymbol()));
}
//THIS METHOD IS CALLED SEVERAL TIMES IN SEQUENCE <----
private static String getPrice(String symbol) {
String result="";
UpdateTaskPrice up = new UpdateTaskPrice();
up.execute(symbol, null, null);
//HERE I WANT THE RESULT FROM onPostExecute() <----
return result;
}
//THIS IS THE ASYNCTASK WHICH IS LAUNCHED SEVERAL TIMES
public class UpdateTaskPrice extends AsyncTask<String, Void, String> {
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected void onPostExecute(String result) {
//HERE I RECEIVE THE RESULT FROM doInBackground <----
//I NEED TO PASS IT BACK TO getPrice() <----
}
#Override
protected String doInBackground(String... symbol) {
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
String srt = "";
String url = context.getString(R.string.urlaternativo).concat(
symbol[0]);
HttpGet getMethod = new HttpGet(url);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
srt = client.execute(getMethod, responseHandler);
int inizio = srt.indexOf("<last data=\"");
int fine = srt.indexOf("\"/>", inizio + 12);
result = srt.substring(inizio + 12, fine);
} catch (Throwable t) {
// Log.e("ERROR", "ERROR", t);
}
//HERE I GET THE RESULT I WANT, AND PASS IT TO onPostExecute() <----
return result;
}
}
AsyncTask is asynchronous and run in a separate thread. So it is not possible to get the result of AsyncTask in very next statement after you execute it.
To get the relative results from AsyncTask, add a member variable "mRequestId" in your UpdateTaskPrice class and before calling UpdateTaskPrice.execute, set unique request ID.
in "onPostExecute" method of your UpdateTaskPrice class, you can return and process result using this Request Id.
public class UpdateTaskPrice extends AsyncTask<String, Void, String> {
protected int mRequestId;
public void setRequestId (int requestId)
{
this.mRequestId = requestId;
}
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected void onPostExecute(String result) {
// do whatever with result using mRequestId
}
#Override
protected String doInBackground(String... symbol) {
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
String srt = "";
String url = context.getString(R.string.urlaternativo).concat(
symbol[0]);
HttpGet getMethod = new HttpGet(url);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
srt = client.execute(getMethod, responseHandler);
int inizio = srt.indexOf("<last data=\"");
int fine = srt.indexOf("\"/>", inizio + 12);
result = srt.substring(inizio + 12, fine);
} catch (Throwable t) {
// Log.e("ERROR", "ERROR", t);
}
//HERE I GET THE RESULT I WANT, AND PASS IT TO onPostExecute() <----
return result;
}
}
You can get the data from multiple asynctask, but the place you want the result is not possible
with the asyctask, you need to use more encapsulation to structure this problem.
the problem with your structure is...
private static String getPrice(String symbol) {
String result="";
UpdateTaskPrice up = new UpdateTaskPrice();
up.execute(symbol, null, null);
//HERE I WANT THE RESULT FROM onPostExecute() <----
return result;
}
when you are starting the new thread it will first execute the statement which is return after task.execute(symbol); in your case it is return statement and then it will exucute pre.. doin.. and post...
Hear is the pattern which you can use to retrieve the data from multiple AsycTask
//Calling to the method callAsyncTask;
callAsyncTask(new AsyncResultCallback(){
public void onResult(String result, String symbol){
//TODO dosomthing with the result
}
});
public void callAsyncTask(AsyncResultCallback callback){
new UpdateTaskPrice(callback).execurte(symbol);
}
public interface AsyncResultCallback{
public void onResult(String result, String symbol);
}
public class UpdateTaskPrice extends AsyncTask<String, Void, String> {
AsyncResultCallback callback;
String symbol;
UpdateTaskPrice(AsyncResultCallback callback){
this.callback = callback;
}
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected void onPostExecute(String result) {
callback.onResult(result, symbol);
}
#Override
protected String doInBackground(String... symbol) {
this.symbol = symbol;
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
String srt = "";
String url = context.getString(R.string.urlaternativo).concat(symbol[0]);
HttpGet getMethod = new HttpGet(url);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
srt = client.execute(getMethod, responseHandler);
int inizio = srt.indexOf("<last data=\"");
int fine = srt.indexOf("\"/>", inizio + 12);
result = srt.substring(inizio + 12, fine);
} catch (Throwable t) {
// Log.e("ERROR", "ERROR", t);
}
//HERE I GET THE RESULT I WANT, AND PASS IT TO onPostExecute() <----
return result;
}
}
hope that help.
Well, I think you can pass the unique request id in the constructor of the AsyncTask. Then in the postExecute() method, update the UI with the result and the unique request id -
public class UpdateTaskPrice extends AsyncTask<String, Void, String> {
private int mIdentifier;
private Service mService;
public UpdateTaskPrice(Service service, int identifier) {
this.mIdentifier = identifier;
}
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected void onPostExecute(String result) {
((UpdateService) mService).informPrice(mIdentifier, result);
}
#Override
protected String doInBackground(String... symbol) {
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
String srt = "";
String url = context.getString(R.string.urlaternativo).concat(
symbol[0]);
HttpGet getMethod = new HttpGet(url);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
srt = client.execute(getMethod, responseHandler);
int inizio = srt.indexOf("<last data=\"");
int fine = srt.indexOf("\"/>", inizio + 12);
result = srt.substring(inizio + 12, fine);
} catch (Throwable t) {
// Log.e("ERROR", "ERROR", t);
}
//HERE I GET THE RESULT I WANT, AND PASS IT TO onPostExecute() <----
return result;
}
}

Categories

Resources