尝试将数据从活动传递到片段时始终获得空值

尝试将数据(category_id)从活动发送到Fragment,但始终接收null(为此我正在使用Bundle类),实际上在活动中我正确地获取了数据,但在Fragment类中获取了null(请参见fragment onCreateView()方法内部类) 这是活动的代码(OfferingActivity.java)

package com.fitness.client.ui.offering;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.fitness.client.BR;
import com.fitness.client.R;
import com.fitness.client.api.product.ProductDetailResponse;
import com.fitness.client.base.classes.BaseActivity;
import com.fitness.client.base.classes.BaseViewPagerAdapter;
import com.fitness.client.databinding.ActivityOfferingBinding;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;


public class OfferingActivity extends BaseActivity<ActivityOfferingBinding, OfferingViewModel, OfferingNavigator> implements OfferingNavigator {


    private List<ProductDetailResponse.Days_timingEntity> dayTiming;
    private HashMap<String, HashMap<String, List<ProductDetailResponse.Days_timingEntity>>> weekHashMap;
    private String category_Id;

    @Override
    public int getLayoutId() {
        return R.layout.activity_offering;
    }

    @Override
    public int getViewModelId() {
        return BR.Offering_model;
    }

    @Override
    public void init(@Nullable Bundle savedInstanceState) {
        setTitle("Offer Timing");
        if (getIntent().getExtras() != null)
            if (getIntent().hasExtra("data")) {
                weekHashMap = new HashMap<>();

                dayTiming = getIntent().getExtras().getParcelableArrayList("data");
                category_Id = getIntent().getStringExtra("category_id");
//                OfferFragment frag = new OfferFragment(category_Id );
                Log.e("Here is it", "category ID in Offering Activity: " + category_Id );

                for (ProductDetailResponse.Days_timingEntity dayTiming : dayTiming) {
                    if (!weekHashMap.containsKey(dayTiming.getWeek())) {
                        weekHashMap.put(dayTiming.getWeek(), new HashMap<>());
                    }

                    if (!Objects.requireNonNull(weekHashMap.get(dayTiming.getWeek())).containsKey(dayTiming.getDay())) {
                        weekHashMap.get(dayTiming.getWeek()).put(dayTiming.getDay(), new ArrayList<>());
                    }
                    weekHashMap.get(dayTiming.getWeek()).get(dayTiming.getDay()).add(dayTiming);

                }


                setUpData();
                getViewDataBinding().daysTab.setupWithViewPager(getViewDataBinding().offeringTiming);
                getViewDataBinding().daysTab.setTabMode(TabLayout.MODE_SCROLLABLE);
            }

        FragmentManager managerCat = getSupportFragmentManager();
            FragmentTransaction t = managerCat.beginTransaction();

        OfferFragment frag = new OfferFragment();

            **Bundle bunleCat = new Bundle();  //Here I used the bundle class for this
                bunleCat.putString("object_id", category_Id);
                frag.setArguments(bunleCat);
                t.commit();**


    }

    private void setUpData() {
        List<OfferFragment> offerFragments = new ArrayList<>();
        List<String> names = new ArrayList<>();


        for (String key : weekHashMap.keySet()) {

            offerFragments.add(OfferFragment.getInstance(buildBundle(key), getContext()));
            names.add("Week " + key);

        }
        getViewDataBinding().offeringTiming.setAdapter(new OfferPager(
                getSupportFragmentManager(),
                offerFragments,
                names));


        // setting up tabs
        for (int i = 0; i < getViewDataBinding().daysTab.getTabCount(); i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.item_offerring_timing, getViewDataBinding().daysTab, false);

            TextView textView = view.findViewById(R.id.sno);
            Objects.requireNonNull(getViewDataBinding().daysTab.getTabAt(i)).setCustomView(view);
        }

    }


    public Bundle buildBundle(String key) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", weekHashMap.get(key));
        return bundle;
    }


    class OfferPager extends BaseViewPagerAdapter<OfferFragment> {

        public OfferPager(FragmentManager fm, List<OfferFragment> fragments, List<String> names) {
            super(fm, fragments, names);
        }
    }


}

这是Fragment类


package com.fitness.client.ui.offering;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.fitness.client.R;
import com.fitness.client.api.product.ProductDetailResponse;
import com.fitness.client.base.classes.BaseRecyclerViewAdapter;
import com.fitness.client.base.classes.BaseViewHolder;
import com.fitness.client.databinding.ItemOfferringTimingBinding;
import com.fitness.client.utils.Utils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

public class OfferFragment extends Fragment {


    private HashMap<String, List<ProductDetailResponse.Days_timingEntity>> days;
    private String category_id;
    private OfferTimingAdapter adapter;

    public OfferFragment() {

    }

