Android 从firebase检索多个数据

Android 从firebase检索多个数据,android,firebase,firebase-realtime-database,Android,Firebase,Firebase Realtime Database,嘿,我对firebase和编程也比较陌生,所以如果这是一个愚蠢的问题,我很抱歉。我正在努力找回一份食谱 上面是firebase的数据树,下面是MainActivity的代码 package com.example.myapplicationdatatest; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;

嘿,我对firebase和编程也比较陌生,所以如果这是一个愚蠢的问题,我很抱歉。我正在努力找回一份食谱

上面是firebase的数据树,下面是MainActivity的代码

       package com.example.myapplicationdatatest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class MainActivity extends AppCompatActivity {

    private TextView category;
    private TextView cookinTime;
    private TextView description;
    private TextView ingridients;
    private TextView nameOfRecipe;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );
        category = findViewById( R.id.category );
        cookinTime = findViewById( R.id.cookingTime );
        description = findViewById( R.id.description );
        ingridients = findViewById( R.id.ingridients );
        nameOfRecipe = findViewById( R.id.nameOfRecipe );
        FirebaseApp.initializeApp( getApplicationContext() );






        FirebaseDatabase.getInstance().getReference().child( "recipes" )
                .addListenerForSingleValueEvent( new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                            Recipe recipe = snapshot.getValue( Recipe.class );

                            category.setText( recipe.getCategory() );
                            cookinTime.setText( recipe.getCookingtime() );
                            description.setText( recipe.getDescription() );
                            ingridients.setText( recipe.getIngredients() );
                            nameOfRecipe.setText( recipe.getIngredients() );
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                    }
                } );
    }





}
布局

<?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=".MainActivity">

    <TextView
        android:id="@+id/category"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

      />

    <TextView
        android:id="@+id/cookingTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <TextView
        android:id="@+id/description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <TextView
        android:id="@+id/ingridients"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <TextView
        android:id="@+id/nameOfRecipe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

</LinearLayout>
例外情况呢

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplicationdatatest, PID: 6400
    com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.HashMap to String
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertString(com.google.firebase:firebase-database@@19.1.0:408)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database@@19.1.0:199)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToType(com.google.firebase:firebase-database@@19.1.0:178)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$100(com.google.firebase:firebase-database@@19.1.0:47)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database@@19.1.0:586)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database@@19.1.0:545)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database@@19.1.0:415)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database@@19.1.0:214)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database@@19.1.0:79)
        at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database@@19.1.0:203)
        at com.example.myapplicationdatatest.MainActivity$1.onDataChange(MainActivity.java:53)
        at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database@@19.1.0:179)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.1.0:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.1.0:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.1.0:55)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
我真的不知道如何检索这些多个分支,特别是因为我想添加多个菜谱


谢谢你的帮助

我想你要做的是拿到所有的食谱,然后一个一个地看一遍。 如果是这种情况,请尝试以下方法:

FirebaseDatabase.getInstance().getReference().child("recipes")
     .addListenerForSingleValueEvent(new ValueEventListener() {
     @Override
     public void onDataChange(DataSnapshot dataSnapshot) {
           for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
               Recipe recipe = snapshot.getValue(Recipe.class);//I'm assuming you have a Recipe class
               //Do something with the data
           }
     }
     @Override
     public void onCancelled(DatabaseError databaseError) {
     }
});
在你的食谱课上,配料不是一串。 这是一个Hashmap。 尝试:


您将收到以下错误:

com.google.firebase.database.DatabaseException:未能将java.util.HashMap类型的值转换为字符串


因为配方类中的字段类型不同于数据库中的属性类型。在Recipe类中有一个名为Components的字段,它的类型为String,而在数据库中我看到它是一个映射,这是不正确的,因此出现了错误。字段的类型必须匹配。除此之外,数据库中还有一个名为AmountFingRedients的属性,该属性实际上在Recipe类中缺失。要解决此问题,请根据数据库中存在的属性类型对配方类进行建模,您的问题将得到解决。

我用您的代码更新了我的代码,并创建了一个新的应用程序进行测试,但是,当我试图在主要活动中显示信息时,我遇到了一个例外情况例外情况是什么?sry我为recipe类添加了例外情况和附加更正-参见我的回答我会立即给你写一个答案。谢谢,我清理了主要活动,但没有更改任何内容将配料类型从字符串更改为列表OK,这可能是一个非常愚蠢的问题,但我正试图用如下代码将映射更改为数组:public String[]getamountfingredientsmap{String[]result=new String[10];Map.values.toArray;return amountfingredients;}但我不知道映射的名称,还是我遗漏了什么,你不能那样做。您应该更改类中变量的类型以匹配数据库中的变量。数据库中没有数组。正如您的错误所说,这些对象是贴图。你试过了吗?是的,它工作了,但是输出看起来是这样的:{amount_ing_2=1,amount_ing_3=123}我想提取数字很高兴听到它工作了:在这种情况下,并获得所需的数据。如果你解决了,请告诉我。非常感谢你的帮助:当一切正常时,我将更改我的代码
FirebaseDatabase.getInstance().getReference().child("recipes")
     .addListenerForSingleValueEvent(new ValueEventListener() {
     @Override
     public void onDataChange(DataSnapshot dataSnapshot) {
           for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
               Recipe recipe = snapshot.getValue(Recipe.class);//I'm assuming you have a Recipe class
               //Do something with the data
           }
     }
     @Override
     public void onCancelled(DatabaseError databaseError) {
     }
});
public class Recipe {

    private String category;
    private String cookingtime;
    private String description;
    private HashMap<String, String> ingredients;
    private String nameOfRecipe;

    public Recipe() {};

    public Recipe(String category, String cookingtime, String description,HashMap<String, String>ingredients, String nameOfRecipe) {
        this.category=category;
        this.cookingtime=cookingtime;
        this.description=description;
        this.ingredients=ingredients;
        this.nameOfRecipe=nameOfRecipe;
    }

    public String getCategory() {
        return category;
    }

    public String getCookingtime() {
        return cookingtime;
    }

    public String getDescription() {
        return description;
    }

    public HashMap<String, String> getIngredients() {
        return ingredients;
    }

    public String getNameOfRecipe() {
        return nameOfRecipe;
    }
}