DatabaseException: ожидал список при десериализации, но получил класс java .util.HashMap - PullRequest
0 голосов
/ 12 февраля 2020

Я пытался использовать GenericTypeIndicator в представлении рециркулятора, чтобы установить массив данных в представление рециркулятора в представлении рециркулятора.

GenericTypeIndicator выдает ошибку, из-за которой приложение обрабатывает sh. Я попытался выяснить ошибку, но, похоже, ожидал список, но вместо этого получил Hashmap.

public class ScheduleOrder extends AppCompatActivity implements IFirebaseLoadListener {

    DeviceSession deviceSession;
    UserSession userSession;
    String Device_Id="",User_Id="";

    IFirebaseLoadListener iFirebaseLoadListener;


    RecyclerView my_recycler_view;
    DatabaseReference myData;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedule_order);


        deviceSession = new DeviceSession(getApplicationContext());
        Device_Id = deviceSession.getDeviceDetails();

        userSession = new UserSession(getApplicationContext());
        final HashMap<String, String> user = userSession.getUserDetails();
        User_Id = user.get(UserSession.User_Id);

        FloatingActionButton myFab = (FloatingActionButton)findViewById(R.id.schedule_add);
        myFab.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(),Schedule_Order.class);
                startActivity(i);
                finish();
            }
        });






        myData=FirebaseDatabase.getInstance().getReference("Cart_Schedule"+"/"+Device_Id);
        iFirebaseLoadListener=this;

        my_recycler_view=findViewById(R.id.my_recyclr_view);
        my_recycler_view.setHasFixedSize(true);
        my_recycler_view.setLayoutManager(new LinearLayoutManager(this));


        getFirebaseData();
    }

    private void getFirebaseData() {
        myData.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                List<ItemGroup>itemGroups=new ArrayList<>();
                for(DataSnapshot groupSnapShot:dataSnapshot.getChildren()){

                    ItemGroup itemGroup=new ItemGroup();
                    for(DataSnapshot newdatasnap:groupSnapShot.child("listItem").getChildren()){
                    itemGroup.setD_Time(groupSnapShot.child("d_Time").getValue(true).toString());
                    itemGroup.setF_Amount(groupSnapShot.child("f_Amount").getValue(true).toString());


                    GenericTypeIndicator<ArrayList<ItemData>> genericTypeIndicator=new GenericTypeIndicator<ArrayList<ItemData>>(){};
                    Log.d("JADOO", "onDataChange: ??? "+genericTypeIndicator);
//                    Log.d("JADOO", "onDataChange: ??? "+itemData1.getB_Quantity());
//                    Log.d("JADOO", "onDataChange: ??? "+itemData1.getC_Price());
                    itemGroup.setListItem(newdatasnap.getValue(genericTypeIndicator));

                    itemGroups.add(itemGroup);

                }}

                iFirebaseLoadListener.onFirebaseLoadSuccess(itemGroups);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

                iFirebaseLoadListener.onFirebaseLoadFailed(databaseError.getMessage());
            }
        });
    }


    @Override
    public void onFirebaseLoadSuccess(List<ItemGroup> itemGroupList) {

        MyItemGroupAdapter adapter = new MyItemGroupAdapter(this,itemGroupList);
        my_recycler_view.setAdapter(adapter);
    }

    @Override
    public void onFirebaseLoadFailed(String message) {

    }
}

ItemData. java

    private String a_Item_name;
    private String b_Quantity;
    private String c_Price;
    private String d_Time;
    private String e_ID;
    private String f_Amount;
    private String g_COD;
    private String h_Address;


    public ItemData(){

    }

    public ItemData(String a_Item_name,String b_Quantity,String c_Price, String d_Time, String e_ID,String f_Amount, String g_COD,String h_Address)
    {
        this.a_Item_name=a_Item_name;
        this.b_Quantity=b_Quantity;
        this.c_Price=c_Price;
        this.d_Time=d_Time;
        this.e_ID=e_ID;
        this.f_Amount=f_Amount;
        this.g_COD=g_COD;
        this.h_Address=h_Address;
    }

    public String getA_Item_name() {
        return a_Item_name;
    }

    public void setA_Item_name(String a_Item_name) {
        this.a_Item_name = a_Item_name;
    }

    public String getB_Quantity() {
        return b_Quantity;
    }

    public void setB_Quantity(String b_Quantity) {
        this.b_Quantity = b_Quantity;
    }

    public String getC_Price() {
        return c_Price;
    }

    public void setC_Price(String c_Price) {
        this.c_Price = c_Price;
    }

    public String getD_Time() {
        return d_Time;
    }

    public void setD_Time(String d_Time) {
        this.d_Time = d_Time;
    }

    public String getE_ID() {
        return e_ID;
    }

    public void setE_ID(String e_ID) {
        this.e_ID = e_ID;
    }

    public String getF_Amount() {
        return f_Amount;
    }

    public void setF_Amount(String f_Amount) {
        this.f_Amount = f_Amount;
    }

    public String getG_COD() {
        return g_COD;
    }

    public void setG_COD(String g_COD) {
        this.g_COD = g_COD;
    }

    public String getH_Address() {
        return h_Address;
    }

    public void setH_Address(String h_Address) {
        this.h_Address = h_Address;
    }
}

Ошибка

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.food.pilo, PID: 1501
    com.google.firebase.database.DatabaseException: Expected a List while deserializing, but got a class java.util.HashMap
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToParameterizedType(com.google.firebase:firebase-database@@16.0.4:233)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToType(com.google.firebase:firebase-database@@16.0.4:176)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database@@16.0.4:101)
        at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database@@16.0.4:239)
        at com.food.pilo.ScheduleOrder$2.onDataChange(ScheduleOrder.java:111)
        at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database@@16.0.4:183)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.4:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@16.0.4:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.4:55)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7156)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)```

Скриншот базы данных FireBase с полями данных, которые необходимо отозвать

1 Ответ

0 голосов
/ 12 февраля 2020

На основании предоставленного снимка экрана данные в */someGroup/listItem/someChild имеют форму объекта ItemData. Внутри вашего обработчика onDataChange() вы пытаетесь прочитать значение */someGroup/listItem/someChild в виде массива, используя GenericTypeIndicator, что не удается, потому что это не массив. Это исправлено передачей ссылки на класс ItemData.

List<ItemGroup>itemGroups=new ArrayList<>();
for(DataSnapshot groupSnapShot:dataSnapshot.getChildren()){
    // moved: outside of loop so that values only processed once (for performance)
    String group_d_Time = groupSnapShot.child("d_Time").getValue(true).toString()
    String group_f_Amount = groupSnapShot.child("f_Amount").getValue(true).toString()

    for(DataSnapshot newdatasnap:groupSnapShot.child("listItem").getChildren()) {
        ItemGroup itemGroup = new ItemGroup(); // moved: inside loop to create new object on each loop
        itemGroup.setD_Time(group_d_Time);
        itemGroup.setF_Amount(group_f_Amount);

        itemGroup.setListItem(newdatasnap.getValue(ItemData.class)); // changed: value of newdatasnap is an ItemData object, not an array of ItemData objects

        itemGroups.add(itemGroup);
    }
}

iFirebaseLoadListener.onFirebaseLoadSuccess(itemGroups);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...