Varun Kumar Varun Kumar - 4 years ago 92
Android Question

How to get real time update of firebase database?

I'm trying to fetch a single string from my firebase database. Although I don't see any error but when I change the data, it's not reflected. I just want to store a string online in firebase and then retrieve it later.
I'm doing this for an android app. Here's the code of MainActivity. Please tell where am I going wrong.

package sadboy.firebase;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

[public class MainActivity extends AppCompatActivity {][1]

private TextView title;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

title = (TextView)findViewById(R.id.title);
mFirebaseInstance = FirebaseDatabase.getInstance();

mFirebaseDatabase = mFirebaseInstance.getReference("hey");
mFirebaseInstance.getReference("new_title").setValue("Realtime Database");
mFirebaseInstance.getReference("new_title").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {

String appTitle = dataSnapshot.getValue(String.class);
Log.e("Hey", appTitle);
title.setText(appTitle);
}

@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e("Hey", "Failed to read app title value.", error.toException());
}
});


}
}


enter image description here

Find the project here :
https://github.com/heysadboy/Firebase-Sample

Answer Source

Try to use this approach:

public class MainActivity extends AppCompatActivity {

    private TextView title;
    private DatabaseReference mFirebaseDatabase;
    private FirebaseDatabase mFirebaseInstance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        title = (TextView) findViewById(R.id.title);

        mFirebaseInstance = FirebaseDatabase.getInstance();
        mFirebaseDatabase = mFirebaseInstance.getReference();

        mFirebaseDatabase.child("new_title").setValue("Realtime Database");
        mFirebaseDatabase.child("new_title").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String appTitle = dataSnapshot.getValue().toString();
                Log.e("Hey", appTitle);
                title.setText(appTitle);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.e("Hey", "Failed to read app title value.", error.toException());
            }
        });
    }
}

EDIT

I made slight changes to your layout just to make it easier to test the codes. Here are the changes I made:

activity_main.xml

I added an EditText and Button.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="sadboy.firebase.MainActivity">

    <EditText
        android:id="@+id/et_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        android:inputType="text" />

    <Button
        android:id="@+id/bt_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        android:text="SEND" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

MainActivity.java

Once the Send Button's clicked, I took the String from EditText and store it as new_title value at your Firebase Database, while listen to the changes made at new_title and show the value at TextView.

public class MainActivity extends AppCompatActivity {

    private TextView title;
    private EditText etInput;
    private Button btSend;
    private DatabaseReference mFirebaseDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        title = (TextView) findViewById(R.id.title);
        etInput = (EditText) findViewById(R.id.et_input);
        btSend = (Button) findViewById(R.id.bt_send);

        mFirebaseDatabase = FirebaseDatabase.getInstance().getReference();

        btSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String valuetoSend = etInput.getText().toString();
                mFirebaseDatabase.child("new_title").setValue(valuetoSend);
            }
        });

        mFirebaseDatabase.child("new_title").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String appTitle = dataSnapshot.getValue().toString();
                title.setText(appTitle);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.e("Hey", "Failed to read app title value.", error.toException());
            }
        });
    }
}

And here is the result:

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download