Arihant Arihant - 5 months ago 23
Android Question

Android web service not parsing data from localhost

I am trying to connect Android App to java webservice to get pHp parsed values.

Php Script is :

<?php
$data = array('name' => 'Froyo', 'version' => 'Android 2.2');
print (json_encode($data));
?>


And the Java WebService is :

package com.json.php;

import android.app.Activity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;


public class JSONExampleActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1/test.php");
TextView textView = (TextView)findViewById(R.id.textView1);
try {

HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONObject object = new JSONObject(jsonResult);

String name = object.getString("name");
String verion = object.getString("version");
textView.setText(name + " - " + verion);

}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}


}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));

try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}

catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}


I tried both
http://127.0.0.1/test.php and http://localhost/test.php
in HttpPost, It doesn't works.
I checked my php file on the browser and that gives the result fine.
Where am i Going wrong?
Also i am working on a Mac, is that anyway related to the problem because of all the permission issues?

Answer

Just take a look at this page : http://developer.android.com/tools/devices/emulator.html#networkaddresses

You'll notice that they refer to:

  • 10.0.2.2 as Special alias to your host loopback interface (i.e., 127.0.0.1 on your development machine)
  • 127.0.0.1 as The emulated device's own loopback interface

Hope I answered and solved your problem :)

Comments