0

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
        }
      })
    }
 }
  • 1
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Henry Twist Apr 29 '21 at 18:31
  • @HenryTwist I tried to base myself on this question but I couldn't find the solution –  Apr 29 '21 at 18:34
  • The error says that `pokemon.abilities` is null, so I am not sure what more clarification you need? If your actual issue is about why that's null, you a) haven't asked that and b) haven't provided any information on what is it, where it's coming from etc. – Henry Twist Apr 29 '21 at 19:02
  • @HenryTwist pokemon.abilities is a pokemon Item value that contains the pokemon's ability. I know the error is on that line, but if with verification (pokemon.abilities [0] .name.isEmpty ()) or verification with "== null" is not working. I don't know what else to do –  Apr 29 '21 at 21:46
  • What do you mean verification with `== null` isn't working? Maybe update your code sample with the verification and I'll take a look, that should catch the problem. – Henry Twist Apr 29 '21 at 22:18
  • Ok, I will update agr –  Apr 29 '21 at 22:22
  • If `pokemon.abilities` is null then obviously calling `pokemon.abilities[0]` will cause another null pointer exception. There's no zeroth element because it doesn't exist. I would definitely take another read of the question I linked, seems like you have a fundamental understanding of the error. – Henry Twist Apr 29 '21 at 22:49
  • So how would I do a check there to help me with this? –  Apr 29 '21 at 22:56
  • `if(pokemon.abilities == null)` – Henry Twist Apr 29 '21 at 23:10
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/231768/discussion-between-matheusfc-and-henry-twist). –  Apr 30 '21 at 01:11

2 Answers2

0

For whatever reason, pokemon.abilities is null. You're trying to access index 0 on a list that isn't there. That's why you're getting this error:

java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object 
java.util.List.get(int)' on a null object reference

you can't call get(int) on null. You need to null check it before you access it:

pokemon.abilities?.get(0)
// or provide a fallback value for if you run into a null
pokemon.abilities?.get(0) ?: "sad pokemon"
// but you should use getOrNull so an empty list doesn't throw an exception
pokemon.abilities?.getOrNull(0) ?: "mysterious pokemon"

If abilities is nullable, i.e. a List?, then your IDE should be warning you about it. At a guess, your API is returning a List!, where the ! means it's coming from Java and isn't giving any hints about whether it's nullable or not.

But it definitely is nullable, because you're getting a null, so maybe you can look at whatever you're using and help it out with a List? type instead, and the same for any other properties your API may or may not provide, or supply some defaults like emptyList(). You'll have to look into how that works for whatever you're using.

cactustictacs
  • 17,935
  • 2
  • 14
  • 25
0

I solved the problem by changing the null check I was doing, from: "pokemon.abilities [0] .name == null" to "pokemon.abilities == null". It was this error that empties me not to do the verification correctly