I created a simple Restful Api using Spring boot and Kotlin, and I'm trying to consume it an android app but can't seem to do so. It's working fine on postman,in an Angular project and in the emulators browser(Google Chrome, 'http://10.0.2.2:8080/api/accounts')
The problem is I'm not getting any data to be displayed in the TextView(tvTest).
The endpoint:
It's running on http://localhost:8080/
@RestController
@RequestMapping("/api")
class AccountController {
@Autowired
val accountService = AccountService()
@GetMapping(value=["/accounts"])
fun accounts(): ResponseEntity<List<Account>> {
return accountService.accounts()
}
}
on postman:
Android Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:usesCleartextTraffic="false"
Api Service:
interface UserApiService {
@GET("accounts")
fun getAccounts(): Call<UserList>
}
Retrofit:
object RetrofitInstance {
private const val BASE_URL = "http://10.0.2.2:8080/api/"
val api: UserApiService by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(UserApiService ::class.java)
}
}
ViewModel:
class HomeViewModel():ViewModel() {
private var userLiveData = MutableLiveData<User>()
fun getUser()
{
RetrofitInstance.api.getAccounts().enqueue(object : Callback<UserList?> {
override fun onResponse(call: Call<UserList?>, response: Response<UserList?>) {
if(response.body() != null)
{
val user = response.body()!!.users[0]
userLiveData.value = user
}else return
}
override fun onFailure(call: Call<UserList?>, t: Throwable) {
print(t.message.toString())
}
})
}
fun observerUserLiveData(): LiveData<User>
{
return userLiveData
}
Activity:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var homeMvvm: HomeViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
homeMvvm = ViewModelProvider(this)[HomeViewModel::class.java]
homeMvvm.getUser()
observeUser()
}
private fun observeUser()
{
homeMvvm.observerUserLiveData().observe(this)
{
t ->
binding.tvTest.text = t!!.firstName
}
}
}
}