Here is the image of firebase realtime database updating from from raspberry pi
以下是我的 MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextView tempvalue;
private TextView humidvalue;
private FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
private DatabaseReference mRootReference = firebaseDatabase.getReference();
private DatabaseReference mChildReference = mRootReference.child("user").child("");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tempvalue = (TextView)findViewById(R.id.tempvalue);
humidvalue = (TextView)findViewById(R.id.humidvalue);
}
@Override
protected void onStart() {
super.onStart();
mChildReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String Temperature = dataSnapshot.getValue(String.class);
String Humidity = dataSnapshot.getValue(String.class);
tempvalue.setText(Temperature);
humidvalue.setText(Humidity);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}}
output error while i'm running it into my phone(usb-debugging) *
答案 0 :(得分:0)
因为你听空了。
您的数据库引用如下:
mChildReference= mRootReference.child("user").child("");
这部分
.child("");
正在侦听空节点。因此你的错误
您必须添加您尝试阅读的确切路径。
修改强>
好吧用这个作为参考:
mChildReference= mRootReference.child("user");
并听取这样的值:
mChildReference.addValueEvent(new Value......{
onDataChange(DataSnapshot datasnapshot){
String temprature= datasnapshot.child("Temprature").getValue().toString();
String humidity= datasnapshot.child("Humidity").getValue().toString();
}
})
答案 1 :(得分:0)
要解决此问题,请使用以下代码:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("user");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String humidity = ds.child("Humidity").getValue(String.class);
String temperature = ds.child("Temperature").getValue(String.class);
Log.d("TAG", humidity + " / " + temperature);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(valueEventListener);
它将打印所有物体的湿度和温度。
如果要显示单个对象的值,请使用以下代码:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("user").child("-L6wEaOp58bSnCGUTSMs");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String humidity = dataSnapshot.child("Humidity").getValue(String.class);
String temperature = dataSnapshot.child("Temperature").getValue(String.class);
Log.d("TAG", humidity + " / " + temperature);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(valueEventListener);