简体   繁体   中英

Retrieve data from FireBase database in android, java by searchin with an ID

I tried to implement a code in java to retrieve data from database( firebase) by searching with an ID and show it in the form.

这是我的android项目的视图 In here i have already saved some data and now when i type the id, it need to show the data of the id in this same form.

btnShow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            searchID = txtid.getText().toString().trim();
            DatabaseReference readRef = FirebaseDatabase.getInstance().getReference();
            DatabaseReference dref = readRef.child("Student");
            Query query = dref.orderByChild("id").equalTo(searchID);
            query.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if(dataSnapshot.hasChildren()){
                        txtID.setText((dataSnapshot.child("id").getValue().toString()));
                        txtName.setText((dataSnapshot.child("name").getValue().toString()));
                        txtAdd.setText((dataSnapshot.child("address").getValue().toString()));
                        txtConNo.setText((dataSnapshot.child("conNo").getValue().toString()));
                    }
                    else
                        Toast.makeText(getApplicationContext(),"No Source to Display",Toast.LENGTH_SHORT).show();

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });
        }
    });

This is the java code i implemented to do that. But when i run the program and give the correct id in database it is always showing as "No source to display"( There are data in my database and save function is working properly)

数据库

I am a beginner in android studio and firebase. Please modify the above code and tell me how can i search by ID.

Thankyou.

Try the following:

if(dataSnapshot.exists()){
    for(DataSnapshot ds : dataSnapshot.getChildren()){
       txtID.setText((ds.child("id").getValue().toString()));
       txtName.setText((ds.child("name").getValue().toString()));
       txtAdd.setText((ds.child("address").getValue().toString()));
       txtConNo.setText((ds.child("conNo").getValue().toString()));
    }
}

Your reference is at node Student therefore you need to loop and then use ds to access the attributes. Also, don't forget to check for errors inside onCancelled :

@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
    Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM