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.
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.
Good luck!