如何在不更新数据的情况下将数据存储到Firebase数据库中?并检索数据

时间:2019-05-16 22:44:18

标签: android firebase firebase-realtime-database

我目前正在从事一个项目,该项目可能在商店中用于订购食物。该设备已经可以存储一些数据并进行检索,但是我一直在处理问题。

问题1#:首先,每次我存储数据时通常如下所示:

enter image description here

由于某种原因,我尝试使用子项“ 02”,因为如果我将“ Ordering”作为子项执行时,它会显示在回收器视图中,但它似乎没有显示在显示屏中。我如何像孩子02中的示例一样向其中添加更多数据,我仍然可以像奶昔或糖果棒一样添加数据?这是我完成的存储代码。

public class Detailsoforder extends AppCompatActivity {

    private static final String TAG = "AddToDatabase";

    private TextView titles;
    private TextView increase;
    private int count = 0;

    //add Firebase
    private FirebaseDatabase mFirebaseDatabase;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private DatabaseReference myRef;

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

        titles = findViewById(R.id.Order);
        increase = findViewById(R.id.Increase);
        String title = getIntent().getStringExtra("title");

        titles.setText(title);

        mAuth = FirebaseAuth.getInstance();
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        myRef = mFirebaseDatabase.getReference();

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                } else {
                    // User is signed out
                    Log.d(TAG, "onAuthStateChanged:signed_out");
                }
            }
        };

        // Read from the database
        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                Object value = dataSnapshot.getValue();
                Log.d(TAG,"Value is"+value);
            }

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

            }
        });
    }

    public void onIncreaseClick(View view) {

        count++;
        increase.setText(String.valueOf(count));

    }

    public void onOrderNow(View view) {

        String value = increase.getText().toString();

        if (value.equals("1")) {

            Toast.makeText(Detailsoforder.this,"The order must be above 1", Toast.LENGTH_LONG).show();

        }
        else {
            Log.d(TAG, "onClick: Attempting to add object to database.");
            String newFood = titles.getText().toString();
            if (!newFood.equals("")) {
                FirebaseUser user = mAuth.getCurrentUser();
                String userID = user.getUid();
                myRef.child(userID).child("02").child("food").setValue(newFood);
                myRef.child(userID).child("02").child("order").setValue(value);
                Toast.makeText(Detailsoforder.this,"Adding " + newFood + " to database...", Toast.LENGTH_LONG).show();
                //reset the text
                titles.setText("");
                Intent intent = new Intent(Detailsoforder.this, Placeorder.class);
                startActivity(intent);
            }
        }


    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }
}

我如何存储许多数据并且不需要更新?

问题2#::检索数据。问题是我似乎只能获得1个数据。我想先修复商店零件,以便检查是否可以获得很多信息。这是我的数据检索代码。

public class Vieworders extends AppCompatActivity {

private RecyclerView mRecyclerView1;
private ViewHolder1 mAdapter1;
private DatabaseReference mDatabaseReference1;
private List<Model1> mModel1;
private FirebaseAuth mAuth;

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

    mRecyclerView1= findViewById(R.id.recyclerview1);
    mRecyclerView1.setHasFixedSize(true);
    mRecyclerView1.setLayoutManager(new LinearLayoutManager(this));

    mModel1 = new ArrayList<>();
    mAuth = FirebaseAuth.getInstance();
    FirebaseUser user = mAuth.getCurrentUser();
    String userID = user.getUid();
    mAdapter1=new ViewHolder1(Vieworders.this, mModel1);
    mRecyclerView1.setAdapter(mAdapter1);
    mDatabaseReference1= FirebaseDatabase.getInstance().getReference(userID);
    mDatabaseReference1.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
            {
                Model1 model1=postSnapshot.getValue(Model1.class);
                mModel1.add(model1);
            }
            mAdapter1.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Toast.makeText(Vieworders.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
        }
    });
}

有人可以帮我吗?我真的需要这样做。

1 个答案:

答案 0 :(得分:0)

