简体   繁体   English

RecyclerView中的数据未从片段传递到适配器

[英]Data in RecyclerView not being passed from Fragment to Adapter

After creating a RecyclerView , I noticed that the strings I have declared within a Bundle are not getting passed from the Fragment to the AlertDialog , and the connected text views appear blank. 创建RecyclerView ,我注意到在Bundle中声明的字符串没有从Fragment传递到AlertDialog ,并且连接的文本视图显示为空白。 Does anyone know what has gone wrong? 有谁知道出了什么问题? Do I need to use an intent for this scenario or something else? 我是否需要针对这种情况或其他目的使用意图?

Used in fragment: 用于片段:

Bundle bundle = new Bundle();
bundle.putString("goalreached",  getResources().getString(R.string.goal_reached));
bundle.putString("day",  getResources().getString(R.string.today));
bundle.putString("distance",  getResources().getString(R.string._3_2_km));
bundle.putString("calories",  getResources().getString(R.string._213_kcal));

Used in adapter: 用于适配器:

Bundle bundle = new Bundle();
String goalreached = bundle.getString("goalreached");   
String day = bundle.getString("day");
String distance = bundle.getString("distance");                        
String calories = bundle.getString("calories");

在此处输入图片说明

expected result 预期结果

在此处输入图片说明

current result 当前结果

在此处输入图片说明

fragment class 片段类

public class TabFragmentRV extends android.support.v4.app.Fragment {
    RecyclerView mRecyclerView;

    public TabFragmentRV() {}

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_rv, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        View v = getView();
        assert v != null;

        mRecyclerView = v.findViewById(R.id.my_recyclerview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

        Bundle bundle = new Bundle();
        bundle.putString("goalreached",  getResources().getString(R.string.goal_reached));
        bundle.putString("day",  getResources().getString(R.string.today));
        bundle.putString("distance",  getResources().getString(R.string._3_2_km));
        bundle.putString("calories",  getResources().getString(R.string._213_kcal));

        super.onActivityCreated(savedInstanceState);

        initRVAdapter();
    }

    private void initRVAdapter(){
        List<Object> itemsList = new ArrayList<>();

        itemsList.add(new RVLineSeparator());
        itemsList.add(new RVTable("Stats", "Today", "Yesterday", "This week", "This month"));

        RVItemsAapter itemsListAdapter = new RVItemsAapter(getContext());
        mRecyclerView.setAdapter(itemsListAdapter);

        itemsListAdapter.setCallSMSFeed(itemsList);
        itemsListAdapter.notifyDataSetChanged();
    }
}

adapter class 适配器类

