[SOLVED] How to connect from Android emulator to application on localhost?

To connect from the Android emulator to the application that we have running on your current machine, you must give the appropriate IP address, because Android internally recognizes localhost / 127.0.0.1 as the internal address of the loopback website.

Solution

Instead of localhost/127.0.0.1 use 10.0.2.2 IP address.

Example

    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("https://10.0.2.2:8080/")
            .addConverterFactory(GsonConverterFactory.create());

File /src/main/res/xml/network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
</network-security-config>

File AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bigdataetl.cards" >
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:networkSecurityConfig="@xml/network_security_config"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

If you enjoyed this post please add the comment below or share this post on your Facebook, Twitter, LinkedIn or another social media webpage.
Thanks in advanced!

1.5 2 votes
Article Rating
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Hussain

File /src/main/res/xml/network_security_config.xml This path is not my App
Anymore source to resolve the error