I have to get info from an api, however, not all data is coming, for example, there are pokemon that have "skills" and others that don't. I think my Null Pointer Exception error is there, but I don't know what to do to solve it, because when I click on a pokemon to go to its details, crash the app, precisely because it doesn't have "ability"
Log error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.pokedex, PID: 12090
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object
java.util.List.get(int)' on a null object reference
at com.example.pokedex.ui.detalhesPokemons.DetalhesPokemonsFragment$configDetalhes$1
.onChanged(DetalhesPokem
onsFragment.kt:45)
at com.example.pokedex.ui.detalhesPokemons.DetalhesPokemonsFragment$configDetalhes$1
.onChanged(DetalhesPokemonsFragment.kt:14)
at androidx.lifecycle.LiveData.considerNotify(LiveData.java:133)
at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:151)
at androidx.lifecycle.LiveData.setValue(LiveData.java:309)
at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData.java:50)
at com.example.pokedex.ui.detalhesPokemons.DetalhesPokemonsViewModel$getDetalhes$1
.invokeSuspend(DetalhesPok
emonsViewModel.kt:20)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/Process: Sending signal. PID: 12090 SIG: 9
Class DetalhesPokemonsFragment (where it is pulled into the error)
class DetalhesPokemonsFragment: Fragment() {
private val detalhesViewModel: DetalhesPokemonsViewModel by viewModels{
DetalhesPokemonsViewModelFactory((activity?.application as MyApplication).repository)
}
private val argumentos by navArgs<DetalhesPokemonsFragmentArgs>()
private val pokemon by lazy { argumentos.pokemon }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(
R.layout.detalhes_pokemon,
container,
false
)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
configDetalhes()
}
private fun configDetalhes() {
detalhesViewModel.getDetalhes(pokemon.id)
detalhesViewModel.mResponse.observe(viewLifecycleOwner, {
if (it.isSuccessful) {
tv_detalhes_nome_pokemon.text = pokemon.nome
// line where the error appears is down here
if(pokemon.abilities[0].name == null){
pokemon.abilities[0].name = "not abilities"
}else{
tv_detalhes_habilidades_pokemon.text =pokemon.abilities[0].name
}
tv_hp_detalhes_pokemon.text = pokemon.hp
}
})
}
}