android-java.lang.NullPointerException使用getCurrentUser firebase auth

时间:2018-04-16 20:37:59

标签: java android firebase firebase-realtime-database firebase-authentication

我在Android应用上使用Firebase;在我的signupActivity.class中创建用户时,我更新了currentUser用户名,并希望下一个活动MenuActivity.class获取当前用户ID和电子邮件,但我一直收到nullpointerException,这是错误:

 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sadainfo.apppfe/com.android.pfe.activity.MenuActivity}: java.lang.NullPointerException
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2245)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2295)
     at android.app.ActivityThread.access$700(ActivityThread.java:150)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
     at android.os.Handler.dispatchMessage(Handler.java:99)
     at android.os.Looper.loop(Looper.java:176)
     at android.app.ActivityThread.main(ActivityThread.java:5279)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:511)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
     at dalvik.system.NativeStart.main(Native Method)

Caused by: java.lang.NullPointerException
     at com.android.pfe.activity.MenuActivity.onCreate(MenuActivity.java:89)
     at android.app.Activity.performCreate(Activity.java:5267)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)

我创建用户的signupClass

public class SignupActivity extends AppCompatActivity {
    private static final String TAG ="SignupActivity" ;
    private EditText mEmail,mPseudo,mMdp;
    private Button mEnregistrer;
    private FirebaseAuth auth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        auth=FirebaseAuth.getInstance();
        final ArrayList<String> arrayList;
        final ArrayAdapter<String> adapter;
        final EditText txtinput ;
        setContentView(R.layout.activity_signup);
        ListView listView = (ListView)findViewById(R.id.ListV);
        String [] item = {};
        arrayList = new ArrayList<>(Arrays.asList(item));
        adapter = new ArrayAdapter<String>(this,R.layout.list_item,R.id.txtitem,arrayList);
        listView.setAdapter(adapter);
        txtinput=(EditText)findViewById(R.id.txtinput);
        Button btadd = (Button)findViewById(R.id.btadd);
        btadd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newitem = txtinput.getText().toString();
                arrayList.add(newitem);
                adapter.notifyDataSetChanged();
            }
        });

        setContentView(R.layout.activity_signup);
        mEmail=(EditText)findViewById(R.id.email);
        mPseudo=(EditText)findViewById(R.id.pseudo);
        mMdp=(EditText)findViewById(R.id.mdp);
        mEnregistrer=(Button) findViewById(R.id.enregCompte);

    mEnregistrer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             final String email = mEmail.getText().toString().trim();
            String password = mMdp.getText().toString().trim();
             final String pseudo =mPseudo.getText().toString().trim();

            if (TextUtils.isEmpty(pseudo)) {
                Toast.makeText(getApplicationContext(), "Entrer le pseudo", Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(email)) {
                Toast.makeText(getApplicationContext(), "Entrer une adresse mail", Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(password)) {
                Toast.makeText(getApplicationContext(), "Entrer un mot de passe", Toast.LENGTH_SHORT).show();
                return;
            }
            if (password.length() < 6) {
                Toast.makeText(getApplicationContext(), "mot de passe trop court, veuillez rentrer un minimum de 6 caractères", Toast.LENGTH_SHORT).show();
                return;
            }


            //créating account
            auth.createUserWithEmailAndPassword(email, password)
                    .addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            //progressBar.setVisibility(View.GONE);

                            if (task.isSuccessful()) {

                                Toast.makeText(SignupActivity.this, "Inscription réussie " + task.isSuccessful(), Toast.LENGTH_SHORT).show();

                                FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                                if(user!=null) {
                                    //changer les infos utilisateur
                                    UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                                            .setDisplayName(pseudo)
                                            .build();

                                    user.updateProfile(profileUpdates)
                                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                                @Override
                                                public void onComplete(@NonNull Task<Void> task) {
                                                    if (task.isSuccessful()) {
                                                        Log.d(TAG, " profile updated.");
                                                    }
                                                }
                                            });
                                    User uti = new User();
                                    uti.addUser(user.getUid(), pseudo, email);

                                    startActivity(new Intent(SignupActivity.this, MenuActivity.class));
                                    finish();
                                }
                           //*****************************************************
                            } else {
                                Toast.makeText(SignupActivity.this, "erreur d'inscription" + task.getException().getMessage(),
                                        Toast.LENGTH_SHORT).show();


                            }
                        }
                    });
        }
    });

    }

和我在MenuActivity中的OnCreate方法,我调用CurrentUser来显示名称和电子邮件

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //get firebase auth instance
        auth = FirebaseAuth.getInstance();
        mHandler = new Handler();

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        navigationView = (NavigationView) findViewById(R.id.nav_view);

        // Navigation view header
        navHeader = navigationView.getHeaderView(0);
        txtName = (TextView) navHeader.findViewById(R.id.name);
        txtWebsite = (TextView) navHeader.findViewById(R.id.job);
     //   imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg);
        imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);

        if(auth.getCurrentUser()!=null) {

            if(auth.getCurrentUser().getDisplayName()!=null) {
            txtName.setText(auth.getCurrentUser().getDisplayName().toString().trim());
        }                txtWebsite.setText(auth.getCurrentUser().getEmail().toString().trim());

        }
        profil=(TextView) navHeader.findViewById(R.id.Profil);
        profil.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent insc = new Intent(MenuActivity.this,ProfilActivity.class);
                startActivity(insc);

            }
        });
        // load toolbar titles from string resources
        activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);

        // load nav menu header data
        //loadNavHeader();

        navigationView.getMenu().getItem(4).setActionView(R.layout.menu_dot);
        // initializing navigation menu
        setUpNavigationView();

        if (savedInstanceState == null) {
            navItemIndex = 0;
            CURRENT_TAG = TAG_HOME;
            loadHomeFragment();
        }
    }

调用txtName.setText(auth.getCurrentUser().getDisplayName().toString().trim());时发生错误 即使我用if语句测试了null。

编辑:我把txtName.setText(auth.getCurrentUser().getDisplayName().toString().trim()); 在if语句中,现在名称在第一次启动时没有显示,我需要再次停止并启动应用程序。如何在第一次调用MenuActivity

时获取显示名称

1 个答案:

答案 0 :(得分:-1)

您正在使用

txtName.setText(auth.getCurrentUser().getDisplayName().toString().trim());

改为使用

txtName.setText(auth.getInstance().getCurrentUser().getDisplayName().toString().trim());