0

First, I will tell the flow of my App.
Login Screen(SignInActivity.java) -> Enter details(MainActivity.java) ->Home Screen(HomeScreenActivity.java)
In my app, I have used Firebase Authentication and Firebase Database. When the user is new, then it should go to Main Activity from SignInActivity where user enters his name, a short description and his hobby. The details are stored in Firebase Database and then HomeScreenActivity opens where user details are shown in Recycler View.

But currently what happens is when same user does login again, it again asks user for details. I want to check if users Google Account already exists in Firebase Auth, then instead of asking details, it should directly go to HomeScreenActivity.

I checked many answers on StackOverflow, but nothing seems to work. One thing that i tried was additionalUserInfo.isNewUser but in this app crashes when user does login again, showing null error where I display user details in HomeScreenActivity.

SignInActivity.java

private void firebaseAuthWithGoogle(String idToken) {
        AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
        mAuthIn.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d(TAG, "SignInWithCredential:success");
                            startActivity(new Intent(SignInActivity.this, MainActivity.class));
                            finish();

                        } else {
                            // If sign in fails, display a message to the user.
                            Toast.makeText(SignInActivity.this, "Authentication Failed", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

MainActivity.java

public void init() {
        hobbiesContinueButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name=user.getText().toString().trim();
                String desc=description.getText().toString().trim();
                String hobby=spinner.getSelectedItem().toString();
                String image="default";
                String thumbnail="default";
                if(!TextUtils.isEmpty(name))
                {
                    FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
                    assert currentUser != null;
                    String userId=currentUser.getUid();

                    User user=new User(name,hobby,desc,image,thumbnail);
                    dbRef.child(userId).setValue(user);
                    startActivity(new Intent(getApplicationContext(), HomeScreenActivity.class));
                    finish();
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Enter a name",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }  

HomeScreenActivity.java

dbRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                imgvw = headerView.findViewById(R.id.imageView);
                imgvw.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //to open gallery
                        Intent galleryIntent = new Intent();
                        galleryIntent.setType("image/*");
                        galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);
                    }
                });

                TextView nameDrawer = findViewById(R.id.navName);
                TextView descDrawer = findViewById(R.id.navDescription);
                User change = snapshot.getValue(User.class);
                assert change != null;
                //This is where null error occurs
                nameDrawer.setText(change.getUserName());
                descDrawer.setText(change.getUserDesc());

                //change profile picture
                image= Objects.requireNonNull(snapshot.child("userImage").getValue()).toString();
                Log.d(TAG, "onComplete: "+image);
                if(!image.equals("default")){
                    Picasso.get().load(image).placeholder(R.drawable.avatar).into(imgvw);
                }
            }


  
Kushagra
  • 89
  • 11

1 Answers1

0

The solution is to save your user details in shared preferences for the first time when the user sign in , then after the user signs out and sign it again , you get data from shared preferences and set them directly to your edittexts Try this Code :

   ///save sharedpreferences
        SharedPreferences sharedPreferences = 
       getSharedPreferences("prefs",Context.MODE_PRIVATE);
      SharedPreferences.Editor editor = sharedPreferences.edit();
      editor.putString("username","put here your username"); //
      editor.putString("email","put your email here"); //you can add more details
      editor.apply();


        ///get sharedpreferences
        SharedPreferences sharedPreferences1 = 
        getSharedPreferences("prefs",Context.MODE_PRIVATE);
        String username = sharedPreferences1.getString("username","");
        String email = sharedPreferences1.getString("email","");
        
         //then here set the valeus from sharedpreferences to your edittexts
Taki
  • 3,290
  • 1
  • 16
  • 41
  • No, i have written in question if user log in's again after logout. Your solution works when user has not logged out. Just reopening the app. I want that my app should not ask user again for details if he has logged out and then again logging in. – Kushagra Jul 19 '20 at 22:15
  • i guess i understood your question and i have editted the post , check it again – Taki Jul 19 '20 at 22:22
  • Thanks for quick reply. I am not quite familiar with SharedPreferences but i know its for saving data. But i am using Firebase Database to store Users data and later process it. Even if it works with Shared Preferences, it would be inconvenient to store same data in two places. – Kushagra Jul 19 '20 at 22:31
  • Sharedpreferences and firebase database are two different things , Sharedpreferences is to save simple light data like login details thats it is convenient i guess but firebase database is to store mutliple users details for example – Taki Jul 19 '20 at 22:34
  • I am sorry but i tried a lot. I am not able to do that. Can you point out to where should i put your code? – Kushagra Jul 20 '20 at 00:12
  • in the block where the user wants to save the data , get the username and email and save them inside the sharedpreferences , then in your oncreate get the values and set them to your edittexts – Taki Jul 20 '20 at 00:14