Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to use a Firebase Database [Android Real-Time Database]
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context="com.tabian.firebaseaddtodatabase.MainActivity">
<ScrollView
android:id="@+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/prompt_email"
android:inputType="textEmailAddress"
android:maxLines="1"/>
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:imeActionId="@+id/login"
android:imeActionLabel="@string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
/>
<Button
android:id="@+id/email_sign_in_button"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Sign In"
android:textStyle="bold"/>
<Button
android:id="@+id/email_sign_out_button"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Sign out"
android:textStyle="bold"/>
<Button
android:id="@+id/add_item_screen"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Add Items to Database"
android:textStyle="bold"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:hint="Enter a Food"
android:layout_marginTop="20dp"
android:textAlignment="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/add_new_food"/>
<Button
android:text="Add to database"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnAddNewFood"/>
</LinearLayout>
package com.tabian.firebaseaddtodatabase;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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;
/**
* Created by User on 2/5/2017.
*/
public class AddToDatabase extends AppCompatActivity {
private static final String TAG = "AddToDatabase";
private Button mAddToDB;
private EditText mNewFood;
//add Firebase Database stuff
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_to_database_layout);
//declare variables in oncreate
mAddToDB = (Button) findViewById(R.id.btnAddNewFood);
mNewFood = (EditText) findViewById(R.id.add_new_food);
//declare the database reference object. This is what we use to access the database.
//NOTE: Unless you are signed in, this will not be useable.
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
toastMessage("Successfully signed in with: " + user.getEmail());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
toastMessage("Successfully signed out.");
}
// ...
}
};
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
Object value = dataSnapshot.getValue();
Log.d(TAG, "Value is: " + value);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
mAddToDB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onClick: Attempting to add object to database.");
String newFood = mNewFood.getText().toString();
if(!newFood.equals("")){
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
myRef.child(userID).child("Food").child("Favorite Foods").child(newFood).setValue("true");
toastMessage("Adding " + newFood + " to database...");
//reset the text
mNewFood.setText("");
}
}
});
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
//add a toast to show when successfully signed in
/**
* customizable toast
* @param message
*/
private void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tabian.firebaseaddtodatabase">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".AddToDatabase"></activity>
</application>
</manifest>
package com.tabian.firebaseaddtodatabase;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
// UI references.
private EditText mEmail, mPassword;
private Button btnSignIn,btnSignOut, btnAddToDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//declare buttons and edit texts in oncreate
mEmail = (EditText) findViewById(R.id.email);
mPassword = (EditText) findViewById(R.id.password);
btnSignIn = (Button) findViewById(R.id.email_sign_in_button);
btnSignOut = (Button) findViewById(R.id.email_sign_out_button);
btnAddToDatabase = (Button) findViewById(R.id.add_item_screen);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
toastMessage("Successfully signed in with: " + user.getEmail());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
toastMessage("Successfully signed out.");
}
// ...
}
};
btnSignIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String email = mEmail.getText().toString();
String pass = mPassword.getText().toString();
if(!email.equals("") && !pass.equals("")){
mAuth.signInWithEmailAndPassword(email,pass);
}else{
toastMessage("You didn't fill in all the fields.");
}
}
});
btnSignOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mAuth.signOut();
toastMessage("Signing Out...");
}
});
btnAddToDatabase.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddToDatabase.class);
startActivity(intent);
}
});
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
//add a toast to show when successfully signed in
/**
* customizable toast
* @param message
*/
private void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.