0

I want my app to know if a user is new or not using GoogleSignInOptions. If the user is new I want them to show Navigation_Drawer as open else close the drawer.

How can I achieve that?

Below is the code that I used for the navigation drawer. But my aim is to know if a user is the first time logging in or a new user and wants to do stuff as required.

Here's my code:

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.material.navigation.NavigationView;
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 de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends AppCompatActivity {
    NavigationView navigationView;
    DrawerLayout drawerLayout;
    GoogleSignInClient mGoogleSignInClient;
    DatabaseReference databaseReference;
    GoogleSignInAccount account;

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

        databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
        

        loadFragment(new MainViewFragment());

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int id = item.getItemId();

                if (id == R.id.nav_mainActivity){
                    startActivity(new Intent(MainActivity.this, MainActivity.class));
                    finish();
                }
                else if (id == R.id.nav_chart) {
                    loadFragment(new PieChartFragment());
                } else if (id == R.id.nav_connect_fb) {
                    Intent i =getPackageManager().getLaunchIntentForPackage("com.facebook.katana");
                    openIntent(i);
                } else if (id == R.id.nav_connect_insta) {
                    openIntent("https://www.instagram.com/prabinchand.007/");
                } else if (id == R.id.nav_connect_linkedin) {
                    openIntent("https://www.linkedin.com/in/prabin-chand-42aa9b111/");
                } else if (id == R.id.nav_connect_website) {
                    openIntent("https://www.prabinchand.com.np/");
                } else if (id == R.id.nav_graph) {
                    loadFragment(new IncomeFragment());
                } else if (id == R.id.nav_logout) {
                    showAlertBox();
                } else if (id == R.id.nav_share) {
                    Toast.makeText(MainActivity.this, "GENERATE_LINK : SHARE MY APP", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "GOTO PLAY_STORE : FEEDBACK", Toast.LENGTH_SHORT).show();
                }
                drawerLayout.closeDrawer(GravityCompat.START);
                return true;
            }
        });
    }

    private void openIntent(String socialMediaLink) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(socialMediaLink));
        startActivity(intent);
    }

    private void openIntent(Intent i){
        Intent intent = new Intent(i);
        startActivity(intent);
    }

    private void showAlertBox() {
        new AlertDialog.Builder(this)
                .setMessage("Do you want to log out ? ")
                .setTitle("Alert !")
                .setIcon(R.drawable.warning)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                                .requestEmail()
                                .build();
                        mGoogleSignInClient = GoogleSignIn.getClient(getApplicationContext(), gso);
                        mGoogleSignInClient.signOut();
                        Toast.makeText(getApplicationContext(), "Logged out", Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(getApplicationContext(), Login.class));
                    }
                }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .show();
    }

    private void requiredByOtherMethods() {
        account = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
        databaseReference = FirebaseDatabase.getInstance().getReference().child("UsersExpense");
    }

    private void findViewByIDS() {
        navigationView = findViewById(R.id.navigationView);
        navigationView.getMenu().getItem(0).setChecked(true);
        navigationView.setItemIconTintList(null);
        drawerLayout = findViewById(R.id.drawerLayout);
    }

    private void loadFragment(Fragment fragment) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.container, fragment);
        ft.commit();
    }

    private void setUserProfileNavHeader() {
        //hook imageView of Navigation Header
        View view = navigationView.getHeaderView(0);
        CircleImageView imageView = (CircleImageView) view.findViewById(R.id.nav_header_imageView);
        //hook textView of Navigation Header
        TextView textView = (TextView) view.findViewById(R.id.nav_header_textView);
        textView.setText(account.getDisplayName());
        //get image URI from user's google account
        Uri imagePic = account.getPhotoUrl();
        Glide.with(this)
                .load(imagePic)
                .placeholder(R.drawable.google)
                .error(R.drawable.google)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .priority(Priority.HIGH)
                .into(imageView);
    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
}

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

1 Answers1

1

When you need to authenticate your users in Firebase with Google, it means that you need to get Google credentials so you can further create a Firebase account. If you need to know if the user signs in for the first time, please note that a GoogleSignInOptions object doesn't contain such information. To solve this, you have to call AuthResult#getAdditionalUserInfo() function that returns an object of type AdditionalUserInfo. Having such an object, you can isNewUser() method which:

Returns whether the user is new or existing.

In Java, you can simply use the code in my answer from the following post:

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Yes, i saw that post before i do post. I didn't get that. I did not find AuthResult. I'm new to programming will you please show me way to do that ? Thanks ! I have integrated google sign in using this doc. https://developers.google.com/identity/sign-in/android/sign-in – prabin chand Dec 13 '22 at 12:51
  • 1
    First, you have to sign in with Google, and right after that with Firebase. The result of the Firebase authentication is an object of type `AuthResult`. If you want to see a concrete example, check this [resource](https://medium.com/firebase-tips-tricks/how-to-create-a-clean-firebase-authentication-using-mvvm-37f9b8eb7336). Here is the corresponding [repo](https://github.com/alexmamo/FirebaseAuthentication). – Alex Mamo Dec 13 '22 at 13:01
  • Hello sir, I have not implemented yet because i was busy in other stuffs. I will let you know when i get home :) – prabin chand Dec 14 '22 at 10:37
  • Ok, looking forward to seeing your feed-back. – Alex Mamo Dec 14 '22 at 10:43
  • Hello sir, I have read your article but couldn't get idea how to implement on my code. I'm new to android studio – prabin chand Dec 15 '22 at 10:50
  • If you have a hard time implementing it, then, please post a new question, here on StackOverflow, using its own [MCVE](https://stackoverflow.com/help/mcve), so I and other Firebase developers can help you. In this way you'll see exactly how to help. – Alex Mamo Dec 15 '22 at 11:01
  • Can I help you with other information regarding the initial problem? – Alex Mamo Dec 15 '22 at 11:01
  • Yes, help me implementing code to know my new user using google authentication – prabin chand Dec 16 '22 at 08:20
  • sir I have added my code to login user using google authentication . Please check it out. – prabin chand Dec 16 '22 at 08:22
  • As requested earlier, If you have a hard time implementing it, then, please post **a new question**, here on StackOverflow, using its own [MCVE](https://stackoverflow.com/help/mcve), so I and other Firebase developers can help you. – Alex Mamo Dec 16 '22 at 08:26
  • Please don't edit the question and add other code, as my answer will become irrelevant. That's the reason why I rolled back your question. – Alex Mamo Dec 16 '22 at 08:26
  • ok i am posting new question now – prabin chand Dec 16 '22 at 08:33
  • Sir, Please check it out https://stackoverflow.com/questions/74821975/how-to-check-for-new-user-when-log-in-with-google-authentication – prabin chand Dec 16 '22 at 08:39
  • Did my answer help? Can I help you with other information regarding the initial question? – Alex Mamo Dec 16 '22 at 08:40
  • yes, you can help me regarding how to implement those code in my code to know if user is new. – prabin chand Dec 16 '22 at 09:22
  • 1
    https://stackoverflow.com/questions/47893328/checking-if-a-particular-value-exists-in-the-firebase-database/47893879. Solved my problem :D – prabin chand Dec 16 '22 at 09:26