java – Want to use a floating action button that adds an item to a recyclerview in a specific fragment that is contained in a ViewPager2-ThrowExceptions

Exception or error:

I have been having a lot of trouble trying to implement multiple recyclerviews across multiple pages(represented by fragments) in a viewpager2, and I want to use a floating action button that when clicked, props up a page where the user can input data that can eventually be added to the recyclerview within a specific page on the viewpager. The Viewpager2 is applied with a tab layout labeling the days “Monday” to “Sunday.” I cannot seem to add to the recyclerview through the activity “activity_add_medication_to_list.” There is a long segment of code with 7 intents that is meant to represent adding to a medication list. The project is essentially a medical scheduling/tracking application. For each day of the week, I want to be able to add a specific medication to the list and be able to see it visibly. There are seven fragments representing each of the days of the week. FirstFragment represents Monday, SecondFragment represents Tuesday, etc. I also have a recyclerviewAdapter class and a ViewPagerAdapter class representing the adapters for both the multiple recyclerviews and the viewPager2.

Main problem: After clicking on the floating action button and inputing my data, it is not adding to the end of the recyclerview for any of the pages (represented by FirstFragment class). What am I missing that is not allowing me to see a visible list of items for any of the recyclerviews? How do I properly integrate the recyclerviews into the fragments so that I can update the recyclerviews using the floating action button?

Only 5 of the 7 fragment classes are shown below to conserve space. They are all according to the day of the week. Monday, Tuesday, Wednesday, Thursday, Friday refer to these first 5 fragment classes.

Code:

Add Medication to List class

package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class add_medication_to_list extends AppCompatActivity {

    String name;
    String time;
    int quantity;
    int dosage;
    String dayOfWeek;
    EditText nameInput;
    EditText timeInput;
    EditText quantityInput;
    EditText dosageInput;
    EditText dayOfWeekInput;
    Button add;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_medication_to_list);
        nameInput =  findViewById(R.id.medicine_name);
        timeInput =  findViewById(R.id.time);
        quantityInput =  findViewById(R.id.medicine_quantity);
        dosageInput = findViewById(R.id.dosage);
        dayOfWeekInput = findViewById(R.id.dayOfWeek);
        add =  findViewById(R.id.addButton);


        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name = nameInput.getText().toString();
                time = timeInput.getText().toString();
                quantity = Integer.parseInt(quantityInput.getText().toString());
                dosage = Integer.parseInt(dosageInput.getText().toString());
                dayOfWeek = dayOfWeekInput.getText().toString();

                // setResult(RESULT_OK);
                    if (dayOfWeek.equalsIgnoreCase("monday")) {
                        FirstFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("tuesday")) {
                        SecondFragmentClass.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("wednesday")) {
                        ThirdFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("thursday")) {
                        FourthFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("friday")) {
                        FifthFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("saturday")) {
                        SixthFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    } else if (dayOfWeek.equalsIgnoreCase("sunday")) {
                        SeventhFragment.add_new_item(name, time, quantity, dosage);
                        Intent new_activity = new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(new_activity);
                    }
                }

        });
    }
}

FirstFragment Class

package com.example.myapplication;
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 androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class FirstFragment extends Fragment {
    private static final String ARG_COUNT = "param1";
    private Integer counter;
    private static Context context;
    private int[] COLOR_MAP = {
            R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
            R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
            R.color.green_500, R.color.green_700
    };
    private RecyclerView myRecyclerView;
    private static ArrayList<Medicine> medlist;
    private static recyclerViewAdapter anAdapter;
    private static int positionCounter;
    View view;
    public FirstFragment() {
        // Required empty public constructor
    }

    public static void add_new_item(String name, String time, int quantity, int dosage) {
        medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
        anAdapter.notifyItemInserted(medlist.size()-1);
        //anAdapter.notifyDataSetChanged();
    }

    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }


    public static FirstFragment newInstance(Integer counter) {
        FirstFragment fragment = new FirstFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COUNT, counter);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            counter = getArguments().getInt(ARG_COUNT);
        }
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_card, container, false);
        return v;
    }
    @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
        FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
        medlist = new ArrayList<>();
        positionCounter = 0;
        myRecyclerView = view.findViewById(R.id.prescription_list);
        myRecyclerView.setHasFixedSize(true);
        anAdapter = new recyclerViewAdapter(getContext(), medlist);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        myRecyclerView.setAdapter(anAdapter);

        new_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent new_activity = new Intent(context, add_medication_to_list.class);
                startActivity(new_activity);

        } });

}
    }

