我对Null Point Exception

时间:2019-11-02 18:56:42

标签: android android-studio

我试图创建Uid代码,但遇到有关NullPointException的问题:


    package com.example.musicmates;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;


import com.google.android.material.navigation.NavigationView;
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.google.firebase.database.annotations.NotNull;
import com.squareup.picasso.Picasso;

import java.util.Set;

import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private RecyclerView postList;
private Toolbar mToolbar;
private CircleImageView NavProfileImage;
private TextView NavProfileUserName;
private ActionBarDrawerToggle actionBarDrawerToggle;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef;
String currentUserID;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        navigationView = findViewById(R.id.navigaition_view);

        mAuth = FirebaseAuth.getInstance();
        currentUserID = mAuth.getCurrentUser().getUid();

        UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");


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

        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);
        View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
        NavProfileImage = navView.findViewById(R.id.nav_profile_image);
        NavProfileUserName = navView.findViewById(R.id.nav_profile_full_name);


        UsersRef.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.get().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 menuItem) {
                UserMenuSelector(menuItem);
                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();

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

            @Override
            public void onCancelled(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(@NonNull MenuItem item) {
        if(actionBarDrawerToggle.onOptionsItemSelected(item)){
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void UserMenuSelector(MenuItem menuItem) {
        switch (menuItem.getItemId()){
            case R.id.nav_post:
                Toast.makeText(this, "Add new post", Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_profile:
                Toast.makeText(this, "Profile", 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_message:
                Toast.makeText(this, "Message", Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_setting:
                Toast.makeText(this, "Setting", Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_logout:
                Toast.makeText(this, "Log out", Toast.LENGTH_SHORT).show();
                mAuth.signOut();
                SendUserToLoginActivity();
                break;
        }
    }
}


  

2019-11-02 11:46:36.860 16810-16810 / com.example.musicmates   E / AndroidRuntime:致命异常:main       程序:com.example.musicmates,PID:16810       java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.musicmates / com.example.musicmates.MainActivity}:   java.lang.NullPointerException:尝试调用虚拟方法   “ java.lang.String com.google.firebase.auth.FirebaseUser.getUid()”   空对象引用           在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)           在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)           在android.app.ActivityThread.-wrap11(未知来源:0)           在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1593)           在android.os.Handler.dispatchMessage(Handler.java:105)           在android.os.Looper.loop(Looper.java:164)           在android.app.ActivityThread.main(ActivityThread.java:6541)           在java.lang.reflect.Method.invoke(本机方法)           在com.android.internal.os.Zygote $ MethodAndArgsCaller.run(Zygote.java:240)           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)        原因:java.lang.NullPointerException:尝试调用虚拟方法'java.lang.String   com.google.firebase.auth.FirebaseUser.getUid()”在空对象上   参考           在com.example.musicmates.MainActivity.onCreate(MainActivity.java:56)           在android.app.Activity.performCreate(Activity.java:6975)           在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)           在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)

1 个答案:

答案 0 :(得分:0)

在您的应用build.gradle中,将其添加到您的依赖项中

compile 'com.google.firebase:firebase-auth:x.x.x'(最新版本)

将此内容添加到onCreate内的navigationView = findViewById(R.id.navigaition_view);

mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
         currentUserID = mAuth.getCurrentUser().getUid();   
        }else{
             finish();
             SendUserToLoginActivity();
   }

onstart中删除检查方法。清理并重建您的项目,让我知道它是否有效。