My android project have a server. This is my configure
- In my MainViewModel file
class MainViewModel :ViewModel(){
private val _filmRespone: MutableState<filmState> = mutableStateOf(filmState())
val filmRespone = _filmRespone
init {
fetchFilms()
}
fun updateFilmState(loading:Boolean = false, error:Boolean = false, respone: List<FILM> = listOf(), e:String = ""){
_filmRespone.value = _filmRespone.value.copy(
loading = loading,
error = error,
respone = respone,
e = e,
)
}
fun fetchFilms(){
viewModelScope.launch {
try {
val respone = SimpleAPI("http://10.0.2.2:8080/").retrofit.create(ApiService::class.java).getFilmsLocalAPI()
updateFilmState(false, false, respone.body()?.results?: listOf(), respone.message())
}catch (e:Exception){
Log.d("ERROR", e.toString())
}
}
}
data class filmState(
val loading:Boolean = false,
val error:Boolean = false,
val respone:List<FILM> = listOf(),
val e:String = "",
)
}
-In my SimpleApi file
val okHttpClient = OkHttpClient()
.newBuilder()
.addInterceptor { chain ->
val request = chain.request().newBuilder()
.addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyMTIzIiwiaWF0IjoxNzEzOTYwNDkyLCJleHAiOjE3MTQ4NDk1MjV9.ULWIVj4PwS_a5oxPGWNYHvrWHfQJkLv-3_wNabHCGeQ")
.build()
chain.proceed(request)
}
.build()
open class SimpleAPI(base_url:String) {
val retrofit = Retrofit
.Builder()
.client(okHttpClient)
.baseUrl(base_url)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
- And in my APIService file
interface ApiService {
@GET("api/v1/films")
suspend fun getFilmsLocalAPI():Response<filmRespone>
}
I don’t know where my program is wrong. I added internet permission, added network_security_config.xml file. Forwarded port. But i just can get and update data from my postman
New contributor
Giáp Xuân is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.