Blog para desarrollo de aplicaciones en Android, aprende paso a paso como crear aplicaciones.

Usamos cookies propias y de terceros que entre otras cosas recogen datos sobre sus hÔbitos de navegación para mostrarle publicidad personalizada y realizar anÔlisis de uso de nuestro sitio.
Si continúa navegando consideramos que acepta su uso. OK MÔs información | Y mÔs

Como crear una Base de Datos en Android utilizando Firebase

Como crear una Base de Datos en Android utilizando Firebase

Android Studio - Database Firebase

Hola amigos en esta ocasión les traigo este tutorial de como aprender a crear una aplicación utilizando la Base de datos de Firebase con este ejemplo claro podra aplicarlo a sus aplicaciones.


Crear Proyecto Database Firebase Tutorial (AquĆ­)

Vamos a crear nuestro proyecto para desarrollar este ejemplo y aprender a utilizar la Base de datos de Firebase.

FireBase

Para aƱadir nuestro proyecto en Firebase puede ver los siguientes enlaces.

- Chat Message Firebase

Design Database Firebase Tutorial

Vamos a crear el diseño de nuestro ejemplo para tener un poco mas claro de como podemos implementarlo en nuestra aplicación.

Añadiremos un archivo al que le pondremos people_list_row.xml en el cual se presentara la información que vayamos agregando.

<?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">

    <TextView
        android:id="@+id/personNameTv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <TextView
        android:id="@+id/personPhone"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Ahora en el activity_main.xml agregaremos lo siguiente.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/LinearLayout1">
        <ListView
            android:id="@+id/peopleList"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </ListView>
    </RelativeLayout>
    <LinearLayout
        android:id="@+id/LinearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="40px"
        android:layout_above="@+id/LinearLayout2"
        android:gravity="center">
        <EditText
            android:id="@+id/fullNameEditText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:textSize="16dp"
            android:layout_weight="1"
            android:hint="Nombre Completo" />
        <EditText
            android:id="@+id/phoneNumberEditText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="Numero Telefono"
            android:layout_weight="1"
            android:textColor="#000000"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/LinearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical"
        android:background="#36FFFFFF">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <Button
                android:id="@+id/loadBtn"
                android:text="Load data"
                android:textColor="#000000"
                android:textStyle="bold"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <Button
                android:id="@+id/addBtn"
                android:text="Add item"
                android:textColor="#000000"
                android:textStyle="bold"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <Button
                android:id="@+id/updateBtn"
                android:text="Update item"
                android:textColor="#000000"
                android:textStyle="bold"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
            <Button
                android:id="@+id/deleteBtn"
                android:text="Delete item"
                android:textColor="#000000"
                android:textStyle="bold"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
        <Button
            android:id="@+id/findBtn"
            android:text="Find item"
            android:textColor="#000000"
            android:textStyle="bold"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>
</RelativeLayout>

Código Database Firebase Tutorial

Vamos a crear el código de nuestra aplicación y quedaría de la siguiente manera. Agregaremos varias clases la primera sera para llevar la estructura de datos de los que vamos ingresando.

public class Person {

    private String fullName;
    private int phoneNumber;

    public Person(){

    }

    public Person(String fullName,  int phoneNumber) {
        this.fullName = fullName;
        this.phoneNumber = phoneNumber;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public int getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(int phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
}

Seguimos con la siguiente clase.

import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by Amal on 12/02/2017.
 */

public class CustomListAdapater extends BaseAdapter {

    private ArrayList names;
    private ArrayList phoneNumbers;
    private AppCompatActivity activity;

    private int x=0;


    public CustomListAdapater(ArrayList names,ArrayList phoneNumbers,AppCompatActivity activity){
        this.names=names;
        this.phoneNumbers=phoneNumbers;
        this.activity=activity;
    }

    @Override
    public int getCount() {
        return names.size();
    }

    @Override
    public Object getItem(int i) {
        return names.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view =  LayoutInflater.from(activity.getApplicationContext()).inflate(R.layout.people_list_row,viewGroup,false);
        ((TextView)view.findViewById(R.id.personPhone)).setText(String.valueOf(phoneNumbers.get(i)));
        ((TextView)view.findViewById(R.id.personNameTv)).setText(names.get(i));
        return view;
    }
}

Y por ultimo agregaremos en nuestro MainActivity el siguiente código.


import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;

import com.google.firebase.database.ChildEventListener;
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.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.Iterator;

public class MainActivity extends AppCompatActivity {

    private DatabaseReference myDatabaseReference;
    private String personId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);
        myDatabaseReference=FirebaseDatabase.getInstance().getReference("Person");
        personId= myDatabaseReference.push().getKey();
        
        (findViewById(R.id.addBtn)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addPerson(((EditText)findViewById(R.id.fullNameEditText)).getText().toString(),
                        Integer.parseInt(((EditText)findViewById(R.id.phoneNumberEditText)).getText().toString()));
            }
        });
        (findViewById(R.id.updateBtn)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updatePerson(((EditText)findViewById(R.id.fullNameEditText)).getText().toString(),Integer.parseInt(((EditText)findViewById(R.id.phoneNumberEditText)).getText().toString()));
            }
        });
        (findViewById(R.id.deleteBtn)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                removePerson("first added");
            }
        });
        (findViewById(R.id.loadBtn)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                readData();
            }
        });

        (findViewById(R.id.findBtn)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                findPerson(((EditText)findViewById(R.id.fullNameEditText)).getText().toString());
            }
        });



    }

    private void addPerson(String name,int phoneNumber){
        Person person = new Person(name,phoneNumber);
        myDatabaseReference.child(personId).setValue(person);
    }
    private void updatePerson(String name,int phoneNumber){
        myDatabaseReference.child(personId).child("fullName").setValue(name);
        myDatabaseReference.child(personId).child("phoneNumber").setValue(phoneNumber);
    }
    private void removePerson(String name){
        myDatabaseReference.child(personId).removeValue();
    }
    private void readData(){
        final ArrayList names = new ArrayList<>();
        final ArrayList phoneNumbers = new ArrayList<>();
        myDatabaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Iterable snapshotIterator = dataSnapshot.getChildren();
                Iterator iterator = snapshotIterator.iterator();
                while((iterator.hasNext())){
                    Person value = iterator.next().getValue(Person.class);
                    names.add(value.getFullName());
                    phoneNumbers.add(value.getPhoneNumber());
                    ((CustomListAdapater)(((ListView)findViewById(R.id.peopleList)).getAdapter())).notifyDataSetChanged();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        ((ListView)findViewById(R.id.peopleList)).
                setAdapter(new CustomListAdapater(names,phoneNumbers,this));
    }
    private void findPerson(String name){
        Query deleteQuery = myDatabaseReference.orderByChild("fullName").equalTo(name);
        deleteQuery.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                Iterable snapshotIterator = dataSnapshot.getChildren();
                Iterator iterator = snapshotIterator.iterator();
                while((iterator.hasNext())){
                    Log.d("Item found: ",iterator.next().getValue().toString()+"---");
                }
            }

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

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

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

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.d("Item not found: ","this item is not in the list");
            }
        });
    }

}

Y con esto ejecutaremos nuestra aplicación para ver el resultado.

Crear Emulador AVD (AquĆ­)

Vamos a crear nuestro emulador para ver nuestra aplicación de Base de datos utilizando Firebase en nuestro aplicación Android.

Si tienes alguna duda déjanos tu opinión en un comentario. Gracias.

No hay comentarios:

Publicar un comentario