Home Android Firebase Android Firebase : Spinner – Save,Retrieve then Show

Android Firebase : Spinner – Save,Retrieve then Show

Android Firebase : Spinner – Save,Retrieve then Show


Language :
Platform :
Type :
Owner :
Main Category :
Sub Category :
License :
Price :


Hello guys.Here is the source for our android firebase spinner tutorial.This is what we do :

  • Save to Firebase from edittext in android.
  • Retrieve data.
  • Show in a spinner

What Is Firebase Realtime Database? Firebase Realtime database is a database backend as a service Cloud hosted solution that gives us the platform to build rich apps.Normally we are used to making HTTP requests to read or write data against our servers.But not in Firebase.It uses synchronization technology that allows it to be realtime,but still performant. Main Feautures?

  • Its realtime .
  • Platfrom Independent.
  • Easy Access Control.
  • It’s a NoSQL solution and is heavily optimized for performance.
  • Has Offline capability .
  • Its User Friendly.

NB/= For demo,firebase setup and more explanations please watch our video tutorial below :

[embedyt] http://www.youtube.com/watch?v=3BHP-iEZG3k[/embedyt]

 

Section 1 : Our Model class : Spacecraft.java

package com.tutorials.hp.firebasespinner.m_Model;

/**
 * Created by Oclemy on 6/20/2016 for ProgrammingWizards Channel and http://www.camposha.com.
 */
public class Spacecraft {

    String name;

    public Spacecraft() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

  Section 2 : Our FirebaseHelper class

  • Basic CRUD class.
  • We perform Reads and Writes to Firebase
  • We return an arraylist
package com.tutorials.hp.firebasespinner.m_FireBase;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseException;
import com.google.firebase.database.DatabaseReference;
import com.tutorials.hp.firebasespinner.m_Model.Spacecraft;

import java.util.ArrayList;

/**
 * Created by Oclemy on 6/20/2016 for ProgrammingWizards Channel and http://www.camposha.com.
 */
public class FirebaseHelper {

    DatabaseReference db;
    Boolean saved=null;

    public FirebaseHelper(DatabaseReference db) {
        this.db = db;
    }

    //SAVE
    public  Boolean save(Spacecraft spacecraft)
    {
        if(spacecraft==null)
        {
            saved=false;
        }else
        {
            try
            {
                db.child("Spacecraft").push().setValue(spacecraft);
                saved=true;
            }catch (DatabaseException e)
            {
                e.printStackTrace();
                saved=false;
            }
        }

        return saved;
    }

    //READ
    public ArrayList<String> retrieve()
    {
        final ArrayList<String> spacecrafts=new ArrayList<>();

        db.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                fetchData(dataSnapshot,spacecrafts);
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                fetchData(dataSnapshot,spacecrafts);

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        return spacecrafts;
    }

    private void fetchData(DataSnapshot snapshot,ArrayList<String> spacecrafts)
    {
        spacecrafts.clear();
        for (DataSnapshot ds:snapshot.getChildren())
        {
            String name=ds.getValue(Spacecraft.class).getName();
            spacecrafts.add(name);
        }

    }
}

 Section 3 : Our MainActivity class

  • Our launcher activity
  • Show Input Dialog
  • Initialize UI views
package com.tutorials.hp.firebasespinner;

import android.app.Dialog;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.tutorials.hp.firebasespinner.m_FireBase.FirebaseHelper;
import com.tutorials.hp.firebasespinner.m_Model.Spacecraft;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    DatabaseReference db;
    FirebaseHelper helper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        Spinner sp= (Spinner) findViewById(R.id.sp);

        //SETUP FB
        db=FirebaseDatabase.getInstance().getReference();
        helper=new FirebaseHelper(db);

        sp.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,helper.retrieve()));

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 displayInputDialog();
            }
        });
    }

    //DISPLAY INPUT DILAOG
     private void displayInputDialog()
     {
         Dialog d=new Dialog(this);
         d.setTitle("Firebase database");
         d.setContentView(R.layout.input_dialog);

         final EditText nameTxt= (EditText) d.findViewById(R.id.nameEditText);
         Button saveBtn= (Button) d.findViewById(R.id.saveBtn);

         //SAVE
         saveBtn.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 //GET DATA
                 String name=nameTxt.getText().toString();

                 //set data
                 Spacecraft s=new Spacecraft();
                 s.setName(name);

                 //SAVE
                 if(name != null && name.length()>0)
                 {
                     if(helper.save(s))
                     {
                         nameTxt.setText("");
                     }

                 }else
                 {
                     Toast.makeText(MainActivity.this, "Name Cannot Be Empty", Toast.LENGTH_SHORT).show();
                 }

             }
         });

         d.show();
     }

}

  Section 3 : Our Layouts 1.InputDialog.xml

  • Layout for our Input Dialog
<?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">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize"
        android:orientation="vertical"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:paddingTop="50dp">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/nameLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/nameEditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:hint= "Name" />
        </android.support.design.widget.TextInputLayout>

        <Button android:id="@+id/saveBtn"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Save"
            android:clickable="true"
            android:background="@color/colorAccent"
            android:layout_marginTop="40dp"
            android:textColor="@android:color/white"/>

    </LinearLayout>

</LinearLayout>

 

Leave a Comment