NullPointerException FirebaseUser.getUid()'对空对象的引用

时间:2018-11-29 11:35:48

标签: android firebase firebase-authentication

这是错误 E / AndroidRuntime:致命异常:main                   流程:com.example.jams.socialnetwork,PID:15878                   java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.jams.socialnetwork / com.example.jams.socialnetwork.MainActivity}:java.lang.NullPointerException:尝试调用虚拟方法'java.lang.String com。 google.firebase.auth.FirebaseUser.getUid()”上的空对象引用                       在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2690)                       在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2755)                       在android.app.ActivityThread.-wrap12(ActivityThread.java)                       在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1495)                       在android.os.Handler.dispatchMessage(Handler.java:102)                       在android.os.Looper.loop(Looper.java:154)                       在android.app.ActivityThread.main(ActivityThread.java:6196)                       在java.lang.reflect.Method.invoke(本机方法)                       在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:888)                       在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)

原因:java.lang.NullPointerException:尝试调用虚拟方法

在空对象引用上

'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()'                       在com.example.jams.socialnetwork.MainActivity.onCreate(MainActivity.java:52)                       在android.app.Activity.performCreate(Activity.java:6698)                       在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)                       在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2643)

我尝试了许多猛虎,但不明白我在哪里做错了

java>       包com.example.jams.socialnetwork;

                     import android.content.Intent;
                     import android.support.annotation.NonNull;
                     import android.support.design.widget.NavigationView;
                     import android.support.v4.widget.DrawerLayout;
                     import android.support.v7.app.ActionBarDrawerToggle;
                     import android.support.v7.app.AppCompatActivity;
                      import android.os.Bundle;
                      import android.support.v7.widget.RecyclerView;
                     import android.support.v7.widget.Toolbar;
                      import android.view.MenuItem;
                      import android.view.View;
                     import android.widget.TextView;
                       import android.widget.Toast;

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

               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 com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends AppCompatActivity {

    private NavigationView navigationView;
    private Toolbar mToolbar;
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle actionBarDrawerToggle;
    private RecyclerView postList;

    private CircleImageView NavProfileImage;
    private TextView NavProfileUserName;

    private FirebaseAuth mAuth;
    private DatabaseReference UserRef;
    String currentUserID;


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


        mAuth = FirebaseAuth.getInstance();
        currentUserID = mAuth.getCurrentUser().getUid();
        UserRef = FirebaseDatabase.getInstance().getReference().child("Users");


        mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle("Home");




        drawerLayout = (DrawerLayout) findViewById(R.id.drawable_layout);
        actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout,R.string.drawer_Open, R.string.drawer_Close);
        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        navigationView = (NavigationView) findViewById(R.id.navigation_view);

        View navView = navigationView.inflateHeaderView(R.layout.navigation_header);

        NavProfileImage = (CircleImageView) navView.findViewById(R.id.nav_profile_image);
        NavProfileUserName = (TextView) navView.findViewById(R.id.nav_user_full_name);






        UserRef.child(currentUserID).addValueEventListener(new ValueEventListener()
        {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot)
            {
               if (dataSnapshot.exists())
               {
                   String fullname = dataSnapshot.child("fullname").getValue().toString();
                   String image = dataSnapshot.child("profileimage").getValue().toString();

                   NavProfileUserName.setText(fullname);
                   Picasso.with(MainActivity.this).load(image).placeholder(R.drawable.profile).into(NavProfileImage);
               }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError)
            {

            }
        });




        navigationView.setNavigationItemSelectedListener
                (new NavigationView.OnNavigationItemSelectedListener()
                {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item)
                    {
                        UserMenuSelector(item);
                        return false;
                    }
                });




    }





    @Override
    protected void onStart()
    {
        super.onStart();

        FirebaseUser currentUser =mAuth.getCurrentUser();

        if(currentUser==null)
        {
            SendUserToLoginActivity();
        }

        else
        {
            CheckUserExistence();
        }


    }

    private void CheckUserExistence()
    {
        final String current_user_id = mAuth.getCurrentUser().getUid();

        UserRef.addValueEventListener(new ValueEventListener()
        {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot)
            {
                if (!dataSnapshot.hasChild(current_user_id))
                {
                    SendUserToSetupActivity();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError)
            {

            }
        });



    }

    private void SendUserToSetupActivity()
    {
        Intent SetupIntent = new Intent(MainActivity.this,SetupActivity.class);
        SetupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(SetupIntent);
        finish();


    }








    private void SendUserToLoginActivity()
    {
        Intent LoginIntent = new Intent(MainActivity.this,LoginActivity.class);
        LoginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(LoginIntent);
        finish();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        if(actionBarDrawerToggle.onOptionsItemSelected(item))
        {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }





    private void UserMenuSelector(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.nav_profile:
                Toast.makeText(this,"Profile",Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_post:
                Toast.makeText(this,"Post",Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_home:
                Toast.makeText(this,"Home",Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_friends:
                Toast.makeText(this,"friends",Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_find_friends:
                Toast.makeText(this,"find friends",Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_messages:
                Toast.makeText(this,"message",Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_settings:
                Toast.makeText(this,"Settings",Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_logout:
                mAuth.signOut();
                SendUserToLoginActivity();
                break;
        }
    }


    }

2 个答案:

答案 0 :(得分:1)

崩溃的根本原因:firebaseauth.getinstance()。getcurrentuser()返回null 因此,在访问firebaseauth.getinstance()。getcurrentuser()之前,请添加一个空检查。

还可以通过官方Firebase文档交叉检查您的Firebase实施:https://firebase.google.com/docs/auth/android/anonymous-auth

答案 1 :(得分:0)

从Firebase中找不到

“用户”列,因此您的应用程序处于崩溃状态。