1

I am getting this error when clicking the button in my project and trying to print the data as text.

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

Can you help me with what I missed?

MainActivity:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private val viewModel: PasswordGeneratorViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.generatePassword.apply {
            setOnClickListener {
                binding.password.text = viewModel.responsePassword.toString()
            }
        }

    }

}

PasswordGeneratorViewModel:

@HiltViewModel
class PasswordGeneratorViewModel @Inject constructor(private val repository: PasswordGeneratorRepository): ViewModel() {

    private val _response = MutableLiveData<List<PasswordModel>>()
    val responsePassword: LiveData<List<PasswordModel>>
        get() = _response

    init {
        getPassword()
    }

    private fun getPassword() = viewModelScope.launch {
        repository.getPasswordGenerate().let {response ->
            if (response.isSuccessful){
                _response.postValue(response.body())
            }else{
                Log.d("tag", "getPassword Error: ${response.code()}")
            }
        }
    }

}

PasswordModel:

import com.google.gson.annotations.SerializedName

data class PasswordModel(
    @SerializedName("char")
    val char: List<String>
)
1
  • 1
    In your model you have added ArrayList, but in your response its not starting with array so remove arraylist from starting your response. Commented Jul 23, 2022 at 7:17

1 Answer 1

3

The response coming from the API is it not an array. The start of response indicates that it is an object. This is a sample output from that API:

{
"char": [
"ReaGU7]37tq"
   ]
}

Solution – use this:

class PasswordResponse : PasswordModel()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.