Firebase getUid()函数只返回NULL

时间:2017-07-31 05:45:59

标签: java android firebase firebase-realtime-database

PostListFragment由我的应用程序中的其他片段扩展。我需要当前用户的uid,但它总是返回null。当我尝试运行我的应用程序时,我总是收到错误:

FATAL EXCEPTION: main
Process: com.example.cleeg.squad, PID: 8524
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
     at com.example.cleeg.squad.fragments.PostListFragment.getUid(PostListFragment.java:162)
     at com.example.cleeg.squad.fragments.MyPostsFragment.getQuery(MyPostsFragment.java:19)
     at com.example.cleeg.squad.fragments.PostListFragment.onActivityCreated(PostListFragment.java:76)

我试图找出为什么这是在线,但我只是变得更加困惑,我真的不知道如何解决它。 函数getUid()位于代码的底部。

public abstract class PostListFragment extends Fragment {

private static final String TAG = "PostListFragment";

private DatabaseReference mDatabaseReference;

private FirebaseRecyclerAdapter<Post, PostViewHolder> mAdapter;
private RecyclerView mRecycler;
private LinearLayoutManager mManager;

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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View rootView = inflater.inflate(R.layout.fragment_all_posts, container, false);

    mDatabaseReference = FirebaseDatabase.getInstance().getReference();

    mRecycler = (RecyclerView) rootView.findViewById(R.id.messages_list);
    mRecycler.setHasFixedSize(true);

    return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // Set up Layout Manager, reverse layout
    mManager = new LinearLayoutManager(getActivity());
    mManager.setReverseLayout(true);
    mManager.setStackFromEnd(true);
    mRecycler.setLayoutManager(mManager);

    // Set up FirebaseRecyclerAdapter with the Query
    Query postsQuery = getQuery(mDatabaseReference);
    mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(Post.class, R.layout.item_post,
            PostViewHolder.class, postsQuery) {
        @Override
        protected void populateViewHolder(final PostViewHolder viewHolder, final Post model, final int position) {
            final DatabaseReference postRef = getRef(position);

            // Set click listener for the whole post view
            final String postKey = postRef.getKey();
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Launch PostDetailActivity
                    Intent intent = new Intent(getActivity(), PostDetailActivity.class);
                    intent.putExtra(PostDetailActivity.EXTRA_POST_KEY, postKey);
                    startActivity(intent);
                }
            });

            // Determine if the current user has liked this post and set UI accordingly
            if (model.stars.containsKey(getUid())) {
                viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_24);
            } else {
                viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_outline_24);
            }

            // Bind Post to ViewHolder, setting OnClickListener for the star button
            viewHolder.bindToPost(model, new View.OnClickListener() {
                @Override
                public void onClick(View starView) {
                    // Need to write to both places the post is stored
                    DatabaseReference globalPostRef = mDatabaseReference.child("posts").child(postRef.getKey());
                    DatabaseReference userPostRef = mDatabaseReference.child("user-posts").child(model.uid).child(postRef.getKey());

                    // Run two transactions
                    onStarClicked(globalPostRef);
                    onStarClicked(userPostRef);
                }
            });
        }
    };
    mRecycler.setAdapter(mAdapter);
}

private void onStarClicked(DatabaseReference postRef) {
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Post p = mutableData.getValue(Post.class);
            if (p == null) {
                return Transaction.success(mutableData);
            }

            if (p.stars.containsKey(getUid())) {
                // Unstar the post and remove self from stars
                p.starCount = p.starCount - 1;
                p.stars.remove(getUid());
            } else {
                // Star the post and add self to stars
                p.starCount = p.starCount + 1;
                p.stars.put(getUid(), true);
            }

            // Set value and report transaction success
            mutableData.setValue(p);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Transaction completed
            Log.d(TAG, "postTransaction:onComplete:" + databaseError);
        }
    });
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (mAdapter != null) {
        mAdapter.cleanup();
    }
}

public String getUid() {
    return FirebaseAuth.getInstance().getCurrentUser().getUid();
}

public abstract Query getQuery(DatabaseReference databaseReference);

}

2 个答案:

答案 0 :(得分:1)

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // User is authenticated and now you can access uesr's properties as followings
    mUserID = user.getUid();
} else {
    // User is authenticated. So, let's try to re-authenticate
    AuthCredential credential = EmailAuthProvider
        .getCredential("user@example.com", "password1234");

    // Prompt the user to re-provide their sign-in credentials
    user.reauthenticate(credential)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            Log.d(TAG, "User re-authenticated.");
        }
    });
}

您可以在以下Firebase文档中获取有关它的详细信息:https://firebase.google.com/docs/auth/android/manage-users

答案 1 :(得分:0)

崩溃是因为没有用户链接,即getCurrentUser()为null。在获取用户标识之前,请让用户拥有该用户。

if (FirebaseAuth.getInstance().getCurrentUser() != null) {
        mUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
} else {
        //login or register screen
}