firebase.auth.FirebaseUser.getEmail()的java.lang.NullPointerException并说currentUser()返回null

时间:2019-07-11 09:53:38

标签: android firebase android-fragments nullpointerexception firebase-authentication

“在MainActivity中,我对应用程序中的配置文件片段执行片段事务。在Profile中,我使用FirebaseAuth获取当前用户电子邮件地址,然后说getEmail()可能会产生Null Pointer Exception.。但是在MainActivity本身中一个AuthStateListener,如果用户未登录,则应要求用户登录。。但是为什么没有发生..“

“我还阅读了其他答案,这些答案说FirebaseUser的getUid上的NullPointerException返回Null Pointer异常,而这些答案对我没有帮助...” ” 在下面,我发布了mainActivity,然后发布了Profile Fragment 我用箭头<-标记了界线 “

package com.github.chillmonk2.mycollege;


import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;


import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.firebase.ui.auth.AuthUI;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;


import java.util.Arrays;

public class MainActivity extends AppCompatActivity {
    private final static int RC_SIGN_IN = 2;
    private final static String TAG = MainActivity.class.getSimpleName();
    public static  Context contextMain;



    FirebaseAuth mFirebaseAuth;
    FirebaseAuth.AuthStateListener mAuthStateListener;
    final Fragment newsFragment = new NewsFragment();
    final Fragment eventsFragment = new EventsFragment();
    final Fragment peopleFragment = new PeopleFragment();
    final Fragment profileFragment = new ProfileFragment();
    final FragmentManager fm = getFragmentManager();
    Fragment active = newsFragment;
    int code ;
public static String isAdmin = "FALSE";
    @Override
    protected void onStart() {
        super.onStart();
        mFirebaseAuth.addAuthStateListener(mAuthStateListener);
    }
//    MainFragment fragment = new MainFragment();
//
//    FragmentTransaction transaction = getFragmentManager().beginTransaction();
//        transaction.replace(R.id.container, fragment, "MainFragment");
//        transaction.commit();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mFirebaseAuth = FirebaseAuth.getInstance();
        BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
        bottomNav.setOnNavigationItemSelectedListener(navListener);
        contextMain = getApplicationContext();
        //I added this if statement to keep the selected fragment when rotating the device
        /*if (savedInstanceState == null) {
            getFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new NewsFragment()).commit();
        }
        */

        mAuthStateListener = new FirebaseAuth.AuthStateListener() {

            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in

                } else {
                    // User is signed out

                    startActivityForResult(
                            AuthUI.getInstance()
                                    .createSignInIntentBuilder()
                                    .setIsSmartLockEnabled(false)
                                    .setAvailableProviders(Arrays.asList(
                                            new AuthUI.IdpConfig.EmailBuilder().build()
                                    ))
                                    .build(),
                            RC_SIGN_IN);
                }
            }
        };
        fm.beginTransaction().add(R.id.fragment_container, profileFragment, "3").hide(profileFragment).commit(); <--- HERE IS THE TRANSACTION
        fm.beginTransaction().add(R.id.fragment_container, peopleFragment, "2").hide(peopleFragment).commit();
        fm.beginTransaction().add(R.id.fragment_container,eventsFragment, "1").hide(eventsFragment).commit();
        fm.beginTransaction().add(R.id.fragment_container,newsFragment, "0").commit();
        getSupportActionBar().setTitle("News");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        code = requestCode;
        if(requestCode==RC_SIGN_IN)
        {
            if(resultCode==RESULT_OK)
            {
                Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
            }
            else if (resultCode ==RESULT_CANCELED)
            {
                Toast.makeText(this, "Sign in Failed", Toast.LENGTH_SHORT).show();
                finish();
            }
        }

    }



    @Override
    protected void onResume() {
        super.onResume();
        if(mAuthStateListener==null)
        mFirebaseAuth.addAuthStateListener(mAuthStateListener);
        Log.d("MainActivity.class","OnResume Method");
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mAuthStateListener != null) {
            mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
            Log.d("MainActivity.class",mAuthStateListener+"onPause Method Inside");
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.app_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.app_menu:

                AuthUI.getInstance().signOut(this);
                return true;
            case R.id.app_menu_settings:
                Intent intent = new Intent(MainActivity.contextMain,SettingsActivity.class);
                startActivity(intent);
            default:
                return super.onOptionsItemSelected(item);

        }

    }






    private BottomNavigationView.OnNavigationItemSelectedListener navListener =
            new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment = null;

                    switch (item.getItemId()) {
                        case R.id.nav_news:
                            fm.beginTransaction().hide(active).show(newsFragment).commit();
                            getSupportActionBar().setTitle("News");
                            active = newsFragment;
                            return true;
                        case R.id.nav_events:
                            fm.beginTransaction().hide(active).show(eventsFragment).commit();
                            active = eventsFragment;
                            getSupportActionBar().setTitle("Events");
                            return true;
                        case R.id.nav_profile:
                            fm.beginTransaction().hide(active).show(profileFragment).commit();
                            active = profileFragment;
                            getSupportActionBar().setTitle("Profile");
                            return true;

                        case R.id.nav_Meetups:
                            fm.beginTransaction().hide(active).show(peopleFragment).commit();
                            active = peopleFragment;
                            getSupportActionBar().setTitle("People");
                            return true;
                    }


                    return false;
                    }
            };

}

