如何在Android中更新RecyclerView的内容?

时间:2019-01-16 07:15:26

标签: android sqlite android-recyclerview

我制作了一个简单的提醒应用,其中将提醒,日期和时间存储在 SQLite数据库中。允许用户编辑删除内容。当用户在对话框中编辑内容时,我的 recyclerView 未更新。     目前,我每次进行修改后都会重新加载活动。是否有任何方法可以更新 recyclerView 每个修改?请帮帮我。

我会给你我的代码

public class Alarm extends Activity {
    TextView title;
    Button menu, info;
    RecyclerView recycler_alarm;
    SqliteHelper sqliteHelper;
    Alarm_Adapter alarm_adapter;
    LinearLayoutManager linearLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm);
        getAds();
        initialise();
    }
    private void initialise() {

        title = findViewById(R.id.currentMonth);
        menu = findViewById(R.id.settings);
        recycler_alarm=findViewById(R.id.recycler_alarm);
        Typeface karthika = Typeface.createFromAsset(getAssets(),
                "fonts/Karthika.ttf");
        title.setTypeface(karthika);
        menu.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Alarm.this, MenuList.class);
                startActivityForResult(intent, 1);
            }
        });
        info = (Button) this.findViewById(R.id.addEvent);
        info.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Alarm.this, Info.class);
                startActivity(intent);
            }
        });

        loadAlarm();


    }

    private void loadAlarm()
    {
        sqliteHelper=new SqliteHelper(Alarm.this);
        final List<Alarm_pojo> alarm_pojoList=sqliteHelper.getdata();
        if(alarm_pojoList!=null&&!alarm_pojoList.isEmpty())
        {
           alarm_adapter=new Alarm_Adapter(Alarm.this,alarm_pojoList);
           linearLayoutManager=new LinearLayoutManager(getApplicationContext());
           recycler_alarm.setLayoutManager(linearLayoutManager);

           alarm_adapter=new Alarm_Adapter(Alarm.this,alarm_pojoList, new Alarm_Adapter.MyAdapterListener() {
               @Override
               public void iconCancelOnClick(View v, final int position) {
                   Log.d("TAG", "iconCancelOnClick at position "+position);
                   final Dialog dialog=new Dialog(Alarm.this);
                   dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                   dialog.setContentView(R.layout.alarm_deletion_dialog);
                   try {
                       dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
                   }
                   catch(NullPointerException e)
                   {
                       e.printStackTrace();
                   }
                   Button btn_yes=dialog.findViewById(R.id.btn_yes);
                   Button btn_no=dialog.findViewById(R.id.btn_no);
                   TextView txt_alarm=dialog.findViewById(R.id.txt_alarm);
                   String month_alarm=alarm_pojoList.get(position).getMonth_alarm();
                   String date_alarm=alarm_pojoList.get(position).getDate_alarm();
                   String month_name=null;
                   switch(month_alarm)
                   {
                       case "1":
                           month_name="ജനുവരി";
                           break;
                       case "2":
                           month_name="ഫെബ്രുവരി";
                           break;
                       case "3":
                           month_name="മാർച്ച്";
                           break;
                       case "4" :
                           month_name="ഏപ്രിൽ";
                           break;
                       case "5":
                           month_name="മെയ്";
                           break;
                       case "6":
                           month_name="ജൂൺ";
                           break;
                       case "7":
                           month_name="ജൂലൈ";
                           break;
                       case "8" :
                           month_name="ആഗസ്റ്റ്";
                           break;
                       case "9":
                           month_name="സെപ്റ്റംബർ";
                           break;
                       case "10":
                           month_name="ഒക്ടോബർ";
                           break;
                       case "11":
                           month_name="നവംബർ";
                           break;
                       case "12":
                           month_name="ഡിസംബര്";
                           break;

                   }

                   String txt_header=month_name+"\t"+date_alarm+"\t"+"ലെ അലാറം നീക്കം ചെയ്യണോ?";
                   txt_alarm.setText(txt_header);

                   btn_yes.setOnClickListener(new View.OnClickListener() {
                       @Override
                       public void onClick(View view) {
                           int id=alarm_pojoList.get(position).getId();
                           sqliteHelper.clearAlarmList(id);
                           alarm_pojoList.remove(position);
                           recycler_alarm.setAdapter(alarm_adapter);
                           alarm_adapter.notifyDataSetChanged();
                           dialog.hide();
                       }
                   });
                   btn_no.setOnClickListener(new View.OnClickListener() {
                       @Override
                       public void onClick(View view) {
                           dialog.dismiss();
//                           String id=String.valueOf(alarm_pojoList.get(position).getId());
//                           Toast.makeText(Alarm.this,id,Toast.LENGTH_SHORT).show();
                       }
                   });
                   dialog.show();

               }
               @Override

               public void iconEditOnClick(View v, final int position)
               {
                   sqliteHelper=new SqliteHelper(Alarm.this);
                   final List<Alarm_pojo> alarm_pojoList=sqliteHelper.getdata();
                   Log.d("TAG", "iconEditOnClick at position "+position);
                   int id=alarm_pojoList.get(position).getId();
                   final Dialog dialog=new Dialog(Alarm.this);
                   dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                   dialog.setContentView(R.layout.alarm_edit_dialog);
                   try {
                       dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
                   }
                   catch(NullPointerException e)
                   {
                       e.printStackTrace();
                   }
                   Button btn_yes=dialog.findViewById(R.id.btn_yes);
                   Button btn_no=dialog.findViewById(R.id.btn_no);
                   TextView txt_editalarm=dialog.findViewById(R.id.txt_editalarm);
                   final TextView txt_month=dialog.findViewById(R.id.txt_month);
                   ImageView img_datepicker=dialog.findViewById(R.id.img_datepicker);
                   final TextView txt_hr=dialog.findViewById(R.id.txt_hr);
                   final EditText et_reminders=dialog.findViewById(R.id.et_reminders);
                   ImageView img_timepicker=dialog.findViewById(R.id.img_timepicker);
                   String month_alarm=alarm_pojoList.get(position).getMonth_alarm();
                   String date_alarm=alarm_pojoList.get(position).getDate_alarm();
                   String year_alarm=alarm_pojoList.get(position).getYear_alarm();
                   String time_alarm=alarm_pojoList.get(position).getTime_alarm();
                   final String reminder=alarm_pojoList.get(position).getReminder();
                   final String selected_date=date_alarm+"-"+month_alarm+"-"+year_alarm;
                   String month_name=null;
                   switch(month_alarm)
                   {
                       case "1":
                           month_name="ജനുവരി";
                           break;
                       case "2":
                           month_name="ഫെബ്രുവരി";
                           break;
                       case "3":
                           month_name="മാർച്ച്";
                           break;
                       case "4" :
                           month_name="ഏപ്രിൽ";
                           break;
                       case "5":
                           month_name="മെയ്";
                           break;
                       case "6":
                           month_name="ജൂൺ";
                           break;
                       case "7":
                           month_name="ജൂലൈ";
                           break;
                       case "8" :
                           month_name="ആഗസ്റ്റ്";
                           break;
                       case "9":
                           month_name="സെപ്റ്റംബർ";
                           break;
                       case "10":
                           month_name="ഒക്ടോബർ";
                           break;
                       case "11":
                           month_name="നവംബർ";
                           break;
                       case "12":
                           month_name="ഡിസംബര്";
                           break;

                   }
                    String text_header=month_name+"\t"+date_alarm+"\t"+"ലെ അലാറം നിങ്ങൾക്ക് എഡിറ്റുചെയ്യണോ?";
                    txt_editalarm.setText(text_header);
                    txt_month.setText(selected_date);
                    txt_hr.setText(time_alarm);
                    et_reminders.setText(reminder);
                    img_timepicker.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Calendar mCurrentTime=Calendar.getInstance();
                            int hour=mCurrentTime.get(Calendar.HOUR_OF_DAY);
                            int minute=mCurrentTime.get(Calendar.MONTH);
                            TimePickerDialog timePickerDialog;
                            timePickerDialog=new TimePickerDialog(Alarm.this, new TimePickerDialog.OnTimeSetListener() {
                                @Override
                                public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                                    String convert_hour=convertTime(selectedHour);
                                    String convert_minute=convertTime(selectedMinute);
                                    String time_selected=convert_hour+":"+convert_minute;
                                    final TextView txt_hr=dialog.findViewById(R.id.txt_hr);
                                    txt_hr.setText(time_selected);
                                }
                            },hour,minute,true);
                            timePickerDialog.setTitle("Select Time");
                            timePickerDialog.show();
                        }

                    });
                    img_datepicker.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            final Calendar myCalendar = Calendar.getInstance();
                            Calendar calendar = Calendar.getInstance();
                            //Setting maximum year as current year
                            calendar.set(2019, 11, 31);
                            DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

                                @Override
                                public void onDateSet(DatePicker view, int year, int monthOfYear,
                                                      int dayOfMonth) {
                                    myCalendar.set(Calendar.YEAR, year);
                                    myCalendar.set(Calendar.MONTH, monthOfYear);
                                    myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                    String myFormat = "dd-MM-yyyy"; //In which you need put here
                                    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
                                    String selected_date=sdf.format(myCalendar.getTime());
                                    String[] out=selected_date.split("-");
                                    String dateconverted=out[0];
                                    String monthconverted=out[1];
                                    String yearconverted=out[2];
                                    //Formating the date and month selected.
                                    //Removing intial zero appearing in the date and month selection
                                    String actual_date=convertSelection(dateconverted);
                                    String actual_month=convertSelection(monthconverted);
                                    String formatedvalue=actual_date+"-"+actual_month+"-"+yearconverted;
                                    //Setting the actual date on the textview.
                                    txt_month.setText(formatedvalue);
                                }

                            };
                      DatePickerDialog datePickerDialog=new DatePickerDialog(Alarm.this, R.style.MyPickerDialogTheme, date, myCalendar
                                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                                    myCalendar.get(Calendar.DAY_OF_MONTH));
                           //For avoiding the past days.
                            datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 10000);
                            //Restricting date picker to show only current year.
                            datePickerDialog.getDatePicker().setMaxDate(calendar.getTimeInMillis()+10000);
                            datePickerDialog.show();


                        }
                    });

                    btn_yes.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String month_selected = txt_month.getText().toString();
                            String time_selected = txt_hr.getText().toString();
                            String reminders = et_reminders.getText().toString();
                            int id=alarm_pojoList.get(position).getId();

                            if (!month_selected.equals("") && !time_selected.equals("") && !reminders.equals(""))
                            {
                                int result= sqliteHelper.updateAlarm(month_selected,time_selected,reminders,id);
                               if(result>0)
                               {
                                   finish();
                                   startActivity(getIntent());
                                   Toast.makeText(Alarm.this,"Updated",Toast.LENGTH_SHORT).show();
                                   dialog.hide();
                               }
                             }
                        else

                        {
                            Toast.makeText(Alarm.this,"Not Updated. Missing input fields!",Toast.LENGTH_SHORT).show();
                        }
                    }
                    });
                    btn_no.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.hide();
                        }
                    });

                   dialog.show();
               }
           });

            recycler_alarm.setAdapter(alarm_adapter);
            alarm_adapter.notifyDataSetChanged();
        }
        else
        {
            Toast.makeText(Alarm.this,"No Alarms added yet!..",Toast.LENGTH_SHORT).show();
        }


    }

    private String convertSelection(String dateconverted) {
        int date=Integer.parseInt(dateconverted);
        if(date>=10)
        {
            return String.valueOf(date);
        }
        else
        {
           return Integer.valueOf(dateconverted).toString();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                finish();
            }

        }
    }
    @Override
    public void onBackPressed() {
        Intent intent = new Intent(Alarm.this, CalendarActivity.class);
        finish();
        startActivity(intent);

    }

    private void getAds() {
        AdView adView = findViewById(R.id.adView1);
        AdRequest adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);
    }


    private String convertTime(int time_selected) {

        if(time_selected>=10)
        {
            return String.valueOf(time_selected);
        }
        else
        {
            return "0" + String.valueOf(time_selected);
        }
    }




}

强文本

1 个答案:

答案 0 :(得分:1)

您不必每次只在适配器中添加新值时设置适配器 alarm_pojoList,然后调用adapter.notifyDataSetChanged()

并且最好使用notifyiteminserted()代替notifyDataSetChanged并传递列表的大小以将值添加到列表的最后一个位置,或者如果需要将其添加到列表的顶部则传递0