androidapikotlinxamppfuel

Unable to connect to API on local xampp server from android app (via emulator)


I have a simple API written in PHP to interact with my MYSQL database. The API returns the correct response when I call it from the browser in the emulator but the request fails when its being done from the code.

package com.example.studenthealthapp
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.result.Result
import org.json.JSONArray

class InfoActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    supportActionBar?.hide()
    setContentView(R.layout.info_layout)

    val api_url =
        "http://10.0.2.2:80/HealthTracker/api.php?email=" + getIntent().getStringExtra("email")
    //Toast.makeText(this,api_url,Toast.LENGTH_LONG).show()

    Fuel.get(api_url).response { request, response, result ->

        when (result) {
            is Result.Success -> {
                //var data = JSONArray(String(response.data))
                //Toast.makeText(this,data.length().toString(),Toast.LENGTH_SHORT).show()
                Toast.makeText(this, "Worked", Toast.LENGTH_SHORT).show()
            }
            is Result.Failure -> {
                Toast.makeText(this, "Didnt work", Toast.LENGTH_SHORT).show()
            }
        }

      }
   }
}

I have tried both my IP address and 10.0.2.2 when calling the API all of them has the same result.


Solution

  • I may have run into this problem before and your solutions may lie in one of two options. I don't recommend the first as it sets a bad precedent for future projects.

    1. The first would be to allow "http://..." without the "s", also called clear text traffic in your apps manifest. A quick search on youtube will get you some outdated tutorials and this is probably not a good sign.
    2. My preferred solution is that you switch from Volley to Retrofit. It has better up-to-date tutorials both on youtube and in articles on the web and is much easier to use. It might seem like starting from scratch but you'll be saving yourself from a lot of future headaches.

    Good luck!