没有CurrentUser检测到时,无法将用户发送到登录活动

时间:2018-12-27 11:57:43

标签: android authentication nullpointerexception firebase-authentication

当我尝试从我的应用程序注销并关闭它并再次打开它时,我遇到了问题。该应用程序在那里崩溃了,我认为是因为MainActivity.class上的 onStart 无法正常工作,所以我花了很多时间来解决这个问题,但是我不能,我需要太多帮助。

这是错误

12-27 19:32:01.753 27788-27788/com.suryaaditya.dissent E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.suryaaditya.dissent, PID: 27788
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
    at com.suryaaditya.dissent.FriendsFragment.onCreateView(FriendsFragment.java:60)
    at android.support.v4.app.Fragment.performCreateView(Fragment.java:2346)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1428)
    at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
    at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
    at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596)
    at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383)
    at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245)
    at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3248)
    at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3200)
    at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:195)
    at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:597)
    at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
    at com.suryaaditya.dissent.MainActivity.onStart(MainActivity.java:113)
    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1392)
    at android.app.Activity.performStart(Activity.java:7157)
    at android.app.ActivityThread.handleStartActivity(ActivityThread.java:2940)
    at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
    at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
    at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1811)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6694)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

此MainActivity

public class MainActivity extends AppCompatActivity {

private Toolbar mToolbar;
private ViewPager myViewPager;
private TabLayout myTabLayout;
private TabsAccessorAdapter myTabsAccessorAdapter;

private FirebaseAuth mAuth;
private DatabaseReference RootRef;

private String currentUserID;


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

    mAuth = FirebaseAuth.getInstance();
    RootRef = FirebaseDatabase.getInstance().getReference();

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

    BottomNavigationView navigationView= findViewById(R.id.bottom_navigation);
    final ChatsFragment chatsFragment = new ChatsFragment();
    final NotificationsFragment notificationsFragment = new NotificationsFragment();
    final FriendsFragment friendsFragment = new FriendsFragment();
    final GroupsFragment groupsFragment = new GroupsFragment();

    navigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

            int id = menuItem.getItemId();
            if (id == R.id.navigation_friends){
                setFragment(friendsFragment);
                return true;
            }
            else if(id == R.id.navigation_group){
                setFragment(groupsFragment);
                return true;
            }
            else  if (id == R.id.navigation_chats){
                setFragment(chatsFragment);
                return true;
            }
            else if(id == R.id.navigation_notif){
                setFragment(notificationsFragment);
                return true;
            }

            return false;
        }
    });


    navigationView.setSelectedItemId(R.id.navigation_friends);
}

private  void setFragment(Fragment fragment){
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.frame, fragment);
    fragmentTransaction.commit();
}

@Override
protected void onStart() {

    super.onStart();

    FirebaseUser currentUser = mAuth.getCurrentUser();

    if (currentUser == null){
        SendUserToLoginActivity();
    }
    else{
        updateUserStatus("online");
        VerifyUserExistence();
    }
}

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


    FirebaseUser currentUser = mAuth.getCurrentUser();


    if (currentUser != null){

        updateUserStatus("offline");
    }

}

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


    FirebaseUser currentUser = mAuth.getCurrentUser();


    if (currentUser != null){

        updateUserStatus("offline");
    }
}

private void VerifyUserExistence() {

    String currentUserID = mAuth.getCurrentUser().getUid();

    RootRef.child("Users").child(currentUserID).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if ((dataSnapshot.child("name").exists())){

            }
            else {
                SendUserToSettingsActivity();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

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);
}

private void SendUserToFindFriendsActivity() {
    Intent findFriendsIntent = new Intent(MainActivity.this , FindFriendsActivity.class);
    startActivity(findFriendsIntent);
}

private void SendUserToSettingsActivity() {
    Intent settingsIntent = new Intent(MainActivity.this , SettingsActivity.class);
    startActivity(settingsIntent);
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {

    super.onCreateOptionsMenu(menu);

    getMenuInflater().inflate(R.menu.option_menu, menu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);

    if (item.getItemId() == R.id.main_logout_option){

        updateUserStatus("offline");

        mAuth.signOut();
        SendUserToLoginActivity();

    }

    if (item.getItemId() == R.id.main_settings_option){

        SendUserToSettingsActivity();

    }

    if (item.getItemId() == R.id.main_create_group_option){

        RequestNewGroup();

    }

    if (item.getItemId() == R.id.main_find_friends_option){
        SendUserToFindFriendsActivity();
    }

    return true;
}

private void RequestNewGroup() {

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.AlertDialog);
    builder.setTitle("Enter Group Name : ");
    final EditText groupNameField = new EditText(MainActivity.this);
    groupNameField.setHint("e.g Dissent");
    builder.setView(groupNameField);

    builder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            String groupName = groupNameField.getText().toString();

            if (TextUtils.isEmpty(groupName)){

                Toast.makeText(MainActivity.this, "Please enter Group Name !" , Toast.LENGTH_SHORT).show();

            }
            else {

                CreateNewGroup(groupName);

            }

        }
    });

    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
{
        @Override
        public void onClick(DialogInterface dialog, int which) {

            dialog.cancel();

        }
    });

    builder.show();

}

