0

I am trying to pass data from my FoodAdapter which exteds from BaseAdapter to FoodDialog which extends from AppCompatDialogFragment. I need to pass the data to FoodDialog when the user clicks on button in the list_item.

addToCart = convertView.findViewById(R.id.button);
        View finalConvertView = convertView;
        addToCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("TAG", String.valueOf(position));
                TextView s = (TextView) finalConvertView.findViewById(R.id.foodName);
                ConfirmFoodDialog confirmFoodDialog = new ConfirmFoodDialog();

                confirmFoodDialog.show(((CategoryMenu) context).getSupportFragmentManager(), "Title");

                Intent intent = new Intent(finalConvertView.getContext(), ConfirmFoodDialog.class);
                intent.putExtra("Dish", s.getText().toString()); // s.getText().toString() returns the desired value
                
                
            }

ConfirmFoodDialog.class

public Dialog onCreateDialog(Bundle savedInstanceState){
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MyCustomTheme);
        LayoutInflater inflater = getActivity().getLayoutInflater();

        Intent intent = getActivity().getIntent();
        food = intent.getStringExtra("Dish"); // food is a String variable
        System.out.println(food); // I don't know why food returns null
}
  • `confirmFoodDialog.show(((CategoryMenu) context).getSupportFragmentManager(), "Title");` here you're showing the dialog, then later `Intent intent = new Intent(finalConvertView.getContext(), ConfirmFoodDialog.class); intent.putExtra("Dish", s.getText().toString()); // s.getText().toString() returns the desired value` you're building an intent which is doing nothing – a_local_nobody Oct 29 '20 at 20:22

1 Answers1

1

Given that you are showing your dialog with show(FragmentManager), it seems like your dialog is a subclass of DialogFragment. If this is the case, then you pass information to it the same way you pass information to any Fragment: via the arguments Bundle.

Bundle args = new Bundle();
args.putString("Dish", s.getText().toString());

ConfirmFoodDialog confirmFoodDialog = new ConfirmFoodDialog();
confirmFoodDialog.setArguments(args);
confirmFoodDialog.show(((CategoryMenu) context).getSupportFragmentManager(), "Title");

To read the value out from within the fragment, access the arguments and read your information:

public Dialog onCreateDialog(Bundle savedInstanceState){
    // ...

    food = getArguments().getString("Dish");
    System.out.println(food);
}

You can simplify the first part by implementing the newInstance() pattern for your DialogFragment.

Ben P.
  • 52,661
  • 6
  • 95
  • 123