I want to use the response from httppost method in onpostexecute? - android

I am using httppost method in doinbackground and I am also getting the the response. Now when I pass the data to webservice I get a Jsonobject which I have to parse. and that jsonobject is stored in responsebody below. I have putted the return statement as "res". but in onpost execute I get a nullpointer exception.
I want to use the String responseBody in onpostexecute method?
class Thread extends AsyncTask<String, Void , String>{
private String responseBody;
private String res;
#Override
protected String doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpResponse response;
JSONObject json=new JSONObject();
HttpPost post = new HttpPost(url1);
try {
json.put("URL",getqrcode());
json.put("EmailID", getuseremail());
StringEntity stringEntity = new StringEntity(json.toString());
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
post.setEntity(stringEntity);
response = client.execute(post);
Log.e("RESPONSE", response.toString());
String responseBody = EntityUtils
.toString(response.getEntity());
String res= responseBody.toString();
Log.e("RESPONSE BODY", responseBody);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return res;
}
#Override
protected void onPostExecute(String res) {
Log.e("response is", res);
// TODO Auto-generated method stub
super.onPostExecute(res);
}

Make a Global variable of response
String res;
and use in onpostExecute() method:
and just replace
String res= responseBody.toString();
with
res= responseBody.toString();
only

Your global res is masking the local res defined in the try block.
Since the res variable you populate is local to the scope of the try block, it cannot be seen outside, and your compiler doesn't complain because of the global res.
You can simply affect the res member without re-declaring it:
res = responseBody;
Technically, it is not useful to declare the res variable globally, you can simply declare it in the method, but in the same scope as the return, that is, outside the try block (before it).
(also, the toString is not useful, as it will only return itself in the case of a String)
(the same goes for responseBody, the local scope hide the global scope. In this case, the global scope is useless)

Just insert this statement in the end of your doInBackground method :
return res;
This will return response to onPostExecute(String oString) wrap-up in oString

Related

Android NetworkOnMainThreadException inside Asyntask class

This code shows the exception when it reach the get sentence (line commented on the code).
The code is the next, consist on get a comments list from Http get Request:
public class ObtencionComentariosPerfil extends AsyncTask<String, Integer, List<Comment>>{
#Override
protected List<Comment> doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
URI url;
List<Comment> listaComentarios = new ArrayList<Comment>();
try {
url = new URI(params[1]);
HttpGet del = new HttpGet(url);
del.setHeader("content-type", "application/json");
del.setHeader("X-Auth-Token", params[0]);
System.out.println("El token params es: "+params[0]);
HttpResponse resp = httpClient.execute(del);// THE EXCEPTION shows here
StatusLine estatus = resp.getStatusLine();
if (estatus.getStatusCode() == 200) {
InputStream is = resp.getEntity().getContent();
CommentsParser parser= new CommentsParser();
listaComentarios = parser.parseoComentarios(is.toString());
} else {
System.out.println("Error");
listaComentarios = null;
}
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listaComentarios;
}
#Override
protected void onPostExecute(List<Comment> lista){
}
}
Here is called from main code:
public List<Comment> obtieneComentariosPerfil(long idUsuario, String aut){
List<Comment> listaComentarios = new ArrayList<Comment>();
String url= "http://"+ip+":8080/api/users/"+idUsuario+"/comments";
String[] params= new String[2];
params[0]=aut;
params[1]=url;
ObtencionComentariosPerfil du = new ObtencionComentariosPerfil();
listaComentarios = du.doInBackground(params);
return listaComentarios;
}
I think it have to be a stupid failure but i cant find the error. Thanks.
Because you call du.doInBackground(params);
you should call du.excute(params) instead
listaComentarios = du.doInBackground(params);
You submit async tasks for execution in a background thread by calling execute(), not by directly calling the doInBackground() callback in the current thread.
Communicate the result back to UI thread in onPostExecute().

Send JSON data from a service to UI in Android

The requirement is : I have a background service and in that service I am doing a REST call to get a JSON data. I want to send the JSON data to UI and update contents.
One method I can use i.e. store the entire JSON string in SharedPreferences and retrieve in UI but I don't think that's efficient.
Any idea guys ? I have added a Handler in UI to update elements but I am not that familiar in using it.
Sample REST call code :
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(DATA_URL);
httpPost.setHeader("Content-Type", "application/json");
//passes the results to a string builder/entity
StringEntity se = null;
try {
se = new StringEntity(RequestJSON.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//sets the post request as the resulting string
httpPost.setEntity(se);
//Handles what is returned from the page
ResponseHandler responseHandler = new BasicResponseHandler();
try {
HttpResponse response = (HttpResponse) httpClient.execute(httpPost, responseHandler);
// response will have JSON data that I need to update in UI
//Show notification
showNotification("Update Complete");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// httpClient = null;
}
On UI activity
Handler myHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
Bundle Recevied = msg.getData();
String resp = Recevied.getString("Mkey");
}
};
messenger = new Messenger(myHandler);
}
pass the messanger to service and once result ready:
Message msg = Message.obtain();
Bundle data = new Bundle();
data.putString("Mkey",
Smsg);
msg.setData(data);
try {
// Send the Message back to the client Activity.
messenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
Something like that may be suitable for you. TL;DR: Create a listener in the service that updates the activity.
In the service, make a static function and a static field:
private static BlaBlaService _instance;
public static BlaBlaService getInstance() {
return _instance;
}
Populate the _instance field on the onCreate function:
public void onCreate() {
super.onCreate();
_instance = this;
...
}
public void addRESTCompleteListener(RESTCompleteListener l) {...}
Once a REST call is complete call:
listener.RESTCompleted(JSON.whatever)
Now in your activity, simply add the listener to the service once it starts:
BlaBlaService.getInstance().addRESTCompleteListener(listener)
Don't forget to dispose all the pointers when needed.
Hope this helps :)

