如何使 Recyclerview 与回调一起正常工作

how to make Recyclerview works correctly with callback

我已经实现了 recyclerview,它工作正常,我在 BikeAdapter 中使用了一个回调来能够点击这个回收器视图的每一行,但是当我把这些行放在 OnCreateView 中时,回收器视图回收器抛出空回调错误,当我删除 mAdapter.setCallback(this); recyclerview 变空了

recyclerView.setAdapter(mAdapter); fillData();
        mAdapter = new BikesAdapter(getActivity(), (ArrayList<Bike>) bikes);
        mAdapter.setCallback(this);

当我将这些行放在 filldata() OnResponse 方法中时:mAdapter.setCallback(this) 无法识别

mAdapter.setCallback(this);

如果我想毫无问题地显示我的回收站视图,我必须删除 mAdapter.setCallback(this); mAdapter = new BikesAdapter(getActivity(), (ArrayList) 自行车); recyclerView.setAdapter(适配器); 在 fillData 内部以在正确的时间获得响应

//我的适配器代码

package com.example.miniprojetandroid.adapters;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.miniprojetandroid.R;
import com.example.miniprojetandroid.models.Bike;


public class BikesAdapter  extends RecyclerView.Adapter<BikesAdapter.BikesViewHolder> {

    private final ArrayList<Bike> bikes;
    private Context mContext;
    private Callback mCallback;

public BikesAdapter(Context mContext, ArrayList<Bike> bikes) {
        this.mContext = mContext ;
        this.bikes = bikes;
        }

@NonNull
@Override
public BikesAdapter.BikesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View mItemView = LayoutInflater.from(mContext).inflate(R.layout.bike_list_item, parent, false);
        return new BikesViewHolder(mItemView, this);
        }

@Override
public void onBindViewHolder(@NonNull BikesAdapter.BikesViewHolder holder, int position) {
final Bike singleItem = bikes.get(position);

        holder.BikeName.setText(singleItem.getModel());
        holder.BikeImage.setBackgroundResource(singleItem.getImage());
        holder.bikeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCallback.onItemClicked(singleItem);
            }
        });
        holder.BikeImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
        Toast.makeText(mContext,singleItem.getModel(),Toast.LENGTH_SHORT).show();
        }
        });
        }

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

public class BikesViewHolder extends RecyclerView.ViewHolder {

    public final TextView BikeName;
    public final ImageView BikeImage;
    public final Button bikeView;
    final BikesAdapter mAdapter;

    public BikesViewHolder(@NonNull View itemView, BikesAdapter mAdapter) {
        super(itemView);
        this.BikeName = itemView.findViewById(R.id.bikeName);
        this.BikeImage = itemView.findViewById(R.id.bikeImage);
        this.bikeView = itemView.findViewById(R.id.btn_view);
        this.mAdapter = mAdapter;
    }
}


    public void setCallback(Callback callback) {
        mCallback = callback;
    }

    public interface Callback {
        void onItemClicked(Bike bike);
    }

}

//包含回收视图的我的片段

    package com.example.miniprojetandroid.ui.fragments;

import android.os.Bundle;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.miniprojetandroid.R;