SecondFragment Class

package com.example.myapplication;

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 androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class SecondFragmentClass extends Fragment {

    private static final String ARG_COUNT = "param1";
    private Integer counter;
    private static Context context;
    private int[] COLOR_MAP = {
            R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
            R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
            R.color.green_500, R.color.green_700
    };
    private RecyclerView myRecyclerView;
    private static ArrayList<Medicine> medlist;
    private static recyclerViewAdapter anAdapter;
    private static int positionCounter;

    public static void add_new_item(String name, String time, int quantity, int dosage) {
        medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
        anAdapter.notifyItemInserted(medlist.size()-1);
        //anAdapter.notifyDataSetChanged();
        positionCounter++;

    }

    public static SecondFragmentClass newInstance(Integer counter) {
        SecondFragmentClass fragment = new SecondFragmentClass();
        Bundle args = new Bundle();
        args.putInt(ARG_COUNT, counter);
        fragment.setArguments(args);
        return fragment;
    }

    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
        positionCounter = 0;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            counter = getArguments().getInt(ARG_COUNT);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_card_2, container, false);
        return v;
    }
    @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
        FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
        positionCounter = 0;
        medlist = new ArrayList<>();
        myRecyclerView = view.findViewById(R.id.prescription_list_2);
        anAdapter = new recyclerViewAdapter(getContext(), medlist);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        myRecyclerView.setAdapter(anAdapter);

        new_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent new_activity = new Intent(context, add_medication_to_list.class);
                startActivity(new_activity);
            }
        });
    }
}

ThirdFragment Class

package com.example.myapplication;

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 androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class ThirdFragment extends Fragment {

    private static final String ARG_COUNT = "param1";
    private Integer counter;
    private static Context context;
    private int[] COLOR_MAP = {
            R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
            R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
            R.color.green_500, R.color.green_700
    };
    private RecyclerView myRecyclerView;
    private static ArrayList<Medicine> medlist = new ArrayList<>();
    private static recyclerViewAdapter anAdapter = new recyclerViewAdapter(context, medlist);
    private static int positionCounter;

    public static void add_new_item(String name, String time, int quantity, int dosage) {
        medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
        anAdapter.notifyItemInserted(medlist.size()-1);
        //anAdapter.notifyDataSetChanged();
        positionCounter++;

    }

    public static ThirdFragment newInstance(Integer counter) {
        ThirdFragment fragment = new ThirdFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COUNT, counter);
        fragment.setArguments(args);
        return fragment;
    }

    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
        positionCounter = 0;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            counter = getArguments().getInt(ARG_COUNT);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_card_3, container, false);
        return v;
    }
    @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
        FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
        positionCounter = 0;
        medlist = new ArrayList<>();
        myRecyclerView = view.findViewById(R.id.prescription_list_3);
        myRecyclerView.setHasFixedSize(true);
        anAdapter = new recyclerViewAdapter(getContext(), medlist);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        myRecyclerView.setAdapter(anAdapter);

        new_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent new_activity = new Intent(context, add_medication_to_list.class);
                startActivity(new_activity);
            }
        });
    }
}

FourthFragment Class

package com.example.myapplication;

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 androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class FourthFragment extends Fragment {

    private static final String ARG_COUNT = "param1";
    private Integer counter;
    private static Context context;
    private int[] COLOR_MAP = {
            R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
            R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
            R.color.green_500, R.color.green_700
    };
    private RecyclerView myRecyclerView;
    private static ArrayList<Medicine> medlist;
    private static recyclerViewAdapter anAdapter;
    private static int positionCounter;

    public static void add_new_item(String name, String time, int quantity, int dosage) {
        medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
        anAdapter.notifyItemInserted(medlist.size()-1);
        //anAdapter.notifyDataSetChanged();
        positionCounter++;

    }

    public static FourthFragment newInstance(Integer counter) {
        FourthFragment fragment = new FourthFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COUNT, counter);
        fragment.setArguments(args);
        return fragment;
    }

    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            counter = getArguments().getInt(ARG_COUNT);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_card_4, container, false);
        return v;
    }
    @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
        FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
        myRecyclerView = view.findViewById(R.id.prescription_list_4);
        positionCounter = 0;
        medlist = new ArrayList<>();
        anAdapter = new recyclerViewAdapter(getContext(), medlist);
        myRecyclerView.setHasFixedSize(true);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        myRecyclerView.setAdapter(anAdapter);

        new_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent new_activity = new Intent(context, add_medication_to_list.class);
                startActivity(new_activity);
            }
        });
    }
}

