0

I'm new to Programming and to Android and have please a question. I have just easy app to insert, delete and update cars. I create an interface to communicate the RecyclerAdapter to the Fragments. Insert and delete cars work without problemes, however when I update the instance it will be not changed. To make it more clearly,the user has a button "updateButtonOnRecyclerView" on RecyclerView and when he clicks it,he get the UpdateFragment where he can update the instance and finally he clicks the button "updateButtonOnFragment" to save the updates.

I hope that someone can help me. thanks a lot.

UpdateFragment

public class UpdateFragment extends Fragment {

    private EditText modelUpdate;
    private EditText colorUpdate;
    private EditText dplUpdate;
    private EditText priceUpdate;
    private EditText descriptionUpdate;
    private Button updateButtonOnFragment;
    private MyViewModel myViewModel;
    public UpdateFragment() {
        // Required empty public constructor
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
       View view= inflater.inflate(R.layout.fragment_update, container, false);
       
        modelUpdate=view.findViewById(R.id.input_model_update);
        colorUpdate=view.findViewById(R.id.input_color_update);
        priceUpdate=view.findViewById(R.id.input_price_update);
        dplUpdate=view.findViewById(R.id.input_dpl_update);
        descriptionUpdate=view.findViewById(R.id.input_description_update);

        MyViewModel myViewModel= new ViewModelProvider(this).get(MyViewModel.class);
        
        updateButtonOnFragment =view.findViewById(R.id.btnUpdate);
        updateButtonOnFragment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String model=modelUpdate.getText().toString();
                String color=colorUpdate.getText().toString();
                String price=priceUpdate.getText().toString();
                String dpl=dplUpdate.getText().toString();
                String description=descriptionUpdate.getText().toString();

                // create an instance of car
                Car car = new Car();
                car.setCarModel(model);
                car.setCarColor(color);
                car.setCarDescription(description);
                car.setCarDpl(dpl);
                car.setCarPrice(price);

                myViewModel.updateCar(car);

                MainActivity.fragmentManager.beginTransaction().replace(R.id.container,new BaseFragment(),null).commit();
            }

        });

       return view;
    }
}

RecyclerAdapter

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {

   private List<Car>list;
   private Context context;
   private MyViewModel myViewModel;
   private CarAdapterEvent carAdapterEvent;
   //Constructor
    public RecyclerAdapter(List<Car> list,Context context,CarAdapterEvent carAdapterEvent ) {
        this.list = list;
        this.context=context;
        this.carAdapterEvent=carAdapterEvent;
    }
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.car_item,parent,false);
        MyViewHolder myViewHolder = new MyViewHolder(view);
        context=parent.getContext();
        return myViewHolder;
    }
    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        Car car = list.get(position);
        holder.tvModel.setText(car.getCarModel());
        holder.tvColor.setText(car.getCarColor());
        holder.tvDpl.setText(car.getCarDpl());
        holder.tvDescription.setText(car.getCarDescription());
        holder.tvPrice.setText(car.getCarPrice());
    }
    @Override
    public int getItemCount() {
        if(list !=null)
        {
            return list.size();
        }
        else return 0;
    }
   public void setData(List<Car>list){
       this.list=list;
       notifyDataSetChanged();
   }
    // generate ViewHolder
    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView tvModel;
        TextView tvColor;
        TextView tvDpl;
        TextView tvDescription;
        TextView tvPrice;
        Button btnDelete;
        Button updateButtonOnRecyclerView;
        // Constructor of ViewHolder
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            // Inflate the views
            tvModel=itemView.findViewById(R.id.model);
            tvColor=itemView.findViewById(R.id.color);
            tvDescription=itemView.findViewById(R.id.description);
            tvDpl=itemView.findViewById(R.id.dpl);
            tvPrice=itemView.findViewById(R.id.price);
            btnDelete=itemView.findViewById(R.id.btn_delete);
            updateButtonOnRecyclerView =itemView.findViewById(R.id.btn_update);
            
            // Listener for Delete button
            btnDelete.setOnClickListener(this);
            btnDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getAdapterPosition();
                    carAdapterEvent.onDeleteClicked(list.get(position));
                }
            });
            //Listener for update button
            updateButtonOnRecyclerView.setOnClickListener(this);
            updateButtonOnRecyclerView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getAdapterPosition();
                    carAdapterEvent.onUpdateClicked(list.get(position));
                }
            });
        }
       private void CreateAlertDialoge()
       {
           AlertDialog.Builder builder =new AlertDialog.Builder(context);
           builder.setMessage("Are you sure to delete");
           builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which) {

                   Car car = new Car();
                   int ID=list.get(getAdapterPosition()).getCarId();
                   car.setCarId(ID);


                  myViewModel.deleteCar(car);


                   MainActivity.fragmentManager.beginTransaction().replace(R.id.container,new BaseFragment(),null).commit();

                   Toast.makeText(context, "Yes", Toast.LENGTH_SHORT).show();
               }
           });
           builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which) {
                   Toast.makeText(context, "no", Toast.LENGTH_SHORT).show();

               }
           });
           builder.create();
           builder.show();
       }
        @Override
        public void onClick(View v) { }
    }
}