public class RVItemsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private final static int TYPE_TABLE = 1, TYPE_SEPARATOR = 2;
    private ArrayList myArrayList = new ArrayList();
    private Context context;

    public RVItemsAdapter(Context context){
        this. context=context;
    }

    public void setCallSMSFeed(List<Object> myArrayList){
        this.myArrayList = (ArrayList) myArrayList;
    }

    @Override
    public int getItemViewType(int position) {
        if (myArrayList.get(position) instanceof TableRV) {
            return TYPE_TABLE;
        } else if (myArrayList.get(position) instanceof RVLineSeparator) {
            return TYPE_SEPARATOR;
        }
        throw new IllegalArgumentException("Item at position " + position + " is not an instance of either Phonecall or SMSmessage");
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        int viewType=holder.getItemViewType();
        switch (viewType){
            case TYPE_TABLE:
                TableRV tblRV = (TableRV) myArrayList.get(position);
                ((TblViewHolder)holder).bind(tblRV);
                break;
            case TYPE_SEPARATOR:
                ((SeparatorViewHolder)holder).showSeparatorDetails();
                break;
            default:
                throw new IllegalArgumentException("unexpected viewType: " + viewType);
        }
    }

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

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

        int layout;
        RecyclerView.ViewHolder viewHolder;
        switch (viewType){
            case TYPE_TABLE:
                layout = R.layout.cardview_tableview_withexpandability;
                View tblView = LayoutInflater
                        .from(parent.getContext())
                        .inflate(layout, parent, false);
                viewHolder = new TblViewHolder(tblView);
                break;
            case TYPE_SEPARATOR:
                layout = R.layout.lineseparatorforrecyclerview;
                View separatorView = LayoutInflater
                        .from(parent.getContext())
                        .inflate(layout, parent, false);
                viewHolder = new SeparatorViewHolder(separatorView);
                break;
            default:
                throw new IllegalArgumentException("unexpected viewType: " + viewType);
        }
        return viewHolder;
    }

    public class TblViewHolder extends RecyclerView.ViewHolder {
        final Typeface iconFont = FontManager.getTypeface(context, FontManager.FONTAWESOME);

        private Button btnToday, btnYesterday, btnThisWeek, btnThisMonth;
        private TextView arrowexpandcollapseTextView, sectionNameTextView;

        TblViewHolder(View itemView) {
            super(itemView);

            btnMale.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog alertDialog = new AlertDialog.Builder(v.getContext()).create();

                    alertDialog.setButton(Dialog.BUTTON_NEUTRAL,"OK",new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });


                    LayoutInflater inflater = LayoutInflater.from(context);
                    @SuppressLint("InflateParams") View content = inflater.inflate(R.layout.dialog_stats, null);
                    alertDialog.setView(content);

                    Bundle bundle = getBundle();
                    String goalreached = bundle.getString("goalreached");   
                    String day = bundle.getString("day");
                    String distance = bundle.getString("distance");                        
                    String calories = bundle.getString("calories");


                    ImageView imgdialogMain = content.findViewById(R.id.imgView_genderA);
                    ivGenderA.setImageResource(R.drawable.ic_male);

                    TextView tvGoalReached = content.findViewById(R.id.txtView_dialog_goalreached);
                    tvGoalReached.setText(goalreached);


                    TextView tvDay = content.findViewById(R.id.txtView_day);
                    tvDay.setText(day);

                    TextView tvImgviewWalking = content.findViewById(R.id.imgView_walking);


                    TextView tvDistance = content.findViewById(R.id.txtView_distance);
                    tvDistance.setText(distance);

                    TextView tvImgviewFire = content.findViewById(R.id.imgView_fire);

                    TextView tvCaloriesBurned = content.findViewById(R.id.txtView_location);
                    tvCaloriesBurned.setText(calories);

                    alertDialog.show();
                }
            });
        }
    }
}

You need to pass the first created bundle into your adapter (probably when you create it) 您需要将第一个创建的捆绑软件传递到适配器中(可能是在创建适配器时)

Here is the class with the necessary changes 这是带有必要更改的课程

