Android connection to localhost
Asked Answered
P

9

22

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;
    }
}
Pontonier answered 16/2, 2014 at 13:31 Comment(0)
T
4

First you have to bind the IP address of the machine where your server is running in the eclipse settings.

You can do this like this.

Eclipse Run Configuration

Right click on the PHP project in the eclipse then Run Configuration then In the Web Application where you will find the Argument tab. Now here give the port and LAN IP address of your machine on which your server is running.

Something like this --port=8888 --address=192.168.1.6 then update the URL to http://192.168.1.6:8080/tests/PhpProject1/connectionBDD.php

Here in my case this is my LAN IP address 192.168.1.6, there you will have to find it using the network command like ipconfig , ifconfig and use that IP address.

Thermidor answered 16/2, 2014 at 13:51 Comment(9)
Thanks for the answer, i managed this with NetBeans so now, urlConnection.connet(); works fine but i have another exception : java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer), maybe you know this issuePontonier
Well, For this new issue you can read here #11207894 and now you can accept the answerThermidor
@TGMCians Is the 8888 a typo ?Himmler
@StephaneEybert No, it's port number on which my server was running.Thermidor
@TGMCians -- I am also facing a problem like this one. I tried to follow your solution, but I did not understand the part "First you have to bind the IP address of the machine where your server is running in the eclipse settings." I am not using Eclipse. I am trying to connect Android with MySQL database using PHP through WAMP server. The PHP file is being saved in the below path -- C:\wamp\www\android_connect This is the question I asked. Your help will be appreciated! :)Cohune
How can I do that on Android studio?Arching
How do i do that in Android Studio ? @AbdelazizMirad Did you find a solution ?Caril
@SaumikBhattacharya Did you find a solution to your question ?Caril
@Taurus -- Please find my answer in this question. It is very straight forward and you will be able to understand.Cohune
M
14

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

Musclebound answered 16/2, 2014 at 15:22 Comment(3)
i have tried it with my lappy's ip address but still it is not connectingMats
This only works on the Emulator, while the question specifically says it is using a device.Strasbourg
No, connecting using the 192.168.1.x IP address of the PC works with physical devices, if the server running on the PC is accessible within the local network. In my answer, I first explained why the code in the question didn't work.Musclebound
C
6

If you try to connect to "localhost", it will resolve to the Android device, not to your own localhost (unless you are running within the emulator). What I recommend for development is to add an overflow menu in the action bar that has an entry named "Settings" that provides a Settings activity for specifying application settings, and to have a "Developer options" entry in "Settings" that lets you specify a custom server address to use. During development, you can use this option to enter a custom server address for your app. (You will need a real server address that is actually reachable over the Internet rather than using localhost for this).

Cephalo answered 16/2, 2014 at 13:39 Comment(0)
T
4

First you have to bind the IP address of the machine where your server is running in the eclipse settings.

You can do this like this.

Eclipse Run Configuration

Right click on the PHP project in the eclipse then Run Configuration then In the Web Application where you will find the Argument tab. Now here give the port and LAN IP address of your machine on which your server is running.

Something like this --port=8888 --address=192.168.1.6 then update the URL to http://192.168.1.6:8080/tests/PhpProject1/connectionBDD.php

Here in my case this is my LAN IP address 192.168.1.6, there you will have to find it using the network command like ipconfig , ifconfig and use that IP address.

Thermidor answered 16/2, 2014 at 13:51 Comment(9)
Thanks for the answer, i managed this with NetBeans so now, urlConnection.connet(); works fine but i have another exception : java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer), maybe you know this issuePontonier
Well, For this new issue you can read here #11207894 and now you can accept the answerThermidor
@TGMCians Is the 8888 a typo ?Himmler
@StephaneEybert No, it's port number on which my server was running.Thermidor
@TGMCians -- I am also facing a problem like this one. I tried to follow your solution, but I did not understand the part "First you have to bind the IP address of the machine where your server is running in the eclipse settings." I am not using Eclipse. I am trying to connect Android with MySQL database using PHP through WAMP server. The PHP file is being saved in the below path -- C:\wamp\www\android_connect This is the question I asked. Your help will be appreciated! :)Cohune
How can I do that on Android studio?Arching
How do i do that in Android Studio ? @AbdelazizMirad Did you find a solution ?Caril
@SaumikBhattacharya Did you find a solution to your question ?Caril
@Taurus -- Please find my answer in this question. It is very straight forward and you will be able to understand.Cohune
H
3

if you are using your phone instead of emulator and running services on localhost then in url instead of '10.0.2.2' use IP address of your PC.

Haplography answered 30/10, 2017 at 13:6 Comment(0)
R
1

I solved it by: 1. Adding another android permission in the manifest: "android.permission.ACCESS_NETWORK_STATE" 2. As I'm using xampp, I've shared the xampp folder of the desktop in the network. 3. The xampp is running in a desktop whose ip is 192.168.x.x so the webservice's url instead of beign "http://localhost/myapi..." is "http://192.168.x.x/myapi..."

I tested the app using the emulator and also in a device. Both cases works out.

Rossini answered 5/4, 2020 at 3:46 Comment(0)
S
0

One simple way i know is keep mobile data on and share wifi . Connect your laptop or computer to this wifi . Now see ip of ur laptop or desktop. Call service from ur phone . Since your phone and your computer are in same network now.

Shing answered 9/1, 2016 at 13:21 Comment(0)
D
0

I assume you are trying to access web service available on your PC from either an android simulator or a real device.

For an android emulator, you must NOT just use "localhost", because "localhost" means android emulator itself, NOT the host PC.

you need modify the /etc/hosts file or the simulator or real device. add a line like "192.168.0.100 service.local".

Donative answered 30/4, 2016 at 16:24 Comment(0)
E
0

I tried "10.0.2.2:80/mysitename/page.php" Miracle happened, it's working now. I am on Mac and using XAMPP for server.

You can change port no. to 80 and try. port 8080 was not working for me!

Cheers.

Edirne answered 30/5, 2017 at 15:43 Comment(1)
This only works on emulators, while the question explicitly specified a physical deviceStrasbourg
L
0

Just Install the "conveyor by Keyoti" the extension in Visual studio and it will generate a url according to your ip address automatically. here's the link:

conveyor

so far so good....!

Linettelineup answered 19/2, 2019 at 13:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.