简体   繁体   中英

Retrieve data from firebase database on button click

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()

You can use addValueEventListener() to retrieve data when an event is triggered.

In your onClick() method you can write :

DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();

// In the database whenever any data is changed then the below code snipped is going to be executed.
mDatabase.child("<dbLocationTag>").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                // the changed value is going to be stored into the dataSnapshot
                // to retrieve value from dataSnapshot we write

                String value = dataSnapshot.getValue(String.class);
                mValueView.setText(value);

                // NOTE: if you've multiple childs of same node then you can use Map to display all of them : EG: 
                /*Map<String, String> map = dataSnapshot.getValue(Map.class);
                String val1 = map.get("val1");
                String val2 = map.get("val2");
                String val3 = map.get("val3");
                Log.v("TAG", "Value 1 "+val1);
                Log.v("TAG", "Value 2 "+val2);
                Log.v("TAG", "Value 3 "+val3);
*/
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

                mValueView.setText(firebaseError.toString());

            }
        });
addButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        DatabaseReference mRef = mDatabaseReference.getDatabase().getReference("users");
        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    Log.d(TAG, "" + ds.getKey());
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        };
    }
});
mRef.addListenerForSingleValueEvent(valueEventListener);

The above method worked for me. Hope it helps for you, too.

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