如何比较数据库数据?

时间:2017-09-16 07:02:58

标签: android firebase

如何编写代码来比较Firebase中的数据?在我的Firebase医疗下是“糖尿病”,当用户想购买药品时,如果用户患有糖尿病,如何让数据库自动比较用户信息,这将不允许用户购买药品?

https://i.stack.imgur.com/vxe2q.png

    DatabaseReference myRef = FirebaseDatabase.getInstance().getReference();
    FirebaseAuth auth = FirebaseAuth.getInstance();
    FirebaseUser mUser = auth.getCurrentUser();
    userID = mUser.getUid();

    btnSubmit.setOnClickListener(this);
    btnCancel.setOnClickListener(this);
}

private void submit(){
    myRef.child("Users");
    myRef.child(userID);
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            UserInformation user = dataSnapshot.getValue(UserInformation.class);

            if(user!=null) {
                if(user.getMedical().equals("Diabetes"))
                    Toast.makeText(getApplicationContext(),"Diabetes",Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(getApplicationContext(),"Not Not Diabetes",Toast.LENGTH_LONG).show();
                myRef.child("Medicines").child("Pain and Fever").child(userID).setValue("Acetaminophen");
                startActivity(new Intent(getApplicationContext(),MainActivity.class));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

用户信息

   public UserInformation(String name, String address, String phone_num,String gender,String country,String medicine,String medical) {
    this.address = address;
    this.name = name;
    this.phone_num = phone_num;
    this.gender = gender;
    this.country = country;
    this.medicine = medicine;
    this.medical = medical;
}

public String getMedical(){return medical;}

public void setMedical(String medical){this.medical = medical;}

2 个答案:

答案 0 :(得分:0)

  DatabaseReference mReference = FirebaseDatabase.getInstance().getReference();      
  FirebaseAuth auth = FirebaseAuth.getInstance();
  FirebaseUser mUser = auth.getCurrentUser();
  // this code will check if user has Diabetes or not
 mReference.child("Users").child(user.getUid()).addValueEventListener(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {

       UserClass user = dataSnapshot.getValue(UserClass.class);

       if(user!=null)
       {
           if(user.medical.equals("Diabetes"))
               Snackbar.make(findViewById(android.R.id.content),"Diabetes",Snackbar.LENGTH_LONG).show();
           else
               Snackbar.make(findViewById(android.R.id.content),"Not Not Diabetes",Snackbar.LENGTH_LONG).show();

       }

   }

   @Override
   public void onCancelled(DatabaseError databaseError) {

   }

});

答案 1 :(得分:-2)

在Databasehalper类

String sql =" SELECT * FROM TABLENAME WHERE Name ='" + datamodel_app.getFood_name()+"'&#34 ;;         cursor = mDatabase.rawQuery(sql,null);           如果(cursor.getCount()&0)

{

//在这里做你的代码。

}

否则{

}