How to Refresh Fragment with new Data

194 Views Asked by At

I have a fragment in which i have 2 designs, 1 design shows all the items stores within my database and out them into a table. Design 2 is where you can add them. Once finishing design 2, when you go back the TableLayout is gone and the new item is not there. Can anyone help and tell me what the issue is

public class Device extends Fragment {

    public Device() {
        // Required empty public constructor
    }

    //FOR CALENDAR
    final Calendar myCalendar = Calendar.getInstance();
    TextView CalendarTxt, TimeTxt;
    EditText ReminderTxt;

    //FOR CALENDAR
    private void updateLabel(TextView edittext) {
        String myFormat = "dd/MM/yy"; //In which you need put here
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.UK);

        edittext.setText(sdf.format(myCalendar.getTime()));
    }

    //FOR CALENDAR
    DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateLabel(CalendarTxt);
        }

    };
    public void Refresh() {
        SQLiteDatabase db = getActivity().openOrCreateDatabase("NotificationDatabase", android.content.Context.MODE_PRIVATE, null);
        Cursor data = db.rawQuery("SELECT * FROM PersonalNotif", null);
        Log.d("Count", String.valueOf(data.getCount()));
        if (data.getCount() > 0) {
            data.moveToFirst();
            //Database values taken and added
            do {
                View tableRow = LayoutInflater.from(getContext()).inflate(R.layout.table_item, null, false);
                TextView name = (TextView) tableRow.findViewById(R.id.TblItemName);
                TextView date = (TextView) tableRow.findViewById(R.id.TblItemDate);

                name.setText(data.getString(0));
                date.setText(data.getString(1));

            } while (data.moveToNext());
            data.close();
        }

    }

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_device, container, false);

        ViewGroup placeholder = (ViewGroup) rootView;

        CircleButton AddNotifBtn = rootView.findViewById(R.id.AddNotifBtn);
        TableLayout tableLayout = rootView.findViewById(R.id.tableLayout);
        //Database established
        SQLiteDatabase db = getActivity().openOrCreateDatabase("NotificationDatabase", android.content.Context.MODE_PRIVATE, null);
        Cursor data = db.rawQuery("SELECT * FROM PersonalNotif", null);

        Log.d("Count", String.valueOf(data.getCount()));
        if (data.getCount() > 0) {
            data.moveToFirst();
            //Database values taken and added
            do {
                View tableRow = LayoutInflater.from(getContext()).inflate(R.layout.table_item, null, false);
                TextView name = (TextView) tableRow.findViewById(R.id.TblItemName);
                TextView date = (TextView) tableRow.findViewById(R.id.TblItemDate);

                name.setText(data.getString(0));
                date.setText(data.getString(1));
                tableLayout.addView(tableRow);

                tableRow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                                .setIcon(android.R.drawable.ic_dialog_alert)
                                .setTitle("Do you want to Delete Reminder- " + name.getText().toString())
                                .setMessage("Accepting will delete the Chosen Reminder")
                                .setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        db.delete("PersonalNotif", "NameOfNotif=? and TimeOfNotif=?", new String[]{name.getText().toString(), date.getText().toString()});
                                        Refresh();
                                        tableLayout.removeView(tableRow);

                                    }
                                })
                                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                    }
                                })
                                .show();

                    }
                });


            } while (data.moveToNext());
            data.close();

        }

        AddNotifBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Refresh();


                View newView = inflater.inflate(R.layout.fragment_device2, container, false);
                View oldView = inflater.inflate(R.layout.fragment_device, container, false);
                //All New Views need newView before hand

                /// Calender Button Code Start
                CalendarTxt = newView.findViewById(R.id.CurrentDateSelect);
                CircleButton CalendarButton = newView.findViewById(R.id.calendarBtn);
                CalendarButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new DatePickerDialog(getContext(), date, myCalendar
                                .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),   //Refers Back to Method at the Top
                                myCalendar.get(Calendar.DAY_OF_MONTH)).show();
                    }
                });
                /// Calender Button Code End

                /// Clock Button Code Start
                TimeTxt = newView.findViewById(R.id.CurrentTimeSelect);
                Calendar mcurrentTime = Calendar.getInstance();
                int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY); //All the Variables needed
                int minute = mcurrentTime.get(Calendar.MINUTE);
                CircleButton ClockButton = newView.findViewById(R.id.timeBtn);
                ClockButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TimePickerDialog mTimePicker;
                        mTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                                @SuppressLint("DefaultLocale") String curTime = String.format("%02d:%02d", selectedHour, selectedMinute);
                                TimeTxt.setText(curTime);
                            }
                        }, hour, minute, true);//Yes 24 hour time
                        mTimePicker.setTitle("Select Time");
                        mTimePicker.show();
                    }
                });
                /// Clock Button Code End

                /// Proceed Button Code Start
                Button ProceedBtn = newView.findViewById(R.id.ProceedBtn);
                ProceedBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ReminderTxt = newView.findViewById(R.id.ReminderTxt);
                        String TimeVal = TimeTxt.getText().toString();
                        String DateVal = CalendarTxt.getText().toString();  //ID initialisation
                        String RemindVal = ReminderTxt.getText().toString();

                        if ((TimeVal + DateVal + RemindVal).isEmpty()) {
                            Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
                        } else if ((TimeVal + DateVal).isEmpty()) {
                            Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
                        } else if ((TimeVal + RemindVal).isEmpty()) {
                            Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
                        } else if ((DateVal + RemindVal).isEmpty()) {
                            Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
                        } else {
                            String FinalAlarmVal = DateVal + " " + " " + TimeVal; //Combines time and Date to make final Val

                            String AlarmHour = TimeVal.substring(0, 2);
                            String AlarmMins = TimeVal.substring(3, 5); //Gets Key Part of TextView

                            String AlarmMonth = DateVal.substring(3, 5);
                            String AlarmDay = DateVal.substring(0, 2);  //Gets Key Part of TextView


                            AlarmScheduler.setReminder(getContext(), Integer.parseInt(AlarmHour), Integer.parseInt(AlarmMins),
                                    Integer.parseInt(AlarmDay), Integer.parseInt(AlarmMonth)); // Here mContext is Context of Activity. If you use this code in Activity then you can pass ActivityName.this and in Fragment you can do getActivity()
                            try {

                                ContentValues values = new ContentValues();
                                values.put("NameOfNotif", RemindVal);
                                values.put("TimeOfNotif", FinalAlarmVal);    //Adds into Database

                                db.insert("PersonalNotif", null, values);

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            placeholder.removeAllViews();
                            placeholder.addView(oldView);
                            Refresh();
                        }
                    }
                });
                /// Proceed Button Code End


                /// Proceed Button Code Start
                Button CancelBtn = newView.findViewById(R.id.CancelBtn);
                CancelBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Fragment currentFragment = getActivity().getSupportFragmentManager().findFragmentById(R.id.container);
                        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                        fragmentTransaction.detach(currentFragment);
                        fragmentTransaction.attach(currentFragment);
                        fragmentTransaction.commit();


                        placeholder.removeAllViews();
                        placeholder.addView(oldView);

                    }
                });
                /// Proceed Button Code End

                //placeholder.removeAllViews();   //These two lines replace old view for the new one
                placeholder.addView(newView);

            }
        });

        return rootView;
    }

}
0

There are 0 best solutions below