ProfileFragment

package com.github.chillmonk2.mycollege;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.preference.PreferenceManager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore;

import org.w3c.dom.Text;


public class ProfileFragment extends Fragment {
    private FirebaseUser mUser;
    private TextView mUserName;
    private TextView mRegdNo;
    private TextView mEmailText;
    private TextView mBioText;
    private TextView mSkillsText;
    private TextView mAchievementsText;
    private TextView mAcademicsText;
    private TextView mHobbiesText;
    private ImageView mMentorImage;
    String email;
    DbHelper mDb;

    public ProfileFragment()
    {
        //empty Constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Profile");
        View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
        mDb = new DbHelper(MainActivity.contextMain);
        mUser = FirebaseAuth.getInstance().getCurrentUser();
        if(mUser == null)

        email = mUser.getEmail();<------HERE IS THE EXCEPTION
        email = new String();
   //     email = "sk.mannam@gmail.com";
       //int res1 = mDb.insertUser(new Student(),email);
        Log.e("TAG","Current User Email is "+ email);
        ImageView editProfile = rootView.findViewById(R.id.edit_profile);

        editProfile.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(),EditProfile.class);
                startActivity(intent);
            }
        });
        mUserName = rootView.findViewById(R.id.userName);
        mRegdNo = rootView.findViewById(R.id.regdNoBelowName);
        mMentorImage  = rootView.findViewById(R.id.mentorImage);
        mEmailText = rootView.findViewById(R.id.emailText);
        mBioText = rootView.findViewById(R.id.bioText);
        mSkillsText  = rootView.findViewById(R.id.skillsText);
        mAchievementsText  = rootView.findViewById(R.id.achievementsText);
        mAcademicsText = rootView.findViewById(R.id.academicsText);
        mHobbiesText = rootView.findViewById(R.id.hobbiesText);
        Student student = new Student();
     //   Toast.makeText(getActivity(),"Success",Toast.LENGTH_SHORT).show();

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.contextMain);
        if(!prefs.getBoolean("firstTime", false)) {
            // run your one time code
            int res = mDb.insertUser(student,FirebaseAuth.getInstance().getCurrentUser().getEmail());

            if(res!=-1)
            {
                Log.e("TAG",res+" is the result id in shared Preferences");
            }
            else
            {
                Log.e("TAG",res+" is the result id in shared Preferences");
            }



            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("firstTime", true);
            editor.commit();
        }


        UpdateUi();

        return rootView;
    }

    void UpdateUi()
    {
        DbHelper mDbHelper = new DbHelper(getActivity());
        Log.e("TAG","Calling getStudent");
        Student student1 = mDb.getStudent(email);
        Log.e("TAG","Returned from Student");
        mUserName.setText(student1.mSurname+" "+student1.mFirstName+" "+student1.mLastName);
        mRegdNo.setText(student1.mRegdNo);

        if(student1.mMentor.toLowerCase().equals("yes"))
            mMentorImage.setVisibility(ImageView.VISIBLE);
        else
            mMentorImage.setVisibility(ImageView.INVISIBLE);
        mEmailText.setText(student1.getmEmail());
        mBioText.setText(student1.getmBio());
        mSkillsText.setText(student1.getmSkills());
        mAchievementsText.setText(student1.getmAchievements());
        mAcademicsText.setText(student1.getmAcademicInterests());
        mHobbiesText.setText(student1.getmActivites());

    }
    @Override
    public void onResume() {
        super.onResume();
        UpdateUi();
    }
}

如果FirebaseAuth.getCurrentUser正在产生nullPointerException,那么AuthStateListener为什么不要求用户登录。.请帮助...谢谢。.

0 个答案:

没有答案