Postingan lainnya
Android respon null saat request api dengan retrofit
Misi bang mau tanya, sudah coba browsing dll. dan mengulang tutorial android tetap sama responnya null saat di tampilkan ke TextView.
ini kode di OverviewFragment.kt
class OverviewFragment : Fragment() {
private lateinit var recycleView: RecyclerView
private lateinit var viewAdapter: RecyclerView.Adapter<*>
private lateinit var viewManager: RecyclerView.LayoutManager
private lateinit var viewModel: MyViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val binding : FragmentOverviewBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_overview, container, false)
viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
binding.setLifecycleOwner(this)
binding.text1.text = viewModel.res.value.toString()
return binding.root
}
}
ini kodenya di viewModel
class MyViewModel : ViewModel() {
private var _res = MutableLiveData<String>()
val res: LiveData<String>
get() = _res
init {
GithubAPI.retrofitService.showList().enqueue(object: Callback<String>{
override fun onResponse(call: Call<String>?, response: Response<String>?) {
_res.value = response!!.body()
}
override fun onFailure(call: Call<String>?, t: Throwable?) {
_res.value = "FAILED"
}
})
}
}
dan ini di GithubApiService.kt
private val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://api.github.com/")
.build()
interface GithubService{
@GET("repos/laravel/laravel/contributors")
fun showList():
Call<String>
}
object GithubAPI{
val retrofitService = retrofit.create(GithubService::class.java)
}
Jadi saat di OverviewFragment saya binding ke TextView mengambil dari viewModel kok dia null, kira-kira kenapa?
0
1 Jawaban:
Jawaban Terpilih
soalnya fungsi setValue() harus dipanggil dari main thread, kalo mau ngerubah value dari background thread (kayak request data dari server) pakenya fungsi postValue()
MyViewModel: <pre> _res.postValue(response!!.body()) </pre>
<a href=''>T</a>
1