我认为您能够发送数据并能够存储这些数据。    现在,这是我从Firebase提取数据的片段。您可以从此代码中寻求帮助。

 private RecyclerView recyclerView;
    private List<RoomRentData> firebaselist;
    private DatabaseReference mFirebaseDatabase;
    private FirebaseDatabase mFirebaseInstance;
    private DualProgressView progressView;

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

        firebaselist=new ArrayList<>();
        recyclerView=findViewById(R.id.rent_item);
        progressView=findViewById(R.id.progressbar);
        progressView.setVisibility(View.VISIBLE);
        recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(),1));
        recyclerView.setItemAnimator( new DefaultItemAnimator());
        recyclerView.hasFixedSize();

        final Calendar today = Calendar.getInstance();
        String year=Integer.toString(today.get(Calendar.YEAR));

        mFirebaseInstance = FirebaseDatabase.getInstance();
        mFirebaseDatabase = mFirebaseInstance.getReference("room_rent").child(year);

        mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                progressView.setVisibility(View.GONE);

                System.out.println("1");
                RoomRentData user = dataSnapshot.getValue(RoomRentData.class);

                if (user == null) {
                    System.out.println("2");
                    Toast.makeText(ShowRentActivity.this,"No data found",Toast.LENGTH_LONG).show();
                    return;
                }else {
                    for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
                        System.out.println("datasnapshot 1"+dataSnapshot1);
                        System.out.println("3");
                        RoomRentData userdetails = dataSnapshot1.getValue(RoomRentData.class);

                        System.out.println("userdetails 1"+userdetails);
                        RoomRentData listdata = new RoomRentData();
                        String month=userdetails.getMonth();
                        String year=userdetails.getYear();
                        String cuRead=userdetails.getCurrentRead();
                        String prevRead=userdetails.getPrevUnit();
                        String totalRent=userdetails.getTotalRoomRent();

                        String perPersonCost=userdetails.getPerpersonCost();
                        String totalPeron=userdetails.getTotalPerson();
                        String paidOn=userdetails.getCurrentTimeAndDate();
                        String description=userdetails.getDescription();

                        System.out.println("description 1"+description);
                        System.out.println("month"+month);

                        listdata.setMonth(month);
                        listdata.setYear(year);
                        listdata.setCurrentRead(cuRead);
                        listdata.setPrevUnit(prevRead);
                        listdata.setTotalRoomRent(totalRent);
                        listdata.setPerpersonCost(perPersonCost);
                        listdata.setTotalPerson(totalPeron);
                        listdata.setCurrentTimeAndDate(paidOn);
                        listdata.setDescription(description);


                        firebaselist.add(listdata);
                    }

                    rentAdapter firebaseListAdapter=new rentAdapter(getApplicationContext(),firebaselist);
                    recyclerView.setAdapter(firebaseListAdapter);
                }
            }

            @Override
            public void onCancelled(DatabaseError error) {
                progressView.setVisibility(View.GONE);
                System.out.println(error);
                System.out.println("error");
            }
        });
    }
}

我创建了一个名为 RoomRentData.class 的模型类。我已使用此模型将此数据添加到RecyclerView中。

这是我的模型类代码。

public class RoomRentData {

    private String month;
    private String year;
    private String roomRent;
    private String perUnitCost;
    private String PrevUnit;
    private String CurrentRead;
    private String totalUnitCostt;
    private String totalRoomRent;
    private String totalPerson;
    private String perpersonCost;
    private String description;
    private String currentTimeAndDate;

    public String getCurrentRead() {
        return CurrentRead;
    }

    public String getCurrentTimeAndDate() {
        return currentTimeAndDate;
    }

    public String getDescription() {
        return description;
    }

    public String getMonth() {
        return month;
    }

    public String getPerpersonCost() {
        return perpersonCost;
    }

    public String getPerUnitCost() {
        return perUnitCost;
    }

    public String getPrevUnit() {
        return PrevUnit;
    }

    public String getRoomRent() {
        return roomRent;
    }

    public String getTotalPerson() {
        return totalPerson;
    }

    public String getTotalRoomRent() {
        return totalRoomRent;
    }

    public String getTotalUnitCostt() {
        return totalUnitCostt;
    }

    public String getYear() {
        return year;
    }

    public void setCurrentRead(String currentRead) {
        CurrentRead = currentRead;
    }

    public void setCurrentTimeAndDate(String currentTimeAndDate) {
        this.currentTimeAndDate = currentTimeAndDate;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setMonth(String month) {
        this.month = month;
    }

    public void setPerpersonCost(String perpersonCost) {
        this.perpersonCost = perpersonCost;
    }

    public void setPerUnitCost(String perUnitCost) {
        this.perUnitCost = perUnitCost;
    }

    public void setPrevUnit(String prevUnit) {
        PrevUnit = prevUnit;
    }

    public void setRoomRent(String roomRent) {
        this.roomRent = roomRent;
    }

    public void setTotalPerson(String totalPerson) {
        this.totalPerson = totalPerson;
    }

    public void setTotalRoomRent(String totalRoomRent) {
        this.totalRoomRent = totalRoomRent;
    }

    public void setTotalUnitCostt(String totalUnitCostt) {
        this.totalUnitCostt = totalUnitCostt;
    }

    public void setYear(String year) {
        this.year = year;
    }
}