我如何不断收到空回复

问题描述 投票:0回答:2

我试图通过我的 api 获取响应,但我总是得到空响应,但我得到了正确的请求。我不知道这是一条错误调用的路径还是什么

这是我的数据类:

data class ResponseGetDataUser(
    @SerializedName("address")
    val address: String,
    @SerializedName("city")
    val city: String,
    @SerializedName("created_at")
    val createdAt: String,
    @SerializedName("email")
    val email: String,
    @SerializedName("email_verified_at")
    val emailVerifiedAt: Any,
    @SerializedName("id")
    val id: Int,
    @SerializedName("image")
    val image: String,
    @SerializedName("name")
    val name: String,
    @SerializedName("phone")
    val phone: String,
    @SerializedName("updated_at")
    val updatedAt: String
)

这是我的 apiService

@GET("user")
suspend fun getDataUser(@Header("token") token: String): ResponseGetDataUser`

这是我的 apiHelper

suspend fun getDataUser(token: String) = apiService.getDataUser(token)

这是我的存储库

suspend fun getDataUser(token: String) = apiHelper.getDataUser(token)

这是我的视图模型

@HiltViewModel
class AkunViewModel @Inject constructor(private val repository: Repository): ViewModel() {
    private var _alreadyLogin = MutableLiveData<String>()
    val alreadyLogin : LiveData<String> get() = _alreadyLogin

    private var _user = MutableLiveData<Resource<ResponseGetDataUser>>()
    val user : LiveData<Resource<ResponseGetDataUser>> get() = _user


    fun getToken(){
        viewModelScope.launch {
            repository.getToken().collect{
                _alreadyLogin.postValue(it)
            }
        }
    }

    fun getUserData(token: String){
        viewModelScope.launch {
            _user.postValue(Resource.loading())
            try {
                _user.postValue(Resource.success(repository.getDataUser(token)))
            } catch (e: Exception){
                _user.postValue(Resource.error(e.localizedMessage?: "Error Occured"))
            }
        }
    }



    fun deleteToken(){
        viewModelScope.launch {
            repository.deleteToken()
        }
    }


}

这是我的 Fragment 类

@AndroidEntryPoint
class AkunFragment : Fragment() {

    private var _binding: FragmentAkunBinding? = null
    private val binding get() = _binding!!
    private val viewModel: AkunViewModel by viewModels()
    private val bundle = Bundle()

    companion object {
        const val USER_NAME = "fullname"
        const val USER_EMAIL = "email"
        const val USER_PHONE_NUMBER = "phone_number"
        const val USER_ADDRESS = "address"
        const val USER_CITY = "city"
        const val USER_IMAGE = "image_url"
        const val USER_TOKEN = "user_token"
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentAkunBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val progressDialog = ProgressDialog(requireContext())
        viewModel.getToken()
        viewModel.alreadyLogin.observe(viewLifecycleOwner) {
            if (it == DEFAULT_TOKEN) {
                AlertDialog.Builder(requireContext())
                    .setTitle("Pesan")
                    .setMessage("Anda Belom Masuk")
                    .setPositiveButton("Login") { dialogP, _ ->
                        findNavController().navigate(R.id.action_akunFragment_to_loginCompose)
                        dialogP.dismiss()
                    }
                    .setNegativeButton("Cancel") { dialogN, _ ->
                        findNavController().navigate(R.id.action_akunFragment_to_homeFragment)
                        dialogN.dismiss()
                    }
                    .setCancelable(false)
                    .show()
                viewModel.alreadyLogin.removeObservers(viewLifecycleOwner)
            } else {
                bundle.putString(USER_TOKEN, it)
                viewModel.getUserData(it)
            }
        }

        viewModel.user.observe(viewLifecycleOwner) {
            when (it.status) {
                SUCCESS-> {
                    progressDialog.dismiss()
                    if (it.data != null) {
                        bundle.putString(USER_NAME, it.data.name)
                        bundle.putString(USER_EMAIL, it.data.email)
                        bundle.putString(USER_CITY, it.data.city)
                        bundle.putString(USER_ADDRESS, it.data.address)
                        bundle.putString(USER_PHONE_NUMBER, it.data.phone)
                        binding.tvNama.text = it.data.name
                        binding.tvNomor.text = it.data.phone
                        binding.tvEmail.text = it.data.email
                        if (it.data.image != null) {
                            Glide.with(requireContext())
                                .load(it.data.image)
                                .placeholder(R.drawable.image_profile)
                                .transform(CenterCrop(), RoundedCorners(50))
                                .into(binding.ivProfile)
                            bundle.putString(USER_IMAGE, it.data.image)
                        }
                    }
                }
                ERROR -> {
                    Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT)
                        .show()
                    progressDialog.dismiss()
                }
                LOADING -> {
                    progressDialog.setMessage("Please Wait...")
                    progressDialog.show()
                }
            }
        }

        binding.listUbahAkun.setOnClickListener {
            findNavController().navigate(R.id.action_akunFragment_to_editAkunFragment, bundle)
        }
        binding.listPengaturanAkun.setOnClickListener {
            val dialogBinding = MenuPengaturanAkunBinding.inflate(LayoutInflater.from(requireContext()))
            val dialogBuilder = androidx.appcompat.app.AlertDialog.Builder(requireContext())
            dialogBuilder.setView(dialogBinding.root)
            val dialog = dialogBuilder.create()
            dialog.setCancelable(true)
            dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            dialogBinding.listChangePassword.setOnClickListener {
                findNavController().navigate(R.id.action_akunFragment_to_changePasswordFragment, bundle)
                dialog.dismiss()
            }
            dialogBinding.listClose.setOnClickListener {
                dialog.dismiss()
            }
            dialog.show()
        }

        binding.listRiwayatPenawaran.setOnClickListener {
            findNavController().navigate(R.id.action_akunFragment_to_riwayatPenawaranFragment, bundle)
        }
        binding.listWishlist.setOnClickListener{
            findNavController().navigate(R.id.action_akunFragment_to_wishlistFragment)
        }

        binding.listKeluar.setOnClickListener {
            AlertDialog
                .Builder(requireContext())
                .setTitle("Konfirmasi Keluar")
                .setMessage("Yakin ingin keluar?")
                .setPositiveButton("Iya") { dialogPositive, _ ->
                    viewModel.deleteToken()
                    Toast
                        .makeText(
                            requireContext(),
                            "Logout Success",
                            Toast.LENGTH_SHORT
                        )
                        .show()
                    findNavController().navigate(R.id.action_akunFragment_to_homeFragment)
                    dialogPositive.dismiss()
                }
                .setNegativeButton("Tidak") { dialogNegative, _ ->
                    dialogNegative.dismiss()
                }
                .setCancelable(false)
                .show()
        }
    }

}

我的状态 请求

回应

我非常感谢你们的帮助

kotlin dependency-injection android-fragmentactivity
2个回答
0
投票

我很困惑:

suspend fun getDataUser(@Header("token") token: String): ResponseGetDataUser

尝试:

suspend fun getDataUser(@Header("token") token: String): Response<ResponseGetDataUser>

suspend fun getDataUser(@Header("token") token: String): Call<ResponseGetDataUser>

我不明白空洞的答案。

您在改造方法抽搐的地方添加了一个断点,然后您得到一个空对象?

您可以运行网络请求查看器 App Inspection 并查看请求/响应的结构吗?

突然一切正常,错误出现在错误的令牌或类似的东西中。


0
投票

您是否尝试过使用定义,注释应该应用到哪里? 它是提升变量,所以你必须将它告诉 kotlin。

data class ResponseGetDataUser(
    @field:SerializedName("address")
    val address: String,
    @field:SerializedName("city")
    val city: String,
    @field:SerializedName("created_at")
    val createdAt: String,
    @field:SerializedName("email")
    val email: String,
    @field:SerializedName("email_verified_at")
    val emailVerifiedAt: Any,
    @field:SerializedName("id")
    val id: Int,
    @field:SerializedName("image")
    val image: String,
    @field:SerializedName("name")
    val name: String,
    @field:SerializedName("phone")
    val phone: String,
    @field:SerializedName("updated_at")
    val updatedAt: String
)
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.