import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.miniprojetandroid.Retrofit.BikeService;
import com.example.miniprojetandroid.Retrofit.RetrofitClient;
import com.example.miniprojetandroid.Retrofit.UserService;
import com.example.miniprojetandroid.adapters.BikesAdapter;
import com.example.miniprojetandroid.models.Bike;
import com.example.miniprojetandroid.models.User;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FragmentOne extends Fragment implements BikesAdapter.Callback{

    private BikeService apiService;

    private RecyclerView recyclerView;
    private List<Bike> bikes = new ArrayList<Bike>();
    private  BikesAdapter mAdapter;
    List<Bike> result = new ArrayList<Bike>();




    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_one, container,false);

        recyclerView = rootView.findViewById(R.id.recycler_bikes);

        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(true);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),
                LinearLayoutManager.VERTICAL, false));

        apiService = RetrofitClient.getClient().create(BikeService.class);
        fillData();
        mAdapter.setCallback(this);
        return rootView;
    }


    public void fillData(){


        Call<List<Bike>> call = apiService.getBikes();
        call.enqueue(new Callback<List<Bike>>() {
            @Override
            public void onResponse(Call<List<Bike>> call, Response<List<Bike>> response) {
                if(response.isSuccessful()){
                    bikes.addAll(response.body());
                    for(Bike bike: bikes){
                        bike.setImage(R.drawable.ruebike);
                    }
                    Log.e("Bike LIST", bikes.toString());
                    mAdapter = new BikesAdapter(getActivity(), (ArrayList<Bike>) bikes);
                    recyclerView.setAdapter(mAdapter);


                    //listView.setAdapter(new UserAdapter(MainActivity.this, R.layout.list_user, list));
                }
            }
            @Override
            public void onFailure(Call<List<Bike>> call, Throwable t) {
                Log.e("ERROR: ", t.getMessage());
            }
        });




        /*bikes.add(new Bike(1,"ECO", "RTT" , "44", R.drawable.ruebike ));
        bikes.add(new Bike(2,"AAA", "RTT" , "33",  R.drawable.ruebike ));
        bikes.add(new Bike(3,"BBB", "RUE" , "11",  R.drawable.ruebike ));
        bikes.add(new Bike(4,"EEE", "SPORT" , "25",  R.drawable.ruebike ));
        bikes.add(new Bike(5,"CCC", "SPORT" , "77", R.drawable.ruebike ));
        Log.e("USERS LIST", bikes.toString());*/
    }

    @Override
    public void onItemClicked(Bike bike) {
        Bundle bundle = new Bundle();
        bundle.putInt("bike_id",bike.getId());
        bundle.putString("model", bike.getModel());
        bundle.putString("type", bike.getType());
        bundle.putString("price", bike.getPrice());
        bundle.putInt("image", bike.getImage());
        DetailsFragment f = new DetailsFragment();
        f.setArguments(bundle);
        getActivity().getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragmentsContainer, f )
                .commit();
    }




}

我想做的是两件事: 1/ 使我的片段 recyclerview 使用回调方法与 filldata 一起工作(对于想法 Log.e 表明此方法工作正常) 2/ 确保当我单击回收站视图的一个项目时,我将选定的自行车传递给一个 thired fragmend (DetailsFragment)

错误:当我删除回调时回收器视图是空的,当我使用它时它抛出空异常

请帮帮我

方法 fillData 没有立即执行,因为它包含网络操作,所以它在后台线程上工作,所以当你调用 setCallback 时,mAdapter 将不会被初始化,所以我建议初始化 mAdapter 并在 onCreate 中调用 setAdapter onResponse 方法,您可以将数组作为 null 传递给构造函数,在 onResponse 内部,您可以通过 setter 方法传递自行车 arrayList,并在分配列表后在此方法(setter 方法)中传递“notifyDataSetChanged();”

因此您的适配器将如下所示:

package com.example.miniprojetandroid.adapters;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.miniprojetandroid.R;
import com.example.miniprojetandroid.models.Bike;


public class BikesAdapter  extends RecyclerView.Adapter<BikesAdapter.BikesViewHolder> {

    private final ArrayList<Bike> bikes;
    private Context mContext;
    private Callback mCallback;

public BikesAdapter(Context mContext, ArrayList<Bike> bikes) {
        this.mContext = mContext ;
        this.bikes = bikes;
        }
public setBikesList(ArrayList<Bike> bikes){
this.bikes=bikes;
notifyDataSetChanged();
}


@NonNull
@Override
public BikesAdapter.BikesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View mItemView = LayoutInflater.from(mContext).inflate(R.layout.bike_list_item, parent, false);
        return new BikesViewHolder(mItemView, this);
        }

@Override
public void onBindViewHolder(@NonNull BikesAdapter.BikesViewHolder holder, int position) {
final Bike singleItem = bikes.get(position);

        holder.BikeName.setText(singleItem.getModel());
        holder.BikeImage.setBackgroundResource(singleItem.getImage());
        holder.bikeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCallback.onItemClicked(singleItem);
            }
        });
        holder.BikeImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
        Toast.makeText(mContext,singleItem.getModel(),Toast.LENGTH_SHORT).show();
        }
        });
        }

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

