Problems to list firebase data on android

Asked

Viewed 830 times

1

Good morning ! I’m having trouble listing data from a certain node in my application... when I list it as the codes below I get the following return from Exception: "com.google.firebase.database.Databaseexception: Can’t Convert Object of type java.lang.String to type com.ramattecgmail.Rafah.herdeirosapp.Models.Cardapio" as the error nçao informs which object exactly it can’t convert I couldn’t solve the problem. Below follows how is the structure in firebase: inserir a descrição da imagem aqui

xml lista_cardapio.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout    xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/fundo_cardapio">


<TextView
    android:id="@+id/tv_refeicao_lista"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Refeição"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="16dp"
    android:layout_marginLeft="24dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:textSize="20sp"/>

<TextView
    android:id="@+id/tv_ingredientes_lista"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="O que teremos?"
    android:layout_marginTop="8dp"
    app:layout_constraintTop_toBottomOf="@+id/tv_refeicao_lista"
    android:layout_marginLeft="24dp"
    app:layout_constraintLeft_toLeftOf="parent" />

 </android.support.constraint.ConstraintLayout>

Activitycardapio.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ramattecgmail.rafah.herdeirosapp.Activitys.CardapioActivity"
android:orientation="vertical">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<ListView
    android:id="@+id/lv_cardapio"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@color/linha_cardapio"
    android:dividerHeight="0.3dp"/>


</LinearLayout>

Cardapio.java(models)

public class Cardapio {
//ATRIBUTOS
private String refeicao;
private String ingredientes;
private String data;

public Cardapio(){

}

public void salvarCardapio(){

    //Pegando o ano atual
    Date ano = Calendar.getInstance().getTime();
    DateFormat format = new SimpleDateFormat("yyyy");
    String anoRetiro = format.format(ano);

    //pegando o ano atual para salvar no nó retiro
    DatabaseReference reference = ConfiguracaoFirebase.getFirebaseReference();
    reference.child("RETIRO")
            .child(anoRetiro)
            .child("CARDAPIO")
            .child(getData())
            .child(getRefeicao())
            .setValue(this);

}

public String getRefeicao() {
    return refeicao;
}

public void setRefeicao(String refeicao) {
    this.refeicao = refeicao;
}

public String getIngredientes() {
    return ingredientes;
}

public void setIngredientes(String ingredientes) {
    this.ingredientes = ingredientes;
}

public String getData() {
    return data;
}

public void setData(String data) {
    this.data = data;
}

}

Cardapioadapter.java

public class CardapioAdapter extends ArrayAdapter<Cardapio> {
private ArrayList<Cardapio> arrayList;
private Context context;

public CardapioAdapter(@NonNull Context c, @NonNull ArrayList<Cardapio> objects) {
    super(c, 0, objects);
    this.arrayList = objects;
    this.context = c;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View view = null;

    //Validando e criando a lista
    if (arrayList != null){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);

        //Montando a view a partir do XML
        view = inflater.inflate(R.layout.lista_cardapio, parent, false);

        //Recuperando os componentes para exibição
        TextView refeicao = view.findViewById(R.id.tv_refeicao_lista);
        TextView ingredientes = view.findViewById(R.id.tv_ingredientes_lista);

        Cardapio cardapio = arrayList.get(position);
        refeicao.setText(cardapio.getRefeicao());
        ingredientes.setText(cardapio.getIngredientes());

    }
    return view;
}
}

and last but not least, the Activity that should display the list Cardapioactivity.java

public class CardapioActivity extends AppCompatActivity {
//ATRIBUTOS
ListView listView;

private ArrayList<Cardapio> arrayList;
private ArrayAdapter adapter;
private DatabaseReference reference;
private ValueEventListener valueEventListener;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cardapio);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    //INSTANCIANDO OS COMPONENTES
    arrayList = new ArrayList<>();
    listView = (ListView) findViewById(R.id.lv_cardapio);
    adapter = new CardapioAdapter(CardapioActivity.this, arrayList);
    listView.setAdapter(adapter);

    //Pegando o ano atual
    Date ano = Calendar.getInstance().getTime();
    DateFormat format = new SimpleDateFormat("yyyy");
    String anoRetiro = format.format(ano);

    reference = ConfiguracaoFirebase.getFirebaseReference()
            .child("RETIRO")
            .child(anoRetiro)
            .child("CARDAPIO")
            .child("24")
            .child("11")
            .child("Almoço");

    valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            arrayList.clear();

            //Listando os eventos
            for (DataSnapshot data: dataSnapshot.getChildren()){
                Cardapio cardapio = data.getValue(Cardapio.class);
                arrayList.add(cardapio);
            }
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    };
}

/******************************** METODOS ********************************/
@Override
protected void onStart() {
    super.onStart();
    reference.addValueEventListener(valueEventListener);
}

@Override
protected void onStop() {
    super.onStop();
    reference.removeEventListener(valueEventListener);
}

}

In the Ference it has the last Child ("Lunch") only for tests because what I want is to list all meals for the day I pass by parameter (in this case the 24 and the 11 will be passed dynamically)And if you observe you can see that in the Cardapio Model class where I do the recording through a dialogFragment I instate the date and firebase alone separates the day of the month on its nodes as image... Thanks in advance !

1 answer

0


Apparently the problem was related to the fact that when I saved the data I didn’t add any kind of key, just pure data at the nodes, so I added an encryption precisely at the node that I needed to bring the children as picture: inserir a descrição da imagem aqui

So the same code presented above the account to bring the data of the cardapio that I needed, I answered for example, if someone has problems to list the data of firebase, maybe adding an encryption to the child node is enough if you’re listing them with dataSnapsho.getchildren

Browser other questions tagged

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