从firebase检索数据到textview

时间:2017-08-30 18:29:30

标签: android firebase firebase-realtime-database

在我的应用中,我有两项活动。第一个活动将数据保存到Firebase,第二个活动检索数据。我可以毫无问题地存储数据,但是当尝试检索数据时,它不会出现在TextView

这是我检索数据的代码

 public class DataOne extends NavigationApp {
  public TextView nameOne, ageOne, addressOne, shcoolOne;
     private DatabaseReference mDatabase;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);



    Firebase.setAndroidContext(this);
    mDatabase = FirebaseDatabase.getInstance().getReference().child("/DetailOne/");

    TextView NameStudent = (TextView) findViewById(R.id.Name);
    TextView agestudent = (TextView) findViewById(R.id.age);
    TextView addressstudent = (TextView) findViewById(R.id.address);
    TextView schoolstudent = (TextView) findViewById(R.id.school);

    nameOne = (TextView) findViewById(R.id.WriteName);
    ageOne = (TextView) findViewById(R.id.WriteAge);
    addressOne = (TextView) findViewById(R.id.WriteAddress);
    shcoolOne = (TextView) findViewById(R.id.WriteSchool);

    Button map = (Button) findViewById(R.id.mapOne);
    map.setOnClickListener(new View.OnClickListener() {
        @Override

        public void onClick(View view) {
            Intent MapOne= new Intent(DataOne.this, DataOneMap.class);

            startActivity(MapOne);
        }
    });

    mDatabase.addValueEventListener(new ValueEventListener() {


        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                Detail detail = dataSnapshot.getValue(Detail.class);

                String name = detail.getName();
                String age = detail.getAge();
                String address = detail.getAddress();
                String school = detail.getSchool();

                nameOne.setText(name);
                ageOne.setText(age);
                addressOne.setText(address);
                shcoolOne.setText(school);


            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

            // [START_EXCLUDE]
            System.out.println("The read failed: " + databaseError.getMessage());
        }
    });
}
}

当我运行应用时,TextView显示为空。

Firebase结构:

firebase

3 个答案:

答案 0 :(得分:1)

从此

更改此行代码
Detail detail = dataSnapshot.getValue(Detail.class);

到此

Detail detail = postSnapshot.getValue(Detail.class);

答案 1 :(得分:0)

尝试改变这一点:

mDatabase =FirebaseDatabase.getInstance().getReference().child("/DetailOne/");

对此:

mDatabase = FirebaseDatabase.getInstance().getReference().child("DetailOne");

在此之后判断它是否有效

答案 2 :(得分:0)

请从

更改您的模型类
Detail detail = dataSnapShot.getValue(Detail.class);

Detail detail = postSnapShot.getValue(Detail.class);

同时检查您的模型类Detail是否所有方法和变量都获得了public访问修饰符..如果private将其更改为public

例如,如果你有

private String name;

更改为

public String name;