Skip to content
Eric Cheng edited this page Nov 29, 2022 · 23 revisions

when you use these you will see import issues. Hover and use suggested import. In case of conflict, DO NOT USE KOTLIN IMPORT. Always use google import

Page Refresh

Run this AFTER data is pushed to the database. Put intent swap in the run() function.

//import this version of handler
import android.os.Handler;
//...

// Redirect to profile view once done
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //time delay to allow database to update
                //TODO: PUT INTENT SWAP CODE HERE
            }
        }, 300);

User Stuff

User Registration

User Signup. Can redirect intents inside the if else. task.getException() will display why user signup failed. IMPORTANT: REPLACE displayName = "Eric Cheng" with value pulled from text field (must do textfield.getText or whatever inside the if, variables will be out of scope) to set display Name

FirebaseAuth mAuth = FirebaseAuth.getInstance();
        mAuth.createUserWithEmailAndPassword("[email protected]", "password").addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task)
            {
                if (task.isSuccessful()) {
                    System.out.println(getApplicationContext() + "Registration successful!");
                    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

                    String displayName = "Eric Cheng";

                    UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                            .setDisplayName(displayName).build();

                    user.updateProfile(profileUpdates);

                    FirebaseDatabase root;
                    DatabaseReference reference;
                    root = FirebaseDatabase.getInstance();

                    UserModel newUser = new UserModel(user.getUid(),user.getEmail(),user.getDisplayName(), new HashMap<>(), new HashMap<>());
                    reference = root.getReference("users");
                    reference.child(newUser.getUid()).setValue(newUser);
                }
                else {

                    // Registration failed
                    System.out.println(task.getException());
                    System.out.println(
                            getApplicationContext() +
                                    " Registration failed!!"
                                    + " Please try again later");

                }
            }
        });

User Login.

FirebaseAuth mAuth = FirebaseAuth.getInstance();
        mAuth.signInWithEmailAndPassword("[email protected]", "password").addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task)
                    {
                        if (task.isSuccessful()) {
                            System.out.println(getApplicationContext() + "Registration successful!");

                            // if the user created intent to login activity
                            FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                            System.out.println(user.getDisplayName()); 
                            System.out.println(user.getEmail());
                            System.out.println(user.getUid());
                        }
                        else {

                            // Registration failed
                            System.out.println(task.getException());
                            System.out.println(
                                            getApplicationContext() +
                                            " Login failed!!"
                                                    + " Please try again later");
                        }
                    }
                });

User Logout

FirebaseAuth.getInstance().signOut()
  .then(function() {
    // Sign-out successful.
  })
  .catch(function(error) {
    // An error happened
  });

Accessing User info. Can be done anywhere as long as past login/signin flow

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // Name, email address, uid
    String name = user.getDisplayName();
    String email = user.getEmail();
    String uid = user.getUid();
}

Beach Access.

Get list of beaches. Work must be done inside else condition with the List of BeachModels

FirebaseDatabase root = FirebaseDatabase.getInstance();
        root.getReference("beaches").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DataSnapshot> task) {
                if (!task.isSuccessful()) {
                    Log.e("firebase", "Error getting data", task.getException());
                }
                else {
                    GenericTypeIndicator<HashMap<String, BeachModel>> t = new GenericTypeIndicator<HashMap<String,BeachModel>>() {}; //beaches are Id'd by name

                    List<BeachModel> beachList = new ArrayList<>(task.getResult().getValue(t).values());
                    Log.d("firebase", String.valueOf(beachList));
                }
            }
        });

Search for a specific beach by name. case sensitive.
Replace beachNameToSearch with the beach name to search;

String beachNameToSearch = "beach1";
                    FirebaseDatabase root = FirebaseDatabase.getInstance();
                    root.getReference("beaches").child(beachNameToSearch).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<DataSnapshot> task) {
                            if (!task.isSuccessful()) {
                                Log.e("firebase", "Error getting data", task.getException());
                            }
                            else {
                                BeachModel beachResult = task.getResult().getValue(BeachModel.class);
                                System.out.println(beachResult);
                            }
                        }
                    });

Reviews

Create Review. Beach name (first parameter) must match! User Id is auto pulled in. Function will do nothing if user is not logged in when called.

/**
     * Craetes a review tied to a user and a beach
     * @param beachName Must match beach name exactly (BeachModel.getName())
     * @param rating double for how many stars out of 5
     * @param message Optional field. Leave empty string if no message. CANNOT BE NULL
     * @param isAnonymous True if anonymous. False if displayname should be shown
     */
DatabaseHelper.createReview("beach2", 2.3, "I hate this beach!", false);

Delete review. Only works if use rlogged in

/**
     * Deletes reviews
     * @param reviewID id of review. stored in ReviewModel.getId
     * @param beachName name of beach. must match exactly
     */
DatabaseHelper.deleteReview("1667887691369", "beach1");

Pull user model

generates uer model object. user model contains hashmap of trips/reviews

FirebaseDatabase root = FirebaseDatabase.getInstance();

                    root.getReference("users").child(user.getUid()).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<DataSnapshot> task) {
                            if (!task.isSuccessful()) {
                                Log.e("firebase", "Error getting data", task.getException());
                            }
                            else {
                                //User retrieved
                                UserModel result = task.getResult().getValue(UserModel.class);
                                System.out.println(result.getEmail());

                            }
                        }
                    });

Create Trip

must be logged in. NEVER CREATE TRIP OBJECT MANUALLY

DatabaseHelper.createTrip("<startTimeAndDat>", DatabaseHelper.generateRouteFromUSC("<destination address>"), "<beachName>", <corresponding parking lot model>);
Clone this wiki locally