0

I was trying to connect to android emulator on localhost and i'm getting the following error

onFailure: java.net.ConnectException: Failed to connect to /127.0.0.1:3000

Any help would be greatly appreciated thanks in advance.

Here is the code i'm trying to run

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        call()
    }

    private fun call() {

        val retrofit = Retrofit.Builder()
            .baseUrl("http://127.0.0.1:3000")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val apiService = retrofit.create(ApiService::class.java)

        val call = apiService.login()
        call.enqueue(object : Callback<String>{
            override fun onResponse(call: Call<String>, response: Response<String>) {
                Log.i("api_test", "onSuccess: ${response.body()}")
            }

            override fun onFailure(call: Call<String>, t: Throwable) {
                Log.i("api_test", "onFailure: $t")
            }

        })

    }
}
interface ApiService {
    @GET("test")
    fun login(): Call<String>
}
  • According to [google](https://google.com?q=android%20emulator%20localhost%20ip), the IP of the local machine from the emulator is 10.0.2.2. – Jorn Jun 22 '23 at 14:40
  • Yes. And localhost is the emulator itself in this case. Every device is its own localhost/127.0.0.1. – blackapps Jun 22 '23 at 14:51
  • Possible duplicate of https://stackoverflow.com/q/5806220/150978 – Robert Jun 22 '23 at 16:27

0 Answers0