从Firebase获取ID的单个值

时间:2019-03-21 09:38:12

标签: android firebase firebase-realtime-database

在获取到目前为止无法获取的用户ID的值“ rate_perltr”时遇到问题,我已经尝试了所有方法,但仍然出现错误。

    myDatabaseRateFetch = FirebaseDatabase.getInstance().getReference("Customers");

customerName.setOnKeyListener(new View.OnKeyListener(){

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            myDatabaseRateFetch.orderByChild("cust_id").equalTo(7040).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    try
                    {
                        String ratePerLtr = dataSnapshot.getValue(String.class);
                        Rate rate = dataSnapshot.getValue(Rate.class);
                        rate_fetch = rate.getRate_perltr();

                    }catch (Exception e)
                    {
                        Toast.makeText(MainActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                    Toast.makeText(MainActivity.this, ""+databaseError.toString()+"", Toast.LENGTH_SHORT).show();
                }
            });

            rate.setText(Html.fromHtml(" "+ String.valueOf(rate_fetch) +""));
            return false;
        }
    });
}

费率模型类 包com.example.wms;

公开课费率{

private double rate_perltr;

public Rate()
{

}

public Rate(double rate_perltr) {
    this.rate_perltr = rate_perltr;
}

public double getRate_perltr() {
    return rate_perltr;
}

public void setRate_perltr(double rate_perltr) {
    this.rate_perltr = rate_perltr;
}

3 个答案:

答案 0 :(得分:0)

您的Rate模型似乎有问题。无法将您的Firebase数据映射到您的Rate模型。

答案 1 :(得分:0)

尝试这个

 private void onDataChange(DataSnapshot datasnapshot){
    for(DataSnapshot snapshot : datasnapshot.getChildren){
       Rate rateFetch = snapshot.getValue(Rate.class);
       rateF[0] = ratefetch.getRate_perltr();
    }
 }

答案 2 :(得分:0)

尝试一下。如果您只想从Firebase表中获取字段的结果,则可以在onDataChange()方法中执行此操作

public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    Rate r = new Rate(); //   

    try {
      r.setVar((String) dataSnapshot.child("var").getValue()); //var is the firebase field
    } catch (Exception e) {
      r.setVar("whatever you want here");
    }
}

如果要用firebase结果填充模型,请确保实例变量名称与firebase表中的字段匹配,然后可以执行以下操作:

public void onDataChange(@NonNull DataSnapshot datasnapshot){
   for(DataSnapshot snapshot : datasnapshot.getChildren){
      Rate rate = snapshot.getValue(Rate.class);
      //then get any variable you want from rate
   }
}