I'm writing an app that allows users to collaborate on inventory by uploading data to a database hosted by firebase. I can write data to it no problem, however it only wants to let me retrieve data when an event is triggered, such as the data being changed. All I want is to retrieve a string that I've saved to the database and set it as the text value of a TextView element on my page, and I want this to happen when I click a button. How do I do this?
Here's the code for the page where the user writes the data:
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
String dbLocationTag = location.getText().toString();
String itemInfo = "Item Description: " + itemDescription.getText().toString() + "\n" + "Job Number: " + jobNumber.getText().toString();
mDatabase.setValue(dbLocationTag, itemInfo);
Context context = getApplicationContext();
final Intent inventoryHomeScreen = new Intent();
inventoryHomeScreen.setClass(context, Inventory_Management.class);
startActivity(inventoryHomeScreen);
}
});
Here's where I would like to be able to retrieve the data:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory__view__item);
final TextView itemInfo = (TextView) findViewById(R.id.itemInfoTextView);
final Button viewButton = (Button) findViewById(R.id.viewButton);
assert viewButton != null;
viewButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//I would like to set the text of itemInfo to the data I just wrote
}
});
}
You need to use addListenerForSingleValueEvent() to retrieve data
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("<childName>").addListenerForSingleValueEvent(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here in child you need to mention your child node name
If you want to get change of whole database, simply remove child so it look like mDatabase.addListenerForSingleValueEvent()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With