Passing data from one Ragment to another

Asked

Viewed 36 times

-3

I want to pass data from one Ragment to another, but the code works but does not pass the data. Someone can help me in this?

I wish to go from ListaPokemonsFragment for DetalhesPokemonFragment

ListaPokemonsFragment:

// acao de ir para os detalhes do pokemon clicado
private fun goToDetalhes(pokemon: PokemonItem){
    val direcao = ListaPokemonsFragmentDirections
        .actionListaPokemonsToDetalhesPokemons(pokemon)
    controlador.navigate(direcao)
}

DetalhesPokemonFragment

private fun configDetalhes() {
   viewModel.getDetalhes(pokemon.id)
    viewModel.mResponse.observe(viewLifecycleOwner, {
        if(it.isSuccessful){
            tv_detalhes_nome_pokemon.text = it.body()?.nome
        }
    })
}

navigation:

<fragment
  android:id="@+id/detalhesPokemons"
  tools:layout="@layout/detalhes_pokemon"
  android:name="com.example.pokedex.ui.detalhesPokemons.DetalhesPokemonsFragment"
  android:label="Detalhes Pokemons" >
  <argument
      android:name="pokemon"
      app:argType="com.example.pokedex.model.PokemonItem" />
</fragment>

1 answer

1


  • Puts your argument inside the initial fragment action ( What has the action of going to a destination) for example:
    <fragment
        android:id="@+id/listPokemonsFragment"
        android:name="seu.pacote.aqui.ListPokemonsFragment"
        android:label="fragment_listPokemons"
        tools:layout="@layout/fragment_list_pokemons" >
        <action
            android:id="@+id/action_listPokemonsFragment_to_DetalhesPokemonFragment"
            app:destination="@id/fragment_detalhes_pokemon">
            <argument
                android:name="pokemon"
                app:argType="com.example.pokedex.model.PokemonItem" />
        </action>
    </fragment>
  • In Detailsespokemonfragment you will receive the Pokemonitem in Bundle with the same name you gave in argument name attribute:
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            pokemonItem = it.getSerializable("pokemon")
        }
    }

Remember that your class needs to implement the Serializable or Parcelable interface to send and receive in the Bundle. You can do this by consulting here https://stackoverflow.com/questions/5784231/how-to-pass-custom-object-in-bundle

  • when I create onCreate, it’s not getting the "pokemonItem"

  • @Matheusfinamor did you serialize the object? The answer is very clear, I tested it here myself and it worked

  • Yes, I solved the problem, it was giving error with my Database. I’m still not doing the data persistence but had already left the database ready, with it ready was giving a conflict with my "Pokemonitem". Delete my Database class and it worked normally. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.