I am new to Android Studio and Firebase.
I am trying to retrive data from Firebase. I have node Orders
and that node has unique id
, choices
and price
.
This is how my Firebase looks like:
my-application0-8b65a
Orders
- Lw4hgcNwuCitXUKHdNh
choices:"Pasta\n"
price:19
- Lw7zID257gZsJN9s0J3
choices:"Shawarma\nPasta\n"
price: 27
I have tried to use addValueEventListener
to retrieve all orders from University, but when I run the app and go to the retreiving page, it goes back to main activity page. I am using listview(id:list_view) to display the data.
public class DataRetrived extends AppCompatActivity {
private DatabaseReference mDatabase;
private ListView mUserList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dataactivity);
mDatabase = FirebaseDatabase.getInstance().getReference();
mUserList = findViewById(R.id.list_view);
final List<Orders> ordersList = new ArrayList<>();
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
ordersList.clear();
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Orders orders = postSnapshot.getValue(Orders.class);
ordersList.add(orders);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: ");
}
});
}
}
Firebase ref = new Firebase(FIREBASE_URL);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
Log.e("Count " ,""+snapshot.getChildrenCount());
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
<YourClass> post = postSnapshot.getValue(<YourClass>.class);
Log.e("Get Data", post.<YourMethod>());
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("The read failed: " ,firebaseError.getMessage());
}
});
First add a reference to node Orders
and then inside onDataChange remove the for loop to be able to retrieve the object Orders
.
Change this:
mDatabase = FirebaseDatabase.getInstance().getReference();
into this:
mDatabase = FirebaseDatabase.getInstance().getReference("Orders");
Then change the onDataChange()
to the following:
public void onDataChange(DataSnapshot snapshot) {
ordersList.clear();
Orders orders = snapshot.getValue(Orders.class);
ordersList.add(orders);
}
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.