参考= FirebaseDatabase.getInstance()。getReference(“ Users”)。child(userID);这行会产生错误。我该如何解决?

我想在MessageActivity.java中使用此行,以使用该用户ID来获取用户名和用户的个人资料图片,以从ChatFragment.java放入MessageActivity.java中。 这是我在所有这三个java文件中编写的代码。

该行在MessageActivity.java文件中。

reference = FirebaseDatabase.getInstance().getReference("Users").child(userID);

UserAdapter.java

package com.psb.farmersmarket.Adapter;

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {

    private Context context;
    private List<User> users1;

    public UserAdapter(Context context, List<User> users1){
        this.context = context;
        this.users1 = users1;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType) {

        View view = LayoutInflater.from(context).inflate(R.layout.user_item,parent, false);
        return new UserAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder,int position) {
        final User user = users1.get(position);
        holder.username.setText(user.getUserName());
        holder.profile_image.setImageResource(R.drawable.round_logo);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, MessageActivity.class);
                intent.putExtra("user_id", user.getUserID());
                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return users1.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        public TextView username;
        public ImageView profile_image;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            username = itemView.findViewById(R.id.username2);
            profile_image = itemView.findViewById(R.id.profile_image);
        }
    }

    public void filterList(ArrayList<User> filtered_Names) {
        this.users1 = filtered_Names;
        notifyDataSetChanged();
    }
}

ChatFragment.java

package com.psb.farmersmarket.Fragments;

public class Chats_Fragment extends Fragment {

    private RecyclerView recyclerView;
    private UserAdapter userAdapter;
    private List<User> usersList;

    FirebaseUser fuser;
    DatabaseReference reference;

    private List<String> user_list;
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_chats_,container,false);
        recyclerView = view.findViewById(R.id.chat_recycler);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        fuser = FirebaseAuth.getInstance().getCurrentUser();

        user_list = new ArrayList<>();

        reference = FirebaseDatabase.getInstance().getReference("chats");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                user_list.clear();
                for(DataSnapshot snapshot: dataSnapshot.getChildren()){
                    Chat chat = snapshot.getValue(Chat.class);

                    assert chat != null;
                    if(chat.getSender().equals(fuser.getUid())){
                        user_list.add(chat.getReceiver());
                    }
                    if(chat.getReceiver().equals(fuser.getUid())){
                        user_list.add(chat.getSender());
                    }
                }
                read_chats();
            }

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

            }
        });

        return view;
    }

    private void read_chats() {
        usersList = new ArrayList<>();
        reference = FirebaseDatabase.getInstance().getReference("Users");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                usersList.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                    User user = snapshot.getValue(User.class);
                    for (String ID : user_list){
                        assert user != null;
                        if (user.getUserID().equals(ID)){
                            if(usersList.size() != 0){
                                for (User user1 : usersList){
                                    if(!user.getUserID().equals(user1.getUserID())){
                                        usersList.add(user);
                                    }
                                }
                            }
                            else{
                                usersList.add(user);
                            }
                        }
                    }
                }
                userAdapter = new UserAdapter(getContext(), usersList);
                recyclerView.setAdapter(userAdapter);
            }

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

            }
        });
    }
}

MessageActivity.java

package com.psb.farmersmarket;

public class MessageActivity extends AppCompatActivity {

    CircleImageView profile_image;
    TextView username;

    FirebaseUser firebaseUser;
    DatabaseReference reference;
    ImageButton btn_send;
    EditText text_send;
    MessageAdapter messageAdapter;
    List<Chat> chats;
    RecyclerView recyclerView;

    Intent intent;

