自定义适配器中的空对象引用上的 ImageView setOnClickListener

ImageView setOnClickListener on a null object reference in custom adapter

我从网上拿了这个适配器,但遇到了问题:

Fatal Exception: java.lang.NullPointerException
Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
.Consts.CustomFriendsRequets.getView

这里 CustomFriendRequest 是我的适配器,它的副本工作正常,但这个不需要。错误指的是第104行,即viewHolder.add.setOnClickListener (v ->。我花了几天时间检查代码,试图找出问题所在。 这是完整的适配器代码。 CustomFriendsRequets:

class CustomFriendsRequets extends ArrayAdapter<addFriends> implements View.OnClickListener{
    private ArrayList<addFriends> dataSet;
    private String uid, uid2;
    private DatabaseReference isRef;
    Context mContext;



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

    public CustomFriendsRequets(ArrayList<addFriends> data, Context context) {
        super(context, R.layout.friends_requests_item, data);
        this.dataSet = data;
        this.mContext=context;

    }

    @Override
    public void onClick(View v) {

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

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        addFriends 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.friends_item, parent, false);
            viewHolder.txtName = convertView.findViewById(R.id.tvDescr);
            viewHolder.txtType = convertView.findViewById(R.id.tvPrice);
            viewHolder.info = convertView.findViewById(R.id.uImgreqs);
            viewHolder.add = convertView.findViewById(R.id.ibAdd);
            viewHolder.del = convertView.findViewById(R.id.ibDel);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();if(user!=null){uid=user.getUid();}
        uid2 = dataModel.uid2;
        viewHolder.txtName.setText(dataModel.username1);
        viewHolder.txtType.setText("хочет добавить вас в друзья");
        viewHolder.info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), EnemyProfile.class);
                intent.putExtra(Constant.UID, dataModel.uid2);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                v.getContext().startActivity(intent);
            }
        });
        isRef = FirebaseDatabase.getInstance().getReference();
        viewHolder.add.setOnClickListener(v ->  //error here
                isRef.child("Users").child("info").child(uid2).addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                Users info = snapshot.getValue(Users.class);
                if (info!=null){
                    String name = info.username;
                    String id = info.uid;
                    addFriends adf = new addFriends(id, name);
                    isRef.child("Users").child(uid).child("Friends").setValue(adf).
                            addOnSuccessListener(aVoid ->
                                    isRef.child("Users").child("info").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(@NonNull DataSnapshot snapshot1) {
                                    Users minfo = snapshot1.getValue(Users.class);
                                    if (minfo!=null){
                                        String mname = minfo.username;
                                        String mid = minfo.uid;
                                        addFriends madf = new addFriends(mid, mname);
                                        isRef.child("Users").child(uid2).child("Friends").setValue(madf)
                                                .addOnSuccessListener(aVoid1 -> {
                                                    isRef.child("Users").child(uid).child("Friends-request").child(uid2).removeValue();
                                                    isRef.child("Users").child(uid2).child("Friends-request").child(uid).removeValue();
                                                });
                                    }
                                }

                                @Override
                                public void onCancelled(@NonNull DatabaseError error) {
                                    Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            }));
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }));
        viewHolder.del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isRef.child("Users").child(uid).child("Friends-request").child(uid2).removeValue();
                isRef.child("Users").child(uid2).child("Friends-request").child(uid).removeValue();
            }
        });
        // Return the completed view to render on screen
        return convertView;
    }
}

这里我在列表视图的 activity 中调用它:

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 (reqsTemp.size() > 0){reqsTemp.clear();}
                for (DataSnapshot ds : snapshot.getChildren()){
                    addFriends reqs = ds.getValue(addFriends.class);
                    if (reqs!=null) {
                        reqsTemp.add(reqs);
                    }
                }
                reqsadapter.notifyDataSetChanged();
            }

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

顺便说一句,这里是来自适配器的元素代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="96dp"
    android:orientation="horizontal">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardViewsdd"
        android:layout_width="86dp"
        android:layout_height="86dp"
        android:layout_marginStart="10dp"
        android:layout_marginTop="5dp"
        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/uImgreqs"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:src="@mipmap/ic_launcher_round"
            android:contentDescription="@string/todo" />
    </androidx.cardview.widget.CardView>

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginStart="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
            android:id="@+id/tvPrice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="18dp"
            android:text="" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="100dp"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/ibAdd"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            app:srcCompat="@android:drawable/ic_input_add" />

        <ImageView
            android:id="@+id/ibDel"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            app:srcCompat="@drawable/ic_dialog_close_light" />
    </LinearLayout>
</LinearLayout>

add按钮应该记录双方用户的id,del相应删除请求。 uImgreqs只是一张用户的照片,两个textview都是用户名等用户数据。如果有什么需要补充的,我会很乐意补充,因为我很绝望,截止日期是运行出来

天啊,不不不不不不不不不不。 Android 工作室,我崇拜你。 我找到了一个解决方案,原来问题是由于 (v ->,我或工作室将 OnClick 函数翻译成 lambda,因此它返回了一个空对象......3 天半.. .我在这上面花了三天多的时间,omg

viewHolder.add.setOnClickListener(new View.OnClickListener() {
                                              @Override
                                              public void onClick(View v) {});

不,这不是赢

呃,不,它没有完全解决问题,现在在每个 imageView .setOnClicklistener 上都会抛出错误...

我发现了问题,我写错了标签:

convertView = inflater.inflate(R.layout.friends_item, parent, false);

很不起眼的线条,脸掌