martedì 27 dicembre 2016

Firebase Database con Android

In questo post sono indicati i passi per interfacciare Android con i database di Firebase.
Il tutto e' stato ripreso dal tutorial ufficiale



Come per il caso delle notifiche si deve inserire nelle SDK tools Google Play Services e Repository



e si deve aggiungere il file google.json nella directory /app

build.gradle (Project)
--------------------
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'        
        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
--------------------

build.gradle (app)
--------------------
apply plugin: 'com.android.application'
android {
    compileSdkVersion 25    buildToolsVersion "23.0.1"    
    defaultConfig {
    applicationId "com.luca_innocenti.dbfirebase"        
    minSdkVersion 19        
    targetSdkVersion 25        
    versionCode 1        
    versionName "1.0"        
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"    }
    buildTypes {
        release {
            minifyEnabled false            
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'        }
    }
}

dependencies {
    compile  'com.google.firebase:firebase-core:10.0.0'    
    compile  'com.google.firebase:firebase-database:10.0.0'
    compile  'com.google.firebase:firebase-auth:10.0.0'

    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'    })
    compile 'com.android.support:appcompat-v7:25.1.0'    
   compile 'com.android.support:design:25.1.0'    testCompile 'junit:junit:4.12'}

apply plugin: 'com.google.gms.google-services'
--------------------

Si parte creando una basic activity che abbia il nome corrispondente con quella selezionata nel DB




Nella activity sono implementata una lettura ed un update di un campo del DB

per effettuare l'update si devono modificare i permessi del DB. Dato che era una prova ci sono permessi di lettura e scrittura senza limitazioni (Firebase avvisa in modo vistoso che e' una scelta da non fare)



Activity
------------------------------
package com.luca_innocenti.dbfirebase;

import android.os.Bundle;
import android.support.annotation.NonNull;
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.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
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;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

    TextView mConditionTextView;
    Button mButton;
    Button mLogin;
    Button mInsert;

    DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference mConditionRef = mRootRef.child("condition");

    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private static final String TAG = "EmailPassword";



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

        mConditionTextView = (TextView) findViewById(R.id.textView2);
        mButton = (Button) findViewById(R.id.button2);
        mInsert = (Button) findViewById(R.id.button5);
        mLogin = (Button) findViewById(R.id.button4);

        // [START initialize_auth]        mAuth = FirebaseAuth.getInstance();
        // [END initialize_auth]
        // [START auth_state_listener]        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());
                } else {
                    // User is signed out                    Log.d(TAG, "onAuthStateChanged:signed_out");
                }
                // [START_EXCLUDE]                // [END_EXCLUDE]            }
        };
        // [END auth_state_listener]
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }


    @Override    protected void onStart()
    {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);

//qui viene aggiunto il listener, ogni volta che viene modificato il campo di interesse
// il valore modificato viene letto e mostrato nella textview 
        mConditionRef.addValueEventListener(new ValueEventListener() {
            @Override            public void onDataChange(DataSnapshot dataSnapshot) {
                String text = dataSnapshot.getValue(String.class);
                mConditionTextView.setText(text);
            }

            @Override            public void onCancelled(DatabaseError databaseError) {

            }
        });
// nel caso che si prema un
        mButton.setOnClickListener(new View.OnClickListener(){
            @Override            public void onClick(View view) {
              mConditionRef.setValue("Update");
            }

        });

        mInsert.setOnClickListener(new View.OnClickListener(){
            @Override            public void onClick(View view) {
                mConditionRef.setValue("Update");
            }

        });

        mLogin.setOnClickListener(new View.OnClickListener(){
            @Override            public void onClick(View view) {
                signIn("lucainnoc@gmail.com","chiara");
            }

        });


    }

    @Override    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

    private void signIn(String email, String password) {
        Log.d(TAG, "signIn:" + email);


        // [START sign_in_with_email]        mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());

                        // If sign in fails, display a message to the user. If sign in succeeds                        // the auth state listener will be notified and logic to handle the                        // signed in user can be handled in the listener.                        if (!task.isSuccessful()) {
                            Log.d(TAG, "signInWithEmail:failed", task.getException());
                            Toast.makeText(getApplicationContext(), "Fallito",Toast.LENGTH_SHORT).show();
                        }

                        // [START_EXCLUDE]                        if (!task.isSuccessful()) {
                            Log.d(TAG, "signInWithEmail:successo");
                            Toast.makeText(getApplicationContext(), "Riuscito",Toast.LENGTH_SHORT).show();

                        }
                        // [END_EXCLUDE]                    }
                });
        // [END sign_in_with_email]    }


    @Override    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();

        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
------------------------------

E adesso la prova modificando i dati sulla consolle di Firebase ed osservando le modifiche sull'emulatore Android (caricato con una immagine con Play Services)