Can't connect to wamp server from android app - android

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?

Related

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 :)

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.

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

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

Android: TRying to show text saying sending when HttpClient sends message to server

I have a simple program that aks questions then call a php file saying if the answer was a yes or a no.
Right now it works but there is a slight pause when the information is being send. I would like some kind message or indicator to come up showing the computer is busy.
Now when I chnage the text of a textvue, before I send the data, the textView does not change, I allso tried to call it's update methed
code
case R.id.butYes:
mSend .setText("Sending your vote to server");
mSend.invalidate();
TalkToServer( mYes[mPes-1] );
UpdateScreen();
mSend .setText("");
break;
String TalkToServer( String addr)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(addr);
HttpResponse response;
String responseBody=new String("");
try {
response = httpclient.execute(httppost);
responseBody = EntityUtils.toString(response.getEntity());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return responseBody;
}
use AsyncTask to avoid hanging of UI when sending data to server just change your code as:
case R.id.butYes:
new SendTextOperation().execute("");
break;
private class SendTextOperation extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
//Update UI here
mSend.setText("Sending your vote to server");
mSend.invalidate();
}
#Override
protected String doInBackground(String... params) {
// Talk to server here to avoid Ui hanging
TalkToServer( mYes[mPes-1] );
return null;
}
#Override
protected void onPostExecute(String result) {
// Update screen here after talk to server end
UpdateScreen();
mSend .setText("");
}
}

Trying to implement AsyncTask to make an http request

I've been trying to implement asynctask to make about 30 http requests to find the distance between two locations using a JSON object and the distance matrix api. The code I've written works when called from the main UI thread, but when I try to run it from the Async Task and save the distances to an array I just end up with an array full of null values. Any advice? (Note: This code was initially written by someone else at my work, and I've merely copy pasted it and changed a few lines to work with my app. So, there may be some unnecessary bits that I'm unaware of. Feel free to point them out)
class DistanceFinder extends AsyncTask<String[], Void, String[]>
{
#Override
protected String[] doInBackground(String[]... locations)
{
String baseURL="https://maps.googleapis.com/maps/api/distancematrix/json?origins=";
String[] distances = new String[locations[1].length];
for(int i = 1;i<locations.length;i++)
{
String url = baseURL + locations[0][0].replace(" ","+") + "&destinations=" + locations[1][i].replace(' ', '+') + "&sensor=true&units=imperial";
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = "";
boolean internet;
try
{
response = httpclient.execute(new HttpGet(url));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
internet=true;
}
else
{
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
internet=false;
Toast.makeText(getApplicationContext(), "Please connect to internet", Toast.LENGTH_LONG).show();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
internet=false;
Toast.makeText(getApplicationContext(),"Please connect to internet", Toast.LENGTH_LONG).show();
}
if(internet){
try
{
JSONObject jsonObj = new JSONObject(responseString);
JSONArray rows = jsonObj.getJSONArray("rows");
JSONObject inRows=rows.getJSONObject(0);
JSONArray elements = inRows.getJSONArray("elements");
JSONObject inElements=elements.getJSONObject(0);
JSONObject distance= inElements.getJSONObject("distance");
distances[i] = distance.getString("text");
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return distances;
}
#Override
protected void onPostExecute(String[] result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
distancesList = result;
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
}
}
Your problem is with you for loop
for(int i = 1;i<locations.length;i++)
First, you should start from 0, unless your first cell doesn't store a String you wish you check the distance to.
Second, your for loop should be
for(int i = 0;i<locations[0].length;i++)
Right now you're checking cells [1][0] and that's it, because the loop ends.
I tested it with manually entered locations and it works.
Also, just to make things easier for you to debug, You should really get used to using Log.d(). It really helps figuring out errors. I used it in your code and saw that the loop only gets executed once.
Good luck
P.s, as mentioned in one of the comments, remove the onPreExecute(). You don't use it.

Categories

Resources