我无法从Firebase获得价值。我有两堂课,MainGarden
和Resort
课。我也确实在数据库中导入了google-service json
文件。返回值仅为null
。
MainGarden.java
package com.example.xh3al3r.myapplication2;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.AsyncTask;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.util.Log;
import android.net.wifi.WifiManager;
import android.text.format.Formatter;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.firebase.client.Firebase;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.iid.FirebaseInstanceId;
import javax.annotation.Nonnull;
public class MainGarden extends AppCompatActivity {
TextView textView;
DatabaseReference refmoisture;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_garden);
final TextView moisturevalue = (TextView) findViewById(R.id.textView15);
refmoisture = FirebaseDatabase.getInstance().getReference("Resort");
refmoisture.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot resortSnapsot : dataSnapshot.getChildren()) {
Resort model = resortSnapsot.getValue(Resort.class);
moisturevalue.setText( model.getValues());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
度假村类别
package com.example.xh3al3r.myapplication2;
public class Resort {
private String Moisture;
public Resort(){
}
public Resort(String moisture){
Moisture=moisture;
}
public String getValues() {
return Moisture;
}
public void setValues(String valuess) {
Moisture=valuess;
}
}
我已经附加了数据库的json。我希望getValue
是“水分”,但是我不能。
答案 0 :(得分:1)
使用此代码
refmoisture = FirebaseDatabase.getInstance().getReference().child("Resort").child("Moisture");
refmoisture.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String moisture = dataSnapshot.child("Value").getValue().toString();
moisturevalue.setText( moisture);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
答案 1 :(得分:0)
您可以在代码中进行这些更改
refmoisture = FirebaseDatabase.getInstance().getReference("Resort").child("Moisture");
refmoisture.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exist()){
String value = dataSnapshot.child("Value").getValue().toString();
moisturevalue.setText( value);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
希望它能起作用!