FifthFragment class

package com.example.myapplication;

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 androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class FifthFragment extends Fragment {

    private static final String ARG_COUNT = "param1";
    private Integer counter;
    private static Context context;
    private int[] COLOR_MAP = {
            R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
            R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
            R.color.green_500, R.color.green_700
    };
    private  RecyclerView myRecyclerView;
    private  static ArrayList<Medicine> medlist;
    private  static recyclerViewAdapter anAdapter;
    private static int positionCounter;

    public static void add_new_item(String name, String time, int quantity, int dosage) {
        medlist.add(new Medicine(name, time, quantity, dosage, R.drawable.resized_pill));
        anAdapter.notifyItemInserted(medlist.size()-1);
        //anAdapter.notifyDataSetChanged();
        positionCounter++;

    }

    public static FifthFragment newInstance(Integer counter) {
        FifthFragment fragment = new FifthFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COUNT, counter);
        fragment.setArguments(args);
        return fragment;
    }

    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
        positionCounter = 0;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            counter = getArguments().getInt(ARG_COUNT);
            positionCounter = 0;

        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_card_5, container, false);
        return v;
    }
    @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setBackgroundColor(ContextCompat.getColor(context, COLOR_MAP[counter]));
        FloatingActionButton new_button = view.findViewById(R.id.actionFloatingButton);
        medlist = new ArrayList<>();
        positionCounter = 0;
        myRecyclerView = view.findViewById(R.id.prescription_list_5);
        myRecyclerView.setHasFixedSize(true);
        anAdapter = new recyclerViewAdapter(getContext(), medlist);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        myRecyclerView.setAdapter(anAdapter);

        new_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent new_activity = new Intent(context, add_medication_to_list.class);
                startActivity(new_activity);
            }
        });
    }
}

ViewPagerAdapter

package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import java.util.ArrayList;

public class ViewPagerAdapter extends FragmentStateAdapter {
    private static final int CARD_ITEM_SIZE = 7;
    private ArrayList<Fragment> arrayList = new ArrayList<>();
    public ViewPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        return arrayList.get(position);
    }

    @Override public int getItemCount() {
        return CARD_ITEM_SIZE;
    }

    public void addFragment(Fragment fragment) {
        arrayList.add(fragment);

    }
}

recyclerViewAdapter

package com.example.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

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

    Context data;
    List<Medicine> new_list;

    public recyclerViewAdapter(Context data, List<Medicine> new_list) {
        this.data = data;
        this.new_list = new_list;
    }

    public recyclerViewAdapter() {
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(data).inflate(R.layout.new_items, parent, false);
        MyViewHolder view = new MyViewHolder(v);
        return view;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

        holder.new_name.setText(new_list.get(position).getName());
        holder.new_quantity.setText(Integer.toString(new_list.get(position).getFrequency()));
        holder.new_image.setImageResource(new_list.get(position).getPhoto());
        holder.new_time.setText(new_list.get(position).getTime());

    }

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

    public static class MyViewHolder extends RecyclerView.ViewHolder {

        private TextView new_name;
        private TextView new_quantity;
        private ImageView new_image;
        private TextView  new_time;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            new_name = itemView.findViewById(R.id.prescription_name);
            new_image = itemView.findViewById(R.id.new_image);
            new_quantity = itemView.findViewById(R.id.quantity_items);
            new_time = itemView.findViewById(R.id.new_time);

        }

    }
}

Medicine Class

package com.example.myapplication;

public class Medicine {

    private String name_of_medicine, time_to_take;
    private int quantity_remaining, Photo, frequency, dosage;

    public Medicine(String name_of_medicine, String time_to_take, int quantity, int dosage, int photo) {
        this.name_of_medicine = name_of_medicine;
        this.time_to_take = time_to_take;
        this.quantity_remaining = quantity;
        this.dosage = dosage;
        Photo = photo;
    }

    public String getName()
    {
        return name_of_medicine;
    }
    public String getTime()
    {
        return time_to_take;
    }
    public int getFrequency() {
        return quantity_remaining;
    }
    public int getPhoto() {
        return Photo;
    }
}
How to solve:

Resolved this issue. Used finish() after calling add_new_item() method.

Leave a Reply

Your email address will not be published. Required fields are marked *