public class RVItemsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private final static int TYPE_TABLE = 1, TYPE_SEPARATOR = 2;
    private ArrayList myArrayList = new ArrayList();
    private Context context;
    //Added Global bundle
    Private Bundle mBundle;

    public RVItemsAdapter(Context context){
        this. context=context;
    }

    //Added Constructor
    public RVItemsAdapter(Context context, Bundle bundle){
        this.context=context;
        this.mBundle = bundle;
    } 

    public void setCallSMSFeed(List<Object> myArrayList){
        this.myArrayList = (ArrayList) myArrayList;
    }

    @Override
    public int getItemViewType(int position) {
        if (myArrayList.get(position) instanceof TableRV) {
            return TYPE_TABLE;
        } else if (myArrayList.get(position) instanceof RVLineSeparator) {
            return TYPE_SEPARATOR;
        }
        throw new IllegalArgumentException("Item at position " + position + " is not an instance of either Phonecall or SMSmessage");
    }

    //Update Bundle
    public void updateView(Bundle bundle){
        mBundle = bundle;
        this.notifyDataSetChanged();
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        int viewType=holder.getItemViewType();
        switch (viewType){
            case TYPE_TABLE:
                TableRV tblRV = (TableRV) myArrayList.get(position);
                ((TblViewHolder)holder).bind(tblRV);
                break;
            case TYPE_SEPARATOR:
                ((SeparatorViewHolder)holder).showSeparatorDetails();
                break;
            default:
                throw new IllegalArgumentException("unexpected viewType: " + viewType);
        }
    }

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

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

        int layout;
        RecyclerView.ViewHolder viewHolder;
        switch (viewType){
            case TYPE_TABLE:
                layout = R.layout.cardview_tableview_withexpandability;
                View tblView = LayoutInflater
                        .from(parent.getContext())
                        .inflate(layout, parent, false);
                viewHolder = new TblViewHolder(tblView);
                break;
            case TYPE_SEPARATOR:
                layout = R.layout.lineseparatorforrecyclerview;
                View separatorView = LayoutInflater
                        .from(parent.getContext())
                        .inflate(layout, parent, false);
                viewHolder = new SeparatorViewHolder(separatorView);
                break;
            default:
                throw new IllegalArgumentException("unexpected viewType: " + viewType);
        }
        return viewHolder;
    }

    public class TblViewHolder extends RecyclerView.ViewHolder {
        final Typeface iconFont = FontManager.getTypeface(context, FontManager.FONTAWESOME);

        private Button btnToday, btnYesterday, btnThisWeek, btnThisMonth;
        private TextView arrowexpandcollapseTextView, sectionNameTextView;

        TblViewHolder(View itemView) {
            super(itemView);

            btnMale.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog alertDialog = new AlertDialog.Builder(v.getContext()).create();

                    alertDialog.setButton(Dialog.BUTTON_NEUTRAL,"OK",new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });


                    LayoutInflater inflater = LayoutInflater.from(context);
                    @SuppressLint("InflateParams") View content = inflater.inflate(R.layout.dialog_stats, null);
                    alertDialog.setView(content);

                    //Pulling String out of bundle
                    String goalreached = mBundle.getString("goalreached");   
                    String day = mBundle.getString("day");
                    String distance = mBundle.getString("distance");                        
                    String calories = mBundle.getString("calories");


                    ImageView imgdialogMain = content.findViewById(R.id.imgView_genderA);
                    ivGenderA.setImageResource(R.drawable.ic_male);

                    TextView tvGoalReached = content.findViewById(R.id.txtView_dialog_goalreached);
                    tvGoalReached.setText(goalreached);


                    TextView tvDay = content.findViewById(R.id.txtView_day);
                    tvDay.setText(day);

                    TextView tvImgviewWalking = content.findViewById(R.id.imgView_walking);


                    TextView tvDistance = content.findViewById(R.id.txtView_distance);
                    tvDistance.setText(distance);

                    TextView tvImgviewFire = content.findViewById(R.id.imgView_fire);

                    TextView tvCaloriesBurned = content.findViewById(R.id.txtView_location);
                    tvCaloriesBurned.setText(calories);

                    alertDialog.show();
                }
            });
        }
    }
}

Currently you are just making a new bundle in your fragment and adding strings to it then doing nothing with it, then in the adapter you are creating another new Bundle and trying to pull out strings that are not there. 当前,您只是在片段中创建一个新捆绑包,然后向其中添加字符串,然后对其进行任何操作,然后在适配器中创建另一个新捆绑包,并尝试提取不存在的字符串。

To update the data you could try something like this in the adapter to be called when you need to update the data (I am not sure if the notifyDataSetChanged() will work from inside the adapter though): 要更新数据,您可以在需要更新数据时尝试在适配器中调用类似的方法(但不确定notifyDataSetChanged()是否可以从适配器内部运行):

//Update Bundle
public void updateView(Bundle bundle){
    mBundle = bundle;
    this.notifyDataSetChanged();
}

You are trying to get the extras from a new Bundle here: 您正在尝试从此处的新捆绑包中获取其他服务:

Bundle bundle = new Bundle();
String goalreached = bundle.getString("goalreached");
...

You need to get the bundle where you stored that info. 您需要获取将信息存储在其中的捆绑软件。 A bundle is only a "container" of info, so you need to store it and then retrieve it. 捆绑包只是信息的“容器”,因此您需要先存储它,然后再检索它。

You are never saving the bundle anywhere, so you can't read it later. 您永远不会将捆绑软件保存在任何地方,因此以后将无法阅读。

I'm not sure what you want to do here, so I can't give you an example, but just check out this: 我不确定您要在这里做什么,所以我不能举一个例子,只需要检查一下:

Bundle bundle = new Bundle();
bundle.putString("goalreached",  getResources().getString(R.string.goal_reached));
bundle.putString("day",  getResources().getString(R.string.today));
bundle.putString("distance",  getResources().getString(R.string._3_2_km));
bundle.putString("calories",  getResources().getString(R.string._213_kcal));

You are creating that bundle, then storing info, and that's it. 您正在创建该捆绑包,然后存储信息,仅此而已。 You are never storing it anywhere. 您永远不会将其存储在任何地方。

The basic usage of a bundle is storing it on an Intent, then retrieving that intent and getting the bundle. 捆绑软件的基本用法是将其存储在Intent上,然后检索该Intent并获取捆绑软件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM