Valueeventlistener coming back null?

Asked

Viewed 124 times

0

I’m messing with the API of a website and from there I get information from a certain item in a list of items that came from the API and saved in the Firebase database, now I’m wanting to take this information from Firebase to use it, but I’m not getting it at all... Now the log I have there is not printing and when I can make it print it shows null. If you can help me I would be grateful!

Firebase inserir a descrição da imagem aqui

Comicvinemodel

private Long id;
private String name;
private String api_detail_url;

public ComicVineModel() {
}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getApi_detail_url() {
    return api_detail_url;
}

public void setApi_detail_url(String api_detail_url) {
    this.api_detail_url = api_detail_url;
}

Bulky (where I’m trying to get the data)

private ArrayList<VolumeModel> volume = new ArrayList<>();
private Context context;
private FirebaseAuth autenticacao;
private DatabaseReference firebase;
private VolumeModel volumeModel = new VolumeModel();
private ComicVineModel comicVineModel = new ComicVineModel();
private ArrayList<ComicVineModel> listaVineModel = new ArrayList<ComicVineModel>();;
private ValueEventListener eventListenerVolume;


public VolumeAdapter(Context c, ArrayList<VolumeModel> volume) {
    this.volume = volume;
    this.context = c;
}


@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View itemLista = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_volume, parent, false);

    return new MyViewHolder(itemLista);
}

@Override
public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
    volumeModel = volume.get(position);
    firebase = FirebaseDatabase.getInstance().getReference("volume");

    holder.nome.setText(volumeModel.getName());
    Picasso.with(context)
            .load(volume.get(position).getImage().getThumb_url())
            //.placeholder(R.drawable.default_hero)
            .error(R.drawable.default_hero)
            .into(holder.imageView);
    holder.ano.setText(volumeModel.getStart_year());
    holder.edicoes.setText(volumeModel.getCount_of_issues());
    holder.editora.setText(volumeModel.getPublisher().getName());


    holder.estrela.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            holder.estrela.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_star_black_24dp));

            //pega a posição marcada e seta essas informações para irem pro banco
            comicVineModel.setId(volume.get(position).getId());
            comicVineModel.setName(volume.get(position).getName());
            comicVineModel.setApi_detail_url(volume.get(position).getApi_detail_url());

            //salva a revista no Firebase no formato de: colecao - id da revista - dados do volume
            DatabaseReference firebaseSalvaRevista = FirebaseDatabase.getInstance().getReference(usuario());
            firebaseSalvaRevista.child("colecao").child(comicVineModel.getId().toString()).setValue(comicVineModel);

            Toast.makeText(context, comicVineModel.getName() + " está nos favoritos!", Toast.LENGTH_LONG).show();
        }
    });

    eventListenerVolume = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot dados : dataSnapshot.getChildren()) {
                comicVineModel = dados.getValue(ComicVineModel.class);
                listaVineModel.add(comicVineModel);
                Log.i("teste", "teste: " + comicVineModel);
            }
            VolumeAdapter.this.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    };
    firebase.addValueEventListener(eventListenerVolume);

}

@Override
public int getItemCount() {
    return volume.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder{
    private TextView nome;
    private ImageView imageView;
    private TextView ano;
    private TextView edicoes;
    private TextView editora;
    private ImageView estrela;

    public MyViewHolder(View itemView) {
        super(itemView);
        nome = itemView.findViewById(R.id.idNomeRevista);
        imageView = itemView.findViewById(R.id.idImagemVolume);
        ano = itemView.findViewById(R.id.idAno);
        edicoes = itemView.findViewById(R.id.idEdicoes);
        editora = itemView.findViewById(R.id.idEditora);
        estrela = itemView.findViewById(R.id.idEstrela);
    }
}

public String usuario(){
    autenticacao = ConfigFirebase.getFirebaseAutenticacao();
    String usuario = autenticacao.getCurrentUser().getEmail().toString();

    usuario = Base64Custom.codificarBase64(usuario);

    return usuario;
}
  • In your code, you access the "volume" node, but the image of your database does not show this node

2 answers

0

Hello,

First, there’s a big mistake in your code, don’t call Real-time Database within your adapter, this way you will not be able to properly address the call return and the life cycle of the Activity.

Second, you try to access a node that does not exist in the bank.

And third, the calls to the bank are asynchronous, so you’ll need to use a way to get that data at the moment it arrives, regardless of whether it’s simultaneously or in 30 seconds. For that, see How to return an object using addListenerForSingleValueEvent from fire base?

  • For future search for solutions.

0

It had exactly the same problem. Inside the Event the list is fed. But elsewhere in the mainactivitie the list is always empty....

The problem is that the operation in Firebase is asynchronous and when you evaluate the contents of the list the "task" is not finished yet.

I solved the problem by creating a Systener Object with a "done" interface which I override when registering the Systener

Class Meulistener, as follows: package com.mfcapelo.projetob;

public class Meulistener {

private static MeuListener instance;
private EventListener eventListener;

public static MeuListener getInstance() {
    if (instance == null) {
        instance = new MeuListener();
    }
    return instance;
}

public void registerEvent(EventListener eventListener) {
    this.eventListener = eventListener;
}

public void unRegisterEvent() {
    this.eventListener = null;
}

public void emitterDone(Imagem img) {
    this.eventListener.done(img);
}

public interface EventListener {
    void done(Imagem img);
}

}

In the Onstart of the instanced activitie we register the Istener ...

@Override
protected void onStart() {
    super.onStart();

    meuListener = MeuListener.getInstance();
    meuListener.registerEvent(new MeuListener.EventListener() {
        @Override
        public void done(Imagem img) {

            listaImagens.add(img);
            Log.d("Test", "Executou o evento:" + listaImagens.size() );

        }
    });
}

on Onstop shot the memory Istener @Override protected void onStop() { super.onStop();

    meuListener.unRegisterEvent();
}

And finally within the return of Firebase I activate the listner

   ValueEventListener postListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {

                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {

                    Imagem img = postSnapshot.getValue(Imagem.class);
                    /* Aqui utilizamos a interface */
                    meuListener = MeuListener.getInstance();
                    meuListener.emitterDone(img);

                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.d("getDadosUsuarioLogado: ", databaseError.getMessage());
        }
    };
    reference.addListenerForSingleValueEvent(postListener);

I used my case, but the solution to yours follows the same pattern.

I hope I’ve helped.

Thank you,

  • Please do the [tour] and read the [Ask]. This is an answer area, not a question area.

Browser other questions tagged

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