What are the best practices for reading data from Firebase and Inserting in Activity?

1

I'm getting Insert and Retrieve Firebase Data ... But I do not know how to pass the information obtained for some EditTexts, TextViews in various classes ..

Questions:

  

What are the best practices for passing information across   Activity with Firebase?

     

What are the best practices for creating a Java Class just for the   Firebase and streamline the code to fit most   classes?

MainActivity.class

package com.hotelaria.neoris.checkincheckout.activitys;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.hotelaria.neoris.checkincheckout.R;
import com.hotelaria.neoris.checkincheckout.models.objects.Firebase;
import com.hotelaria.neoris.checkincheckout.models.objects.User;

public class MainActivity extends AppCompatActivity {

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

        this.onClickButtonGoToBookingActivity();
    }

    public void onClickButtonGoToBookingActivity(){
        Button btnBookingActivity = findViewById(R.id.buttonBooking);
        btnBookingActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, BookingActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

}

Firebase.class

package com.hotelaria.neoris.checkincheckout.models.objects;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.util.Log;
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.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 com.hotelaria.neoris.checkincheckout.activitys.MainActivity;


public class Firebase {

    private final FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
    private final FirebaseAuth mFirebaseAuth = FirebaseAuth.getInstance();
    private final DatabaseReference mDatabaseReference = mFirebaseDatabase.getReference();

    public void writeNewUser(final Activity activity, final String email, final String password){
        this.mFirebaseAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(activity, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if(task.isSuccessful()) {
                            User user = new User();
                            user.setUsername(email);
                            user.setPassword(password);

                            mDatabaseReference.child("usr/" + mFirebaseAuth.getUid()).setValue(user);

                            Toast.makeText(activity.getApplicationContext(),"SUCESSO, CONTA CADASTRADA!", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(activity.getApplicationContext(),"OPS ACONTECEU ALGUM ERRO...", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    public void signInUser(final Activity activity, String email, String password){
        this.mFirebaseAuth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if(task.isSuccessful()){
                    Toast.makeText(activity.getApplicationContext(),"SUCESSO...", Toast.LENGTH_SHORT).show();
                    activity.getApplicationContext().startActivity(new Intent(activity.getApplicationContext(), MainActivity.class));
                    queryUserData();
                } else {
                    Toast.makeText(activity.getApplicationContext(),"OPS ACONTECEU ALGUM ERRO...", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    private void queryUserData(){
        String userUid = this.mFirebaseAuth.getUid();
        Query queryUser = this.mDatabaseReference.child("usr").orderByKey().equalTo(userUid);

        queryUser.addValueEventListener(new ValueEventListener() {
            MainActivity mMainActivity = new MainActivity();

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot userSnapshot: dataSnapshot.getChildren()){
                    User mDataUser = userSnapshot.getValue(User.class);
                }


            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Getting Post failed, log a message
                Log.w("onCancelled", "loadPost:onCancelled", databaseError.toException());
                // ...
            }
        });

    }
}
    
asked by anonymous 28.05.2018 / 21:48

1 answer

1
  

What are the best practices for creating a Java Class just for the   Firebase and streamline the code to fit most   classes?

I use this class to pull the reference from DatabaseReference and FirebaseAuth

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public final class FirebaseConfig {

    private static DatabaseReference databaseReference;
    private static FirebaseAuth firebaseAuth;

    public static DatabaseReference getFirebaseReference() {
        if (databaseReference == null) {
            FirebaseDatabase.getInstance().setPersistenceEnabled(true);
            databaseReference = FirebaseDatabase.getInstance().getReference();
            databaseReference.keepSynced(true);
        }
        return databaseReference;
    }

    public static FirebaseAuth getFirebaseAuth() {
        if (firebaseAuth == null) {
            firebaseAuth = FirebaseAuth.getInstance();
        }
        return firebaseAuth;
    }

}

In activity if you need to pull the user reference I use:

DatabaseReference databaseReference = FirebaseConfig.getFirebaseReference().child("users");

The same is for authentication:

FirebaseAuth firebaseAuth = FirebaseConfig.getFirebaseAuth();
firebaseAuth.signInWithEmailAndPassword(...
    
28.05.2018 / 22:19