    ValueEventListener seenListener;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MessageActivity.this, HomeActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
            }
        });

        recyclerView = findViewById(R.id.recyclerview);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        linearLayoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(linearLayoutManager);

        username = findViewById(R.id.username);
        profile_image = findViewById(R.id.profile_image);
        btn_send = findViewById(R.id.btn_send);
        text_send = findViewById(R.id.text_send);

        intent = getIntent();
        final String userID = intent.getStringExtra("userID");
        firebaseUser = FirebaseAuth.getInstance().getCurrentUser();

        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = text_send.getText().toString();
                if(!msg.equals("")){
                    sendMessage(firebaseUser.getUid(), userID, msg);
                } else {
                    Toast.makeText(MessageActivity.this,"You can't send empty Text Message",Toast.LENGTH_SHORT).show();
                }
                text_send.setText("");
            }
        });

        assert userID != null;
        reference = FirebaseDatabase.getInstance().getReference("Users").child(userID);
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);
                assert user != null;
                username.setText(user.getUserName());
                if(user.getImageURL().equals("default")){
                    profile_image.setImageResource(R.mipmap.ic_launcher);
                }else {
                    Picasso.with(getApplicationContext())
                            .load(user.getImageURL())
                            .placeholder(R.mipmap.ic_launcher)
                            .into(profile_image);
                }

                readMessage(firebaseUser.getUid(), userID, user.getImageURL());
            }

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

            }
        });
        seenMessage(userID);
    }

    private void seenMessage(final String userID){
        reference = FirebaseDatabase.getInstance().getReference("Chats");
        seenListener =reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                    Chat chat = snapshot.getValue(Chat.class);
                    assert chat != null;
                    if(chat.getSender().equals(firebaseUser.getUid()) && chat.getSender().equals(userID)){
                        HashMap <String, Object> hashMap = new HashMap<>();
                        hashMap.put("is seen" , true);
                        snapshot.getRef().updateChildren(hashMap);
                    }
                }
            }

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

            }
        });
    }

    private void sendMessage(String sender, String receiver, String message){
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference();

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("sender", sender);
        hashMap.put("receiver", receiver);
        hashMap.put("message", message);
        hashMap.put("is seen", false);

        reference.child("Chats").push().setValue(hashMap);
    }

    private void readMessage(final String myID,final String userID,final String ImageURL){
        chats = new ArrayList<>();
        reference = FirebaseDatabase.getInstance().getReference("Chats");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                chats.clear();
                for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                    Chat chat = snapshot.getValue(Chat.class);
                    assert chat != null;
                    if(chat.getReceiver().equals(myID) && chat.getSender().equals(userID) ||
                            chat.getReceiver().equals(userID) && chat.getSender().equals(myID)){
                        chats.add(chat);
                    }
                    messageAdapter = new MessageAdapter(MessageActivity.this, chats, ImageURL);
                    recyclerView.setAdapter(messageAdapter);
                }
            }

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

            }
        });
    }

    private void status(String status){
        reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("Status", status);
        reference.updateChildren(hashMap);
    }

    @Override
    protected void onResume() {
        super.onResume();
        status("online");
    }

    @Override
    protected void onPause() {
        super.onPause();
        reference.removeEventListener(seenListener);
        status("offline");
    }
}

这是下面给出的数据库。

enter image description here & the last is UserModel

User.java

package com.psb.farmersmarket.Model;

import com.google.firebase.database.Exclude;
import com.google.firebase.database.IgnoreExtraProperties;
import com.google.firebase.database.PropertyName;

@IgnoreExtraProperties
public class User {
    private String UserName;
    private String UserPhone;
    private String UserDesc;
    private String UserEmail;
    private String UserID;
    private String imageURL;
    private String search;

    public User(String userName,String userPhone,String userDesc,String userEmail, String userID, String imageURL, String search) {
        this.UserName = userName;
        this.UserPhone = userPhone;
        this.UserDesc = userDesc;
        this.UserEmail = userEmail;
        this.UserID = userID;
        this.imageURL = imageURL;
    }

    public User() {
    }

    @PropertyName("name")
    public String getUserName() {
        return UserName;
    }

    @PropertyName("name")
    public void setUserName(String userName) {
        UserName = userName;
    }

    @PropertyName("Phone No")
    public String getUserPhone() {
        return UserPhone;
    }

    @PropertyName("Phone No")
    public void setUserPhone(String userPhone) {
        UserPhone = userPhone;
    }

    @PropertyName("Description")
    public String getUserDesc() {
        return UserDesc;
    }

    @PropertyName("Description")
    public void setUserDesc(String userDesc) {
        UserDesc = userDesc;
    }

    @PropertyName("email")
    public String getUserEmail() {
        return UserEmail;
    }

    @PropertyName("email")
    public void setUserEmail(String userEmail) {
        UserEmail = userEmail;
    }

    @Exclude
    public String getUserID() {
        return UserID;
    }

    @Exclude
    public void setUserID(String userID) {
        UserID = userID;
    }

    @PropertyName("imageURL")
    public String getImageURL() {
        return imageURL;
    }

    @PropertyName("imageURL")
    public void setImageURL(String imageURL) {
        this.imageURL = imageURL;
    }

    public String getSearch() {
        return search;
    }

    public void setSearch(String search) {
        this.search = search;
    }
}

&错误在下面给出

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.psb.farmersmarket, PID: 30143
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.psb.farmersmarket/com.psb.farmersmarket.MessageActivity}: java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:201)
        at android.app.ActivityThread.main(ActivityThread.java:6806)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
     Caused by: java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
        at com.google.firebase.database.DatabaseReference.child(com.google.firebase:firebase-database@@19.3.0:96)
        at com.psb.farmersmarket.MessageActivity.onCreate(MessageActivity.java:98)
        at android.app.Activity.performCreate(Activity.java:7224)
        at android.app.Activity.performCreate(Activity.java:7213)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:201) 
        at android.app.ActivityThread.main(ActivityThread.java:6806) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) 
评论