我对android很新。在调试过程中我没有遇到错误的地方。我能够看到输入的字段值,但在firebase(后端)中数据没有更新。
以下是我的代码:
public class MainActivity extends AppCompatActivity {
private EditText editTextName;
private EditText editTextAddress;
private TextView textViewPersons;
private Button buttonSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
buttonSave = (Button) findViewById(R.id.buttonSave);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAddress = (EditText) findViewById(R.id.editTextAddress);
textViewPersons = (TextView) findViewById(R.id.textViewPersons);
buttonSave.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(android.view.View v) {
//Creating firebase object
Firebase ref = new Firebase(Config.FIREBASE_URL);
//Getting values to store
String name = editTextName.getText().toString().trim();
String address = editTextAddress.getText().toString().trim();
//Creating Person object
Person person = new Person();
//Adding values
person.setName(name);
person.setAddress(address);
//Storing values to firebase
ref.child("Person").setValue(person);
//Value event listener for realtime data update
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
Person person = postSnapshot.getValue(Person.class);
//Adding it to a string
String string = "Name: "+person.getName()+"\nAddress: "+person.getAddress()+"\n\n";
//Displaying it on textview
textViewPersons.setText(string);
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
}
});
}
}
感谢所有帮助。
答案 0 :(得分:2)
尝试通过替换
来更新代码Person person = new Person();
//Adding values
person.setName(name);
person.setAddress(address);
//Storing values to firebase
ref.child("Person").setValue(person);
与
ref.child("Person").setValue(name)