Android connection to localhost

AlexDG picture AlexDG · Feb 16, 2014 · Viewed 72.6k times · Source

I'm trying to connect my android application to a local host url thanks to wamp server but it doesn't work. My goal here, is to fetch json data and parse these data. For my test, i'm using a device not the emulator and i use permission in AndroidManifest.xml :

<uses-permission android:name="android.permission.INTERNET" />

My url looks like this :

String url = "http://10.0.2.2:8080/tests/PhpProject1/connectionBDD.php";

i tried :

http://localhost/
http://10.0.2.2:8080/
http://10.0.2.2/

But it never worked so far :

    java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)

    failed to connect to /10.0.2.2 (port 8080): connect failed: ETIMEDOUT (Connection timed out)

    java.net.ConnectException: failed to connect to /10.0.2.2 (port 80): connect failed: ETIMEDOUT (Connection timed out)

Then i tried with a json url test found on the internet : http://headers.jsontest.com/

It worked really good and i got json data at this address. So i guess my code is good and the issue here is my localhost url, i don't know what should be its exact form.. I read many threads about it but i didn't find a solution.

Here my code :

Main activity :

public class MainActivity extends Activity {
    private String url = "http://10.0.2.2:8080/tests/PhpProject1/connectionBDD.php";

    private ListView lv = null;
    private Button bGetData;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final JsonDownloaderTask task = new JsonDownloaderTask(this);
        lv = (ListView) findViewById(R.id.list);

        bGetData = (Button)findViewById(R.id.getdata);
        bGetData.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {               
                task.execute(url);                      
            }
        });
    }

    public void jsonTaskComplete(JSONArray data){
        //todo
    }   
}

AsyncTask :

public class JsonDownloaderTask extends AsyncTask<String, String, JSONArray> {

    MainActivity ma;

    public JsonDownloaderTask(MainActivity main){
        ma = main;
    }

    @Override
    protected JSONArray doInBackground(String... url) {
        JSONParser jParser = new JSONParser();
        // Getting JSON from URL
        JSONArray jsonArray = null;
        try {
            jsonArray = jParser.getJSONFromUrl(url[0]);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonArray;        
    }

    protected void onPostExecute(JSONArray data){

        ma.jsonTaskComplete(data);
    }
}

JSONParser :

public class JSONParser {
    String data = "";
    JSONArray jsonArray = null;        
    InputStream is = null;

    public JSONParser(){}

    // Method to download json data from url
    public JSONArray getJSONFromUrl(String strUrl) throws IOException{
        try{
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            is = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            StringBuffer sb  = new StringBuffer();

            String line = "";
            while( ( line = br.readLine())  != null){
                sb.append(line);
            }
            is.close();
            data = sb.toString();

            //br.close();

            jsonArray = new JSONArray(data);

        }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
        }finally{
            is.close();
        }

        return jsonArray;
    }
}

Answer

user3316041 picture user3316041 · Feb 16, 2014

IP-address 10.0.2.2 is used to fetch data from the emulator. Localhost will always point to the emulator/android device running the application. To let your device fetch data from your pc, it should be in the same network (connected by WiFi to your router) and you should use the local IP-address of your pc (normally a 192.168.1.x-number).