我是Android应用开发的初学者,我使用Firebase数据库创建了一个聊天应用。我正在使用两部Android手机来测试应用程序,Android三星4.4.2 API 19和三星5.0.1 API 21.该应用程序曾经在两部手机上正常工作。我在CharActivity中添加了一些行以用于通知目的,我运行了应用程序,它在Android Samsung 4.4.2 API 19上运行良好,但在午餐时在Samsung 5.0.1 API 21上崩溃。所以我撤消我所做的所有更改,直到我的应用程序在Samsung 5.0.1 API 21上工作正常。但令人惊讶的是它仍然崩溃!
现在我遇到了Samsung 5.0.1 API 21的问题。每次运行应用程序时,它都会在午餐时崩溃,这就是我遇到的问题。
FATAL EXCEPTION: main
Process: com.example.maalialabdulhafith.nfc_mac, PID: 30357
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
请注意,我的其他Android三星4.4.2 API 19工作正常,并没有崩溃。
FriendsFragment Class(列出我所有朋友的地方)
public class FriendsFragment extends Fragment {
private RecyclerView mFriendsList;
private DatabaseReference mFriendsDatabase;
private DatabaseReference mUsersDatabase;
private FirebaseAuth mAuth;
private String mCurrent_user_id;
private View mMainView;
public FriendsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_friends, container, false);
mFriendsList = (RecyclerView) mMainView.findViewById(R.id.friends_list);
mAuth = FirebaseAuth.getInstance();
mCurrent_user_id = mAuth.getCurrentUser().getUid();
mFriendsDatabase = FirebaseDatabase.getInstance().getReference().child("Friends").child(mCurrent_user_id);
mFriendsDatabase.keepSynced(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDatabase.keepSynced(true);
mFriendsList.setHasFixedSize(true);
mFriendsList.setLayoutManager(new LinearLayoutManager(getContext()));
// Inflate the layout for this fragment
return mMainView;
}
@Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Friends, FriendsViewHolder> friendsRecyclerViewAdapter = new FirebaseRecyclerAdapter<Friends, FriendsViewHolder>(
Friends.class,
R.layout.users_single_layout,
FriendsViewHolder.class,
mFriendsDatabase
) {
@Override
protected void populateViewHolder(final FriendsViewHolder friendsViewHolder, Friends friends, int i) {
//friendsViewHolder.setDate(friends.getDate());
final String list_user_id = getRef(i).getKey();
mUsersDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("name").getValue().toString();
final String userStatus = dataSnapshot.child("status").getValue().toString(); // I added this
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
if(dataSnapshot.hasChild("online")) {
String userOnline = dataSnapshot.child("online").getValue().toString();
friendsViewHolder.setUserOnline(userOnline);
}
friendsViewHolder.setName(userName);
friendsViewHolder.setUserImage(userThumb, getContext());
friendsViewHolder.setUserStatus(userStatus); //<== if you want to show status instead of date
friendsViewHolder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]{"Open Profile", "Send message"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if(i == 0){
Intent profileIntent = new Intent(getContext(), ProfileActivity.class);
profileIntent.putExtra("user_id", list_user_id);
startActivity(profileIntent);
}
if(i == 1){
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("user_id", list_user_id);
chatIntent.putExtra("user_name", userName);
startActivity(chatIntent);
}
}
});
builder.show();
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mFriendsList.setAdapter(friendsRecyclerViewAdapter);
}
public static class FriendsViewHolder extends RecyclerView.ViewHolder {
View mView;
public FriendsViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
/*public void setDate(String date){
TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_status);
userStatusView.setText(date);
}*/
//if you want to display the statuse instead of the date, activite this and comment setDate method
public void setUserStatus(String status) {
TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_status);
userStatusView.setText(status);
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_name);
userNameView.setText(name);
}
public void setUserImage(String thumb_image, Context ctx){
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.user_single_image);
Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.default_avatar).into(userImageView);
}
public void setUserOnline(String online_status) {
ImageView userOnlineView = (ImageView) mView.findViewById(R.id.user_single_online_icon);
if(online_status.equals("true")){
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
}
}
&#13;
聊天班
public class ChatActivity extends AppCompatActivity {
// user id whom we want to chat with
private String mChatUser;
private DatabaseReference mRootRef;
private TextView mTitleView;
private TextView mLastSeenView;
private CircleImageView mProfileImage;
private FirebaseAuth mAuth;
private String mCurrentUserId;
private ImageButton mChatAddBtn;
private ImageButton mChatSendBtn;
private EditText mChatMessageView;
private RecyclerView mMessagesList;
private SwipeRefreshLayout mRefreshLayout; // For Pagination
private final List<Messages> messagesList = new ArrayList<>();
private LinearLayoutManager mLinearLayout;
private MessageAdapter mAdapter;
// For Pagination
private static final int TOTAL_ITEMS_TO_LOAD = 10;
private int mCurrentPage = 1;
private int itemPos = 0;
private String mLastKey = "";
private String mPrevKey = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat2);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
mRootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mCurrentUserId = mAuth.getCurrentUser().getUid();
mChatUser = getIntent().getStringExtra("user_id");
String userName = getIntent().getStringExtra("user_name");
getSupportActionBar().setTitle(userName);
// to display the image in the bar
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View action_bar_view = inflater.inflate(R.layout.chat_custom_bar, null);
actionBar.setCustomView(action_bar_view);
// ---- Custom Action bar Items ----
mTitleView = (TextView) findViewById(R.id.custom_bar_title);
mLastSeenView = (TextView) findViewById(R.id.custom_bar_seen);
mProfileImage = (CircleImageView) findViewById(custom_bar_image);
//mChatAddBtn = (ImageButton) findViewById(R.id.chat_add_btn);
mChatSendBtn = (ImageButton) findViewById(R.id.chat_send_btn);
mChatMessageView = (EditText) findViewById(R.id.chat_message_view);
mAdapter = new MessageAdapter(messagesList);
mMessagesList = (RecyclerView) findViewById(R.id.messages_list);
mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.message_swipe_layout); // pagenation
mLinearLayout = new LinearLayoutManager(this);
mMessagesList.setHasFixedSize(true);
mMessagesList.setLayoutManager(mLinearLayout);
mMessagesList.setAdapter(mAdapter);
loadMessages();
mTitleView.setText(userName);
// showing last time was seen
mRootRef.child("Users").child(mChatUser).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String online = dataSnapshot.child("online").getValue().toString();
String image = dataSnapshot.child("image").getValue().toString();
if(online.equals("true")) {
mLastSeenView.setText("Online");
} else {
GetTimeAgo getTimeAgo = new GetTimeAgo();
long lastTime = Long.parseLong(online);
String lastSeenTime = getTimeAgo.getTimeAgo(lastTime, getApplicationContext());
mLastSeenView.setText(lastSeenTime);
}
//CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.custom_bar_image);
//Picasso.with(i).load(image).placeholder(R.drawable.default_avatar).into(userImageView);
//Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.default_avatar).into(userImageView);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mRootRef.child("Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(mChatUser)){
Map chatAddMap = new HashMap();
chatAddMap.put("seen", false);
chatAddMap.put("timestamp", ServerValue.TIMESTAMP);
Map chatUserMap = new HashMap();
chatUserMap.put("Chat/" + mCurrentUserId + "/" + mChatUser, chatAddMap);
chatUserMap.put("Chat/" + mChatUser + "/" + mCurrentUserId, chatAddMap);
mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError != null){
Log.d("CHAT_LOG", databaseError.getMessage().toString());
}
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mChatSendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendMessage();
}
});
// Swipe/Pull to Refresh for Android RecyclerView
mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
mCurrentPage++;
itemPos = 0;
loadMoreMessages();
}
});
}
// ------------------ LOAD More Messages ------------------
private void loadMoreMessages() {
DatabaseReference messageRef = mRootRef.child("messages").child(mCurrentUserId).child(mChatUser);
Query messageQuery = messageRef.orderByKey().endAt(mLastKey).limitToLast(10);
messageQuery.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages message = dataSnapshot.getValue(Messages.class);
String messageKey = dataSnapshot.getKey();
if (!mPrevKey.equals(messageKey)){
messagesList.add(itemPos++, message);
} else{
mPrevKey=mLastKey;
}
if (itemPos == 1){
mLastKey = messageKey;
}
Log.d("TOTALKEYS", "Last Key: " + mLastKey + "| Prev Key: " + mPrevKey + "| Message Key: " + messageKey );
mAdapter.notifyDataSetChanged();
mRefreshLayout.setRefreshing(false);
mLinearLayout.scrollToPositionWithOffset(10,0);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
// ------------------ LOAD Messages ------------------
private void loadMessages() {
DatabaseReference messageRef = mRootRef.child("messages").child(mCurrentUserId).child(mChatUser);
Query messageQuery = messageRef.limitToLast(mCurrentPage * TOTAL_ITEMS_TO_LOAD);
messageQuery.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages message = dataSnapshot.getValue(Messages.class);
itemPos++;
if (itemPos == 1){
String messageKey = dataSnapshot.getKey();
mLastKey = messageKey;
mPrevKey = messageKey;
}
messagesList.add(message);
mAdapter.notifyDataSetChanged();
mMessagesList.scrollToPosition(messagesList.size () -1);
mRefreshLayout.setRefreshing(false);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void sendMessage() {
String message = mChatMessageView.getText().toString();
if(!TextUtils.isEmpty(message)){
String current_user_ref = "messages/" + mCurrentUserId + "/" + mChatUser;
String chat_user_ref = "messages/" + mChatUser + "/" + mCurrentUserId;
DatabaseReference user_message_push = mRootRef.child("messages")
.child(mCurrentUserId).child(mChatUser).push();
String push_id = user_message_push.getKey();
Map messageMap = new HashMap();
messageMap.put("message", message);
messageMap.put("seen", false);
messageMap.put("type", "text");
messageMap.put("time", ServerValue.TIMESTAMP);
messageMap.put("from", mCurrentUserId);
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref + "/" + push_id, messageMap);
messageUserMap.put(chat_user_ref + "/" + push_id, messageMap);
mChatMessageView.setText("");
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError != null){
Log.d("CHAT_LOG", databaseError.getMessage().toString());
}
}
});
}
}
}
&#13;
对我来说没有意义的是,它如何在一台设备上运行而在另一台设备上运行?我很感激一个详细的答案。提前谢谢!
鸣谢:我在Youtube上从惊人的TVAC Studio学到了这段代码。
答案 0 :(得分:0)
用户未登录。 将您的代码更改为以下
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null && !firebaseUser.getUid().isEmpty()) {
// all OK
} else {
// repeat the authentication process again
}
答案 1 :(得分:0)
正如tim4dev所解释的那样,您尚未使用任何特定用户登录。如果您尚未创建用户,请转到firebase控制台并允许注册类型。它们就像电子邮件和密码验证,电话号码验证,匿名等。一旦启用了其中一个选项,您就可以使用auth类注册并在之后登录/登录。在设备上使用用户帐户登录后,只有
mCurrent_user_id = mAuth.getCurrentUser().getUid();
语句工作并返回非null id。
希望它能解决问题。