Почему я не могу сохранить информацию из моего пожарного хранилища в моем классе модели Java

Класс активности магазина должен извлекать данные из базы данных и отправлять им класс модели магазина, а также настраивать представление ресайклера для отображения информации. Существует также класс адаптера магазина, который обрабатывает отдельные элементы представления Recycler View, он извлекает необходимую информацию из класса модели магазина.

Хотя кажется, что он получает данные из базы данных, он не отправляет эти данные в класс модели. Мы считаем, что эта проблема возникает в классе активности магазина, и отметили в комментариях, где, по нашему мнению, возникает проблема.

Это структура базы данных Firestore, все поля в магазине - String: 1

Это то, что приложение отображает в настоящее время Это то, что приложение отображает в настоящее время

код задействован

package com.example.deliveryapp;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;


public class StoreActivity extends AppCompatActivity{
    //Gets the current instance of the database
    private FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
    //Stores the Collection Path for Store
    private CollectionReference StoreRef = firebaseFirestore.collection("Store");
    //Variable for storing the RecyclerView
    private RecyclerView sFirestoreList;
    StoreAdapter adapter;


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

        //Gets Current Instance of Database
        firebaseFirestore = FirebaseFirestore.getInstance();
        StoreRef = firebaseFirestore.collection("Store");
        sFirestoreList = findViewById(R.id.StoreList_rv);

        sFirestoreList.setLayoutManager(new LinearLayoutManager(this));

        //Creates the Query for getting information from the Database
        Query query = StoreRef;

        //Sends the Query to the Database and send that information to the Model Class
        //reminder to self the problem is in this part (Possibly), the app is retrieving data from the Database however can't seem to send it to the model class
        FirestoreRecyclerOptions<StoreModel> options = new FirestoreRecyclerOptions.Builder<StoreModel>()
                .setQuery(query, StoreModel.class)
                .build();

        //Connects the activity to the Adapter Class
        adapter = new StoreAdapter(options);
        //Connects the RecyclerView to the Adapter Class
        sFirestoreList.setAdapter(adapter);
    }

    // Gets the App to start reading data from the Database
    @Override
    protected void onStart(){
        super.onStart();
        adapter.startListening();
    }

    // Gets the App to Stop reading data from the Database
    @Override
    protected void onStop() {
        super.onStop();
        adapter.stopListening();
    }
}



package com.example.deliveryapp;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;

public class StoreAdapter extends FirestoreRecyclerAdapter<StoreModel, StoreAdapter.StoreViewholder> {

    public StoreAdapter(@NonNull FirestoreRecyclerOptions<StoreModel> options){
        super(options);
    }

    //Binds the data from the model class to Adapter's variables
    @Override
    protected void onBindViewHolder(@NonNull StoreViewholder holder, int position, @NonNull StoreModel model){
        holder.storeName.setText(model.getStoreName());
        holder.storeAddress.setText(model.getStoreAddress());
        holder.storeID.setText(model.getStoreID());
        //holder.storeID.setText("Test ID");
        //holder.storeName.setText("Test Store");
        //holder.storeAddress.setText("Test Address");
    }

    //Finds the display card for the data to be printed on
    @NonNull
    @Override
    public StoreViewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.storelist, parent, false);
        return new StoreAdapter.StoreViewholder(view);
    }

    //Prints the Store Information to the Activity Display
    class StoreViewholder extends RecyclerView.ViewHolder {
        TextView storeID, storeName, storeAddress;
        //Finds the Textviews by their ID and sets the their text
        public StoreViewholder(@NonNull View itemView){
            super(itemView);
            storeID = itemView.findViewById(R.id.Store_ID);
            storeName = itemView.findViewById(R.id.Store_Name);
            storeAddress = itemView.findViewById(R.id.Store_Address);
        }
    }
}


package com.example.deliveryapp;

public class StoreModel {
    private String storeID;
    private String storeName;
    private String storeAddress;

    //private String storeID = "TestID";
    //private String storeName = "TestName";
    //private String storeAddress = "TestAddress";

    //Empty Constructore for Firebase
    public StoreModel(){
        //Empty
    }

    //Constructor for gathering information from the firestore
    public StoreModel(String StoreAddress, String StoreID, String StoreName) {
        this.storeID = StoreID;
        this.storeName = StoreName;
        this.storeAddress = StoreAddress;
    }

    // Gets the Store ID
    public String getStoreID() {
        return storeID;
    }

    // Sets the Store ID
    public void setStoreID(String StoreID) {
        this.storeID = StoreID;
    }

    // Gets the Store Name
    public String getStoreName() {
        return storeName;
    }

    // Sets the Store Name
    public void setStoreName(String StoreName) {
        this.storeName = StoreName;
    }

    // Gets the Store Address
    public String getStoreAddress() {
        return storeAddress;
    }

    // Sets the Store Address
    public void setStoreAddress(String StoreAddress) {
        this.storeAddress = StoreAddress;
    }
}

person Qrow    schedule 23.04.2021    source источник


Ответы (1)


Firebase / Firestore использует соглашение об именах JavaBean для определения соответствия между полями Java и полями в документе.

Это означает, что ваш метод public String getStoreID() интерпретируется как поле storeID в документе. Но на самом деле в вашем документе есть StoreID с заглавными буквами S. Поскольку storeID и StoreID не совсем то же самое, Firebase не отображает их при чтении / записи данных.

Вы можете использовать storeID в качестве имени поля в документе или использовать _ 8_ аннотация для каждого метода получения и настройки:

@PropertyName("StoreID")
public String getStoreID() {
    return storeID;
}

@PropertyName("StoreID")
public void setStoreID(String StoreID) {
    this.storeID = StoreID;
}

Также см:

person Frank van Puffelen    schedule 23.04.2021