使用getCurrentUser firebase auth的android- java.lang.NullPointerException [英] android- java.lang.NullPointerException using getCurrentUser firebase auth

查看:62
本文介绍了使用getCurrentUser firebase auth的android- java.lang.NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Firebase on an Android app; when creating a user in my signupActivity.class I update the currentUser username and want the next activity MenuActivity.class to get the current user Id and email, but I keep getting nullpointerException, here is the error:

 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我在其中创建用户的地方:

my signupClass where I create the user:

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以显示名称和电子邮件

and my OnCreate method in MenuActivity where i call the CurrentUser to display the name and the email

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.

the error happens when calling the txtName.setText(auth.getCurrentUser().getDisplayName().toString().trim()); even though I tested the null with an if statement.

我放了txtName.setText(auth.getCurrentUser().getDisplayName().toString().trim()); 在if语句中,现在名称在第一次启动时不显示,我需要停止并再次启动该应用程序.我如何在第一次调用MenuActivity

i put the txtName.setText(auth.getCurrentUser().getDisplayName().toString().trim()); in an if statement, and now the name doesnt display on the first launch , i need to stop and launch the app again. how can i get the display name at the first call of MenuActivity

推荐答案

您正在使用

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

代替使用此

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

这篇关于使用getCurrentUser firebase auth的android- java.lang.NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