private void CreateNewGroup(final String groupName) {

    RootRef.child("Groups").child(groupName).setValue("")
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()){
                        Toast.makeText(MainActivity.this, groupName + " is Created Successfully !", Toast.LENGTH_SHORT).show();
                    }
                }
            });

}

private void updateUserStatus(String state){

    String saveCurrentTime, saveCurrentDate;

    Calendar calendar = Calendar.getInstance();

    SimpleDateFormat currentTime = new SimpleDateFormat("hh:mm a");
    saveCurrentTime = currentTime.format(calendar.getTime());

    SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
    saveCurrentDate = currentDate.format(calendar.getTime());


    HashMap<String , Object> onlineStateMap = new HashMap<>();
    onlineStateMap.put("time", saveCurrentTime);
    onlineStateMap.put("date", saveCurrentDate);
    onlineStateMap.put("state", state);


    currentUserID = mAuth.getCurrentUser().getUid();
    RootRef.child("Users").child(currentUserID).child("userState")
            .updateChildren(onlineStateMap);
}
}

这是FriendsFragment

public class FriendsFragment extends Fragment {

private View FriendsView;
private RecyclerView friendsList ;

private DatabaseReference friendsRef, usersRef ;
private FirebaseAuth mAuth;

private String currentUserID;

public FriendsFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    FriendsView = inflater.inflate(R.layout.fragment_friends, container, false);


    friendsList = (RecyclerView) FriendsView.findViewById(R.id.friends_list);
    friendsList.setLayoutManager(new LinearLayoutManager(getContext()));

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

    friendsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(currentUserID);
    usersRef = FirebaseDatabase.getInstance().getReference().child("Users");

    return FriendsView;
}

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

    FirebaseRecyclerOptions options =
            new FirebaseRecyclerOptions.Builder<Contacts>()
            .setQuery(friendsRef, Contacts.class)
            .build();

    FirebaseRecyclerAdapter<Contacts, FriendsViewHolder> adapter =
            new FirebaseRecyclerAdapter<Contacts, FriendsViewHolder>(options) 
{
                @Override
                protected void onBindViewHolder(@NonNull final FriendsViewHolder holder, int position, @NonNull Contacts model) {

                    String userID = getRef(position).getKey();

                    usersRef.child(userID).addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {

                            if (dataSnapshot.exists()){

                                if (dataSnapshot.child("userState").hasChild("state")) {

                                    String state = dataSnapshot.child("userState").child("state").getValue().toString();
                                    String date = dataSnapshot.child("userState").child("date").getValue().toString();
                                    String time = dataSnapshot.child("userState").child("time").getValue().toString();

                                    if (state.equals("online")){

                                        holder.onlineIcon.setVisibility(View.VISIBLE);
                                    }
                                    else if (state.equals("offline")){

                                        holder.onlineIcon.setVisibility(View.INVISIBLE);
                                    }
                                }
                                else {

                                    holder.onlineIcon.setVisibility(View.INVISIBLE);
                                }

                                if (dataSnapshot.hasChild("image")){

                                    String userImage = dataSnapshot.child("image").getValue().toString();
                                    String profileName = dataSnapshot.child("name").getValue().toString();
                                    String profileStatus = dataSnapshot.child("status").getValue().toString();


                                    holder.userName.setText(profileName);
                                    holder.userStatus.setText(profileStatus);
                                    Picasso.get().load(userImage).placeholder(R.drawable.profile_image).into(holder.profileImage);

                                }
                                else {

                                    String profileName = dataSnapshot.child("name").getValue().toString();
                                    String profileStatus = dataSnapshot.child("status").getValue().toString();

                                    holder.userName.setText(profileName);
                                    holder.userStatus.setText(profileStatus);
                                }
                            }

                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

                }

                @NonNull
                @Override
                public FriendsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {

                    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup,false);

                    FriendsViewHolder viewHolder = new FriendsViewHolder(view);
                    return viewHolder;

                }
            };

        friendsList.setAdapter(adapter);
        adapter.startListening();

}

public static class FriendsViewHolder extends RecyclerView.ViewHolder{

    TextView userName, userStatus;
    CircleImageView profileImage;
    ImageView onlineIcon;

    public FriendsViewHolder(View itemView) {
        super(itemView);

        userName = itemView.findViewById(R.id.user_profile_name);
        userStatus = itemView.findViewById(R.id.user_status);
        profileImage = itemView.findViewById(R.id.user_profile_image);
        onlineIcon = (ImageView) itemView.findViewById(R.id.user_online_status);

    }
}
}

1 个答案:

答案 0 :(得分:0)

问题出在FriendsFragment上。您正在尝试在空对象引用上获取Uid,这意味着在您与FriendsFragment进行交易时,该用户尚未登录。