无法使用自定义适配器从 firebase 获取数据,“Сan 不能为子 () 中的参数 pathString 传递 null”

Can't get data from firebase using custom adapter, "Сan't pass null for argument pathString in child ()"

我不太明白自定义数组适配器是如何工作的,但其中一个已经在我的项目中工作了,所以我决定也将它添加到其他列表中。 我不确定,但我认为问题出在从 addFriends 到 Message

的重新查看中
private void getFriends(){
    DatabaseReference isRef = FirebaseDatabase.getInstance().getReference().child("Users").child(uid).child("Friends");
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if(listTemp.size() > 0){listTemp.clear();}
            for (DataSnapshot ds : snapshot.getChildren()){
                addFriends addFriend = ds.getValue(addFriends.class);
                if(addFriend != null){  //переоброзование в вид с чатом
                    String message = "put message is here, don`t forget. @chatID";
                    String nameuser = addFriend.username1;
                    String userID = addFriend.uid2;
                    Message mainFriends = new Message(message, nameuser, userID);
                    if(mainFriends != null) {
                        listTemp.add(mainFriends);
                    }
                }
            }
            adapter.notifyDataSetChanged();
        }

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

        }
    };
    isRef.addValueEventListener(valueEventListener);
}

问题正好指向private void getFriends(){ 问题:

Unable to start activity ComponentInfo{esport.inyourlife.myproektlink.Profile.Friends}: java.lang.NullPointerException: Can't pass null for argument 'pathString' in child() android.app.ActivityThread.performLaunchActivity

还有我借用的适配器代码:

package #.Consts;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.snackbar.Snackbar;

import java.util.ArrayList;

import esport.inyourlife.insport.R;

public class CustomAdapter extends ArrayAdapter<Message> implements View.OnClickListener{
    private ArrayList<Message> dataSet;
    Context mContext;

    // View lookup cache
    private static class ViewHolder {
        TextView txtName;
        TextView txtType;
        ImageView info;
    }

    public CustomAdapter(ArrayList<Message> data, Context context) {
        super(context, R.layout.msg_center_item, data);
        this.dataSet = data;
        this.mContext=context;

    }

    @Override
    public void onClick(View v) {

        int position=(Integer) v.getTag();
        Object object= getItem(position);
        Message dataModel=(Message) object;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        Message dataModel = getItem(position);
        // Check if an existing view is being reused, otherwise inflate the view
        ViewHolder viewHolder; // view lookup cache stored in tag

        if (convertView == null) {

            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.msg_center_item, parent, false);
            viewHolder.txtName = convertView.findViewById(R.id.tvDescr);
            viewHolder.txtType = convertView.findViewById(R.id.tvPrice);
            viewHolder.info = convertView.findViewById(R.id.uImgg);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.txtName.setText(dataModel.nameuser);
        viewHolder.txtType.setText(dataModel.message);
        // Return the completed view to render on screen
        return convertView;
    }
}

项目:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal">
    <androidx.cardview.widget.CardView
        android:id="@+id/cardViewsdd"
        android:layout_width="86dp"
        android:layout_height="83dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        app:cardBackgroundColor="@color/common_google_signin_btn_text_dark_disabled"
        app:cardCornerRadius="50dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageView
            android:id="@+id/uImgg"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:src="@mipmap/ic_launcher_round" />
    </androidx.cardview.widget.CardView>
    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="5dp"
        android:layout_weight="1"
        android:orientation="vertical">
        <TextView
            android:id="@+id/tvDescr"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text=""
            android:textSize="20sp">
        </TextView>
        <TextView
            android:id="@+id/tvPrice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="18dp"
            android:text="">
        </TextView>
    </LinearLayout>
</LinearLayout>

如果所有 Friends.class 代码都能派上用场

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.google.android.material.tabs.TabLayout;
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 java.util.ArrayList;
import java.util.List;

import esport.inyourlife.insport.Consts.CustomAdapter;
import esport.inyourlife.insport.Consts.CustomFriends;
import esport.inyourlife.insport.Consts.Message;
import esport.inyourlife.insport.Consts.addFriends;
import esport.inyourlife.insport.R;
import esport.inyourlife.insport.findtest;

public class Friends extends AppCompatActivity {
    private final FirebaseAuth mAuth = FirebaseAuth.getInstance();
    private ArrayAdapter adapter;
    private ArrayList<Message> listTemp;
    private String uid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friends);
        setTitle("Друзья");
        assert getSupportActionBar() != null;   //null check
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getFriends();
        TabLayout tabs = findViewById(R.id.tabsFriends);
        LinearLayout freq = findViewById(R.id.support_layout);
        ListView friendList = findViewById(R.id.FriendList);
        tabs.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                if (position == 0) {
                    freq.setVisibility(View.GONE);
                    friendList.setVisibility(View.VISIBLE);
                    getFriends();
                }
                 else if (position == 1) {
                    freq.setVisibility(View.VISIBLE);
                    friendList.setVisibility(View.GONE);
                    getReqs();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        ImageButton add = findViewById(R.id.addFriendToAll);
        add.setOnClickListener(v -> {
            startActivity(new Intent(this, findtest.class));
        });
        Button reqs = findViewById(R.id.reqs);
        reqs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Friends.this, friendsRequest.class));
            }
        });
        listTemp = new ArrayList<>();
        adapter = new CustomAdapter(listTemp, getApplicationContext());
        friendList.setAdapter(adapter);
        FirebaseUser user = mAuth.getCurrentUser();
        if (user == null) {this.finish();}
        if (user != null){
        uid = user.getUid();
        }
    }

    private void getFriends(){//получение друзей в 05/02 было из users/uid/friends
        DatabaseReference isRef = FirebaseDatabase.getInstance().getReference().child("Users").child(uid).child("Friends");
        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if(listTemp.size() > 0){listTemp.clear();}
                for (DataSnapshot ds : snapshot.getChildren()){
                    addFriends addFriend = ds.getValue(addFriends.class);
                    if(addFriend != null){  //переоброзование в вид с чатом
                        String message = "put message is here, don`t forget. @chatID";
                        String nameuser = addFriend.username1;
                        String userID = addFriend.uid2;
                        Message mainFriends = new Message(message, nameuser, userID);
                        if(mainFriends != null) {
                            listTemp.add(mainFriends);
                        }
                    }
                }
                adapter.notifyDataSetChanged();
            }

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

            }
        };
        isRef.addValueEventListener(valueEventListener);
    }

    private void getReqs() {
        /*DatabaseReference isRef = FirebaseDatabase.getInstance().getReference().child("Users").child(uid).child("Friends-request");
        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if(listData.size() > 0){listData.clear();}
                for (DataSnapshot ds : snapshot.getChildren()) {
                    addFriends addFriendless;
                    addFriendless = ds.getValue(addFriends.class);
                    if (addFriendless != null) {
                        listData.add(addFriendless.username1);
                    }
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(Friends.this, error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        };
        isRef.addValueEventListener(valueEventListener);
    }*/

    }

    @Override
    public boolean onSupportNavigateUp(){
        finish();
        return true;
    }
}

顺便说一下,消息 class 本身

package #

public class Message {
    public String message;
    public String nameuser;
    public String userID;

    public Message(String message, String nameuser, String userID) {
        this.message = message;
        this.nameuser = nameuser;
        this.userID = userID;
    }

    public Message() {
    }
}

它在你的错误中说

Can't pass null for argument 'pathString' in child()

正如它所说的那样。很有可能你的uid等于null。在发送之前检查该变量。我可以在你的代码中看到你在给 uid 赋值之前调用 getFriends(),这导致了这个错误。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_friends);
    setTitle("Друзья");
    assert getSupportActionBar() != null;   //null check
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    FirebaseUser user = mAuth.getCurrentUser();
    if (user == null) this.finish();
    if (user != null){
      uid = user.getUid();
    }

    getFriends();

在调用 getFriends()

之前获取 uid