public class BikesViewHolder extends RecyclerView.ViewHolder {

    public final TextView BikeName;
    public final ImageView BikeImage;
    public final Button bikeView;
    final BikesAdapter mAdapter;

    public BikesViewHolder(@NonNull View itemView, BikesAdapter mAdapter) {
        super(itemView);
        this.BikeName = itemView.findViewById(R.id.bikeName);
        this.BikeImage = itemView.findViewById(R.id.bikeImage);
        this.bikeView = itemView.findViewById(R.id.btn_view);
        this.mAdapter = mAdapter;
    }
}


    public void setCallback(Callback callback) {
        mCallback = callback;
    }

    public interface Callback {
        void onItemClicked(Bike bike);
    }

}

和你的片段:

package com.example.miniprojetandroid.ui.fragments;

import android.os.Bundle;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.miniprojetandroid.R;

import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.miniprojetandroid.Retrofit.BikeService;
import com.example.miniprojetandroid.Retrofit.RetrofitClient;
import com.example.miniprojetandroid.Retrofit.UserService;
import com.example.miniprojetandroid.adapters.BikesAdapter;
import com.example.miniprojetandroid.models.Bike;
import com.example.miniprojetandroid.models.User;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FragmentOne extends Fragment implements BikesAdapter.Callback{

    private BikeService apiService;

    private RecyclerView recyclerView;
    private List<Bike> bikes = new ArrayList<Bike>();
    private  BikesAdapter mAdapter;
    List<Bike> result = new ArrayList<Bike>();




    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_one, container,false);

        recyclerView = rootView.findViewById(R.id.recycler_bikes);

        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(true);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),
                LinearLayoutManager.VERTICAL, false));

        apiService = RetrofitClient.getClient().create(BikeService.class);
        fillData();
        mAdapter = new BikesAdapter(getActivity(),null);
        mAdapter.setCallback(this);
        recyclerView.setAdapter(mAdapter);
       
        return rootView;
    }


    public void fillData(){


        Call<List<Bike>> call = apiService.getBikes();
        call.enqueue(new Callback<List<Bike>>() {
            @Override
            public void onResponse(Call<List<Bike>> call, Response<List<Bike>> response) {
                if(response.isSuccessful()){
                    bikes.addAll(response.body());
                    for(Bike bike: bikes){
                        bike.setImage(R.drawable.ruebike);
                    }
                    Log.e("Bike LIST", bikes.toString());
                    mAdapter.setBikesList(bikes);


                    //listView.setAdapter(new UserAdapter(MainActivity.this, R.layout.list_user, list));
                }
            }
            @Override
            public void onFailure(Call<List<Bike>> call, Throwable t) {
                Log.e("ERROR: ", t.getMessage());
            }
        });




        /*bikes.add(new Bike(1,"ECO", "RTT" , "44", R.drawable.ruebike ));
        bikes.add(new Bike(2,"AAA", "RTT" , "33",  R.drawable.ruebike ));
        bikes.add(new Bike(3,"BBB", "RUE" , "11",  R.drawable.ruebike ));
        bikes.add(new Bike(4,"EEE", "SPORT" , "25",  R.drawable.ruebike ));
        bikes.add(new Bike(5,"CCC", "SPORT" , "77", R.drawable.ruebike ));
        Log.e("USERS LIST", bikes.toString());*/
    }

    @Override
    public void onItemClicked(Bike bike) {
        Bundle bundle = new Bundle();
        bundle.putInt("bike_id",bike.getId());
        bundle.putString("model", bike.getModel());
        bundle.putString("type", bike.getType());
        bundle.putString("price", bike.getPrice());
        bundle.putInt("image", bike.getImage());
        DetailsFragment f = new DetailsFragment();
        f.setArguments(bundle);
        getActivity().getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragmentsContainer, f )
                .commit();
    }
}