    public static OfferFragment getInstance(Bundle bundle, Context context) {
        OfferFragment frag = (OfferFragment) OfferFragment.instantiate(context, OfferFragment.class.getName());
        frag.setArguments(bundle);

        return frag;
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//Here I am trying to recieve the data but recieving null value always
       **Bundle bundleCat = getArguments();
        if (bundleCat != null) {
            String cat = bundleCat.getString("object_id");
            Log.e("Haha", "onCreateView: offer fragment ID: " + cat );
        }**
//        assert getArguments() != null;
//        category_id = getArguments().getString("categoryId");
        return inflater.inflate(R.layout.fragment_offering, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

        if (getArguments() != null) {

            days = (HashMap<String, List<ProductDetailResponse.Days_timingEntity>>) getArguments().getSerializable("data");

        }

        ((RecyclerView) view.findViewById(R.id.days)).setAdapter(new DayAdapter(new ArrayList<>(days.keySet()), (object, itemView) -> {
            adapter.clear();
            for (ProductDetailResponse.Days_timingEntity days_timingEntity : Objects.requireNonNull(days.get(object))) {
                adapter.addData(days_timingEntity.getPackage_timing());
            }


        }));

        ((RecyclerView) view.findViewById(R.id.timing)).setAdapter(adapter = new OfferTimingAdapter(new ArrayList<>()));

        //Button
        view.findViewById(R.id.booking_change_form).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Show the dialog to change block the booking
                LayoutInflater inflater = LayoutInflater.from(getContext());
                View blockUi = inflater.inflate(R.layout.alert_block_booking, null);

                TextView categoryID = blockUi.findViewById(R.id.category_Id);
                //set the category Id
//                categoryID.setText(cat);

                Log.e("Here is it", "onClick: In Offer Fragment: " + category_id );
                //Date
                TextView fromDate = blockUi.findViewById(R.id.from_block_date);
                TextView toDate = blockUi.findViewById(R.id.to_block_date);
                //Time
                TextView fromTime = blockUi.findViewById(R.id.from_block_time);
                TextView toTime = blockUi.findViewById(R.id.to_block_time);

                //Choosing the Date
                fromDate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Utils.showDatePicker(getContext(), new Utils.OnSelectedTime() {
                            @Override
                            public void onSelected(String query) {
                                fromDate.setText(query);
                            }
                        });
                    }
                });

                toDate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Utils.showDatePicker(getContext(), new Utils.OnSelectedTime() {
                            @Override
                            public void onSelected(String query) {
                                toDate.setText(query);
                            }
                        });
                    }
                });


                Calendar calendar = Calendar.getInstance();

                final int hour = calendar.get(Calendar.HOUR_OF_DAY);
                final int minute = calendar.get(Calendar.MINUTE);
                //Choosing the Time
                fromTime.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TimePickerDialog timePickerDialog = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                fromTime.setText(hourOfDay + ":" + minute + ":00");
                            }
                        }, hour, minute, android.text.format.DateFormat.is24HourFormat(getContext()));
                        timePickerDialog.show();
                    }
                });
                toTime.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TimePickerDialog timePickerDialog = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                toTime.setText(hourOfDay + ":" + minute + ":00");
                            }
                        }, hour, minute, android.text.format.DateFormat.is24HourFormat(getContext()));
                        timePickerDialog.show();
                    }
                });


                //Show the dialog
                AlertDialog.Builder blockbuiler = new AlertDialog.Builder(getContext());
                blockbuiler.setView(blockUi);
                AlertDialog BlockDialog = blockbuiler.create();
                BlockDialog.show();


                Button submit = blockUi.findViewById(R.id.submit_block);
                Button cancel = blockUi.findViewById(R.id.cancel_block);

                submit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getContext(), "Submit is Clicked", Toast.LENGTH_SHORT).show();
                    }
                });

                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //Close the Dialog
                        BlockDialog.dismiss();
                    }
                });





            }
        });

    }



    class DayAdapter extends BaseRecyclerViewAdapter<DayAdapter.DayHolder, String> {


        public DayAdapter(List<String> data, OnItemClickListener<String> onItemClickListener) {
            super(data, onItemClickListener);
        }

        @NonNull
        @Override
        public DayHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new DayHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_offerring_timing, parent, false));
        }


        class DayHolder extends BaseViewHolder<String, ItemOfferringTimingBinding> {

            public DayHolder(View itemView) {
                super(itemView);
            }

            @Override
            protected void bindObject(String object) {

                getViewDataBinding().sno.setText(object);
                getViewDataBinding().getRoot().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        informClick(object, v);
                    }
                });
            }


        }
    }

    class OfferTimingAdapter extends BaseRecyclerViewAdapter<OfferTimingAdapter.OfferTimingHolder, ProductDetailResponse.Days_timingEntity.Package_timingEntity> {


        public OfferTimingAdapter(List<ProductDetailResponse.Days_timingEntity.Package_timingEntity> data) {
            super(data);
        }

        @NonNull
        @Override
        public OfferTimingHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new OfferTimingHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_offerring_timing, parent, false));
        }


        class OfferTimingHolder extends BaseViewHolder<ProductDetailResponse.Days_timingEntity.Package_timingEntity, ItemOfferringTimingBinding> {

            public OfferTimingHolder(View itemView) {
                super(itemView);
            }

            @Override
            protected void bindObject(ProductDetailResponse.Days_timingEntity.Package_timingEntity object) {
                getViewDataBinding().sno.setText(object.getFrom() + " - " + object.getTo());


            }


        }
    }
}

除捆绑服务外,任何帮助或其他任何人都可以使用,然后请分享,谢谢。

评论