Interface for communication

public interface CarAdapterEvent {
    void onDeleteClicked(Car car);
    void onUpdateClicked(Car car);
}

BaseFragment

public class BaseFragment extends Fragment implements CarAdapterEvent {

    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private List<Car>list=new ArrayList<>();
    private MyViewModel myViewModel;
    public RecyclerAdapter recyclerAdapter;

    // Required empty public constructor
    public BaseFragment() { }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_base, container, false);
        //Inflate recyclerView
        recyclerView=view.findViewById(R.id.recyclerViewId);
        // define and set LayoutManager
        layoutManager= new GridLayoutManager(requireActivity(),2);
        recyclerView.setLayoutManager(layoutManager);
        //define and set RecyclerView Adapter
        recyclerAdapter = new RecyclerAdapter(list, getContext(),this);
        recyclerView.setAdapter(recyclerAdapter);
        //observer
       myViewModel= new ViewModelProvider(this).get(MyViewModel.class);
       myViewModel.getGetAllCars().observe(getViewLifecycleOwner(), new Observer<List<Car>>() {
           @Override
           public void onChanged(List<Car> cars) {
               recyclerAdapter.setData(cars);
           }
       });
        return view;
    }
    @Override
    public void onDeleteClicked(Car car) {
      myViewModel.deleteCar(car);
      MainActivity.fragmentManager.beginTransaction().replace(R.id.container,new BaseFragment(),null).commit();
    }
    @Override
    public void onUpdateClicked(Car car) {
        myViewModel.updateCar(car);
        MainActivity.fragmentManager.beginTransaction().replace(R.id.container,new UpdateFragment(),null).commit();

    }
}
john
  • 3
  • 3
  • In Update Fragment you are creating a new instance of MyViewModel and you are updating on that instance. You need to pass the reference of the Car to update fragment in onUpdateClicked(). – mohammed ahmed Mar 16 '22 at 10:38
  • first of all, thank you for the answer. What do you mean exactly with "eference of the Car " and how can I do it? @mohammedahmed – john Mar 16 '22 at 16:29
  • You can find multiple ways of fragment-to-fragment communication [here](https://stackoverflow.com/questions/13700798/basic-communication-between-two-fragments) – mohammed ahmed Mar 18 '22 at 09:13
  • Another thing that might work is replace `myViewModel= new ViewModelProvider(this).get(MyViewModel.class);` with `myViewModel= new ViewModelProvider(getActivity()).get(MyViewModel.class);` in both base and update fragment. – mohammed ahmed Mar 18 '22 at 09:19

0 Answers0