Taking Values from JSON

I am new in android.I need to take values from web service.Here i used json parsing.The out put Json format is { "flag": 0 }. Here i need to take the value of flag and using that value i want to start another method. How do i take the value of flag. please help me. I used in this way.
public String objectvalue(String result){
try {
JSONObject obj=new JSONObject(result);
String flag=obj.getString("flag");
mString=flag;
System.out.println(mString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mString;
}
But i didnot get the value of flag.Here argument result is output from the server.ie,result={ "flag": 0 }
First of all, where is the declaration of mString variable? I assume it is declared as instance variable in your java class having this method, if not please check.
You have a well formed JSON in the form of
{ "flag": 0 }
so converting it to a JSONObject should work perfectly.
For extracting value of flag key
There is key named flag in this JSONObject which has an Integer value and you are trying to extract it using getString() method.
You should be using either of the following methods calls
optInt(String key)
Get an optional int value associated with a key, or zero if there is no such key or if th value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.
int flag = optInt("flag");
OR
optInt(String key, int defaultValue)
Get an optional int value associated with a key, or the default if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.
int flag = optInt("flag", 0);
Your code with changes
public int objectValue(String result){
int flag = 0;
try {
JSONObject obj=new JSONObject(result);
flag = obj.optInt("flag");
} catch (JSONException e) {
e.printStackTrace();
}
return flag;
}
Edit: Answer to question in comment.
public String objectValue(String result){
int flag = 0;
try {
JSONObject obj=new JSONObject(result);
flag = obj.optInt("flag");
} catch (JSONException e) {
e.printStackTrace();
}
return String.valueOf(flag);
}
Hope this helps.
You may try using AsyncTask for your concern. It's best and preffered way to fetch JSON data
Define AsyncTask like this ..
new BussinessOwnerHttpAsyncTask().execute();
and your AsyncTask class ..
class BussinessOwnerHttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// Progress dialog code goes over here ..
pDialog = new ProgressDialog(getParent());
pDialog.setMessage("Please wait ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// Maintaining Shared preferences class for further...
HttpClient httpclient = new DefaultHttpClient();
String myUrl = Your_url_goes_over_here;
String encodedURL = "";
try {
encodedURL = URLEncoder.encode(myUrl, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
URL url = new URL(encodedURL);
Log.d("asca", ""+url);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.i("url", city_name + "~" + country_name);
Log.d("location", request_url+encodedURL);
HttpGet httpget = new HttpGet(request_url+encodedURL);
try {
httpresponse = httpclient.execute(httpget);
System.out.println("httpresponse" + httpresponse);
Log.i("response", "Response" + httpresponse);
InputStream is = httpresponse.getEntity().getContent();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String recievingDataFromServer = null;
while ((recievingDataFromServer = br.readLine()) != null) {
Log.i("CHECK WHILE", "CHECK WHILE");
sb.append(recievingDataFromServer);
}
myJsonString = sb.toString();
Log.d("manish", myJsonString);
serverSearchData = sb.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pDialog.dismiss();
if (myJsonString.length() > 0) {
try {
myJsonObject = new JSONObject(myJsonString);
String your_flag = myJsonObject.getString("flag");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Now you are good to go with your queries..
{ // JSONObject
"flag": 0
}
Use
JSONObject obj=new JSONObject(result);
int flag=obj.getInt("flag");
http://developer.android.com/reference/org/json/JSONObject.html
public int getInt (String name)
Added in API level 1
Returns the value mapped by name if it exists and is an int or can be coerced to an int.
Throws
JSONException if the mapping doesn't exist or cannot be coerced to an int.
If this does not work you need to post more info.
the "flag" values format at interger, not string, this is simple code to do that :
int flagValues = jsonObject.getInt("flag");
Log.w("values ",String.valuesOf(flagValues));

Android- Not getting full response from HttpResponse

I am trying to get an HttpResponse in xml but Im not getting the whole response, what is courious is that if I loop the request the response ends in different parts but is never full.
I use the same code to request things from different Urls but I only get problems with one.
Here is the code of the AsyncTask:
public class NetworkTask extends AsyncTask<String, Void, HttpResponse> {
private AsyncTaskListener listener;
#Override
protected HttpResponse doInBackground(String... params) {
String link = params[0];
HttpGet request = new HttpGet(link);
AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
try {
HttpResponse httpResponse = client.execute(request).;
return httpResponse;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
client.close();
}
}
#Override
protected void onPostExecute(HttpResponse result) {
if (result != null){
try {
String sRes = EntityUtils.toString(result.getEntity());
listener.onNTCompleted(sRes);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public NetworkTask(AsyncTaskListener listener){
this.listener=listener;
}
}
I am not sure if this helps you but you have a problem because EntityUtils.toString() reads data from the network stream, which should not be done on UI thread (onPostExecute). Try moving EntityUtils.toString() to doInBackground() first. This may not help solve your problem, but it is the right thing to do.

Can't connect to wamp server from android app

I know my php file works, I can call it from localhost and I get the response.
I also know I have the correct ip address for calling it from the AVD because when I call the url from the browser in the AVD I get a response.
So the problem is in my asynctask function.
Here's my code from the asynctask class.
protected String doInBackground(String... args) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(new HttpGet(url));
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String str) {
// updating UI from Background Thread
resp=str;
returned();
}
I'm calling this class from the parent class and putting the string from onpostexecute() to string resp, which is a string in the parent class. The response is always null.
Well, you ARE returning null, so your code is working as written.
Maybe instead of return null in doInBackground(), you want to return part of the http response?

Categories

Resources