What are Good Practices for Reading Firebase Data and Inserting into Activitys?

Asked

Viewed 226 times

1

I’m getting Insert and Recover Firebase Data... But I I don’t know how to pass the information obtained for some Edittexts, Textviews in several classes..

Questions:

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

What are the best practices for creating a Java Class for Firebase and streamline the code, so it serves for 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());
                // ...
            }
        });

    }
}
  • 1

    It has several free courses on the internet of how to use Firebase, I answered a question from you a little while ago and the code was not even checked and adjusted with the use of the buttons. I recommend the guide of firebase itself

  • @Gaspar sends me the link to the question, because I’m not finding.

1 answer

0


What are the best practices for creating a Java Class for Firebase and streamline the code, so it serves for most classes?

I use this class to pull the reference from the DatabaseReference and of 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 users reference I use:

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

The same goes for authentication:

FirebaseAuth firebaseAuth = FirebaseConfig.getFirebaseAuth();
firebaseAuth.signInWithEmailAndPassword(...
  • you do not create any method in the Firebase class, for data search? This you do "manually" within the Activity class is this? Beauty, I can insert and take the information, but how do I insert a result for example in an Edittext, taking into account that there are several Activitys that will contain the same information.

  • When I have this situation I create a helper class of a data model (for example users = Usuariohelper.class) and within this class I put one alteration in the firebase, to quest of firebase It’s asynchronous, so it’s not very cool to create a dynamic class to search for data at that point and continue the code like other databases. Then when it is a search in the firebase database I create each Activity a Listener and remove the Listener in the onDestroy from Activity. So if you have a contact list for example, a user has changed the name, will change Automat

  • There was a case that happened to me that was demanding a lot of mobile resource to search and recover data from Firebase because of this specific situation of a value be used by VARIOUS ACTIVITIES, it was then that I made a gambiarra to place a Istener in a Service in a specific fact for each user, so the value was always there to recover if it changed, it would automatically change

  • ball show, got it.. Could you give me an example of this Helper in your answer above? Is this part makes reference to my question too, where I doubt.

  • In the above case it had a value in the variable status inside Users that certain situation that status was "0", another situation was "1", so I put a Liener in the Service who was always listening to the change in databaseReference.child("users").child("idUser").child("status"); and in the onDataChange The value changed for all other activities

  • Yes, this class I use for Activationservice.class, and this to Userhelper.class, I was the author of this whole :D bullshit, use it as you wish

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.