mercredi 6 mai 2020

How to save the state of Multiple checkbox using a Button click

In my app I have a recyclerView of ArrayList in which i setted a checkBox next to the textView. what i want to save the state of all the checkBox by clicking a button. and i want to load it in another activity , and these all should done with the SharedPrefrennces.

Actually I am not getting the concept that how can i save the state of checkBox in SharedPrefrennces.

NOTE:Please keep in mind i am begginer

Here is the code that shows what i did ..

public class StudentListActivity extends AppCompatActivity {
private static final String DATETIME = "dateTime";
private RecyclerView recyclerView;
private RecyclerView.Adapter rAdapter;
private RecyclerView.LayoutManager layoutManager;
ArrayList<ListOfNames> listOfNames;


SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;

String t1 = "10";
String t2 = "100%";
Bundle bundle;
String subName;
Toolbar toolbar;
boolean[] items;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.student_list);

    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    bundle = getIntent().getExtras();
    subName = bundle.getString("Subject Name");
    if (bundle != null) {
        getSupportActionBar().setTitle(subName);
    }
    loadData();


    Calendar calendar = Calendar.getInstance();
    String currentDate = DateFormat.getDateTimeInstance().format(calendar.getTime());


    toolbar.setSubtitle(currentDate);
    fabButton();
    buildRecyclerView();


}

@Override
public void onBackPressed() {
    super.onBackPressed();
    Intent intent = new Intent(this, ScrollingActivity.class);
    intent.putExtra("count", listOfNames.size());
    startActivity(intent);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
        case R.id.changeDateTime:
            handleDate();

            return true;
        case R.id.pastAttendances:
            Intent intent = new Intent(this, PastAttendences.class);

            intent.putExtra("Title", subName);
            sharedPreferences = getSharedPreferences("MY_PREF", MODE_PRIVATE);
            editor = sharedPreferences.edit();

            String result = sharedPreferences.getString(DATETIME, null);



            intent.putExtra("key", result);

            editor.remove(DATETIME);
            editor.apply();
            startActivity(intent);

            return true;

        case R.id.saveButton:

            final String toolbarDateTime = toolbar.getSubtitle().toString();

            sharedPreferences = getSharedPreferences("MY_PREF", MODE_PRIVATE);
            editor = sharedPreferences.edit();
            editor.putString(DATETIME, toolbarDateTime);
            editor.apply();


            return true;
    }

    return super.onOptionsItemSelected(item);
}

public void handelTime(final CharSequence charSequence) {

    final Calendar calendar = Calendar.getInstance();

    int Hour = calendar.get(Calendar.HOUR);
    int Minute = calendar.get(Calendar.MINUTE);

    boolean is24Hour = android.text.format.DateFormat.is24HourFormat(this);

    TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int Hour, int Minute) {


            Calendar calendar1 = Calendar.getInstance();

            calendar1.set(Calendar.HOUR, Hour);
            calendar1.set(Calendar.MINUTE, Minute);

            CharSequence charSequence1 = android.text.format.DateFormat.format("HH:mm:ss a", calendar1);
            toolbar.setSubtitle(charSequence + " " + charSequence1);
        }
    }, Hour, Minute, is24Hour);
    timePickerDialog.show();
}

public void handleDate() {

    final Calendar calendar = Calendar.getInstance();

    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int date = calendar.get(Calendar.DATE);

    DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int date) {


            Calendar calendar1 = Calendar.getInstance();

            calendar1.set(Calendar.YEAR, year);
            calendar1.set(Calendar.MONTH, month);
            calendar1.set(Calendar.DATE, date);

            CharSequence charSequence = android.text.format.DateFormat.format("dd-MMM-yyyy", calendar1);

            handelTime(charSequence);
        }
    }, year, month, date);

    datePickerDialog.show();
}


private void buildRecyclerView() {

    recyclerView = findViewById(R.id.recyclerView2);
    recyclerView.hasFixedSize();
    layoutManager = new LinearLayoutManager(StudentListActivity.this);
    rAdapter = new AdapterForStudentList(this, listOfNames);

    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(rAdapter);

    ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
    itemTouchHelper.attachToRecyclerView(recyclerView);

}

public void insertData(String text, String t1, String t2) {
    ListOfNames lt = new ListOfNames(text, t1, t2);
    if (listOfNames.contains(lt)) {
        Toast.makeText(this, "Student Name Already exists!!", Toast.LENGTH_SHORT).show();
    } else {
        listOfNames.add(lt);
        rAdapter.notifyDataSetChanged();
    }

}

public void saveData() {
    sharedPreferences = getSharedPreferences("SHARED PREF", MODE_PRIVATE);
    editor = sharedPreferences.edit();

    Gson gson = new Gson();
    String json = gson.toJson(listOfNames);
    editor.putString(subName, json);
    editor.apply();
}

public void loadData() {


    sharedPreferences = getSharedPreferences("SHARED PREF", MODE_PRIVATE);

    Gson gson = new Gson();
    String json = sharedPreferences.getString(subName, null);
    Type type = new TypeToken<ArrayList<ListOfNames>>() {
    }.getType();

    listOfNames = gson.fromJson(json, type);

    if (listOfNames == null) {
        listOfNames = new ArrayList<>();
    }
}


ListOfNames deletedItem = null;
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
    @Override
    public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
        return false;
    }

    @Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
        final int position = viewHolder.getAdapterPosition();
        String name = listOfNames.get(position).getStudentName();

        deletedItem = listOfNames.get(position);
        listOfNames.remove(deletedItem);

        sharedPreferences = getSharedPreferences("SHARED PREF", MODE_PRIVATE);
        editor = sharedPreferences.edit();
        editor.remove("text");


        saveData();
        editor.apply();
        rAdapter.notifyItemRemoved(position);

        Snackbar.make(recyclerView, name + "Deleted", Snackbar.LENGTH_LONG)
                .setAction("Undo", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        listOfNames.add(position, deletedItem);
                        rAdapter.notifyItemInserted(position);

                        saveData();
                    }
                }).show();
    }

    @Override
    public void onChildDrawOver(@NonNull Canvas c, @NonNull RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
        new RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)

                .addSwipeLeftBackgroundColor(ContextCompat.getColor(StudentListActivity.this, R.color.my_background))
                .addSwipeLeftActionIcon(R.drawable.ic_delete_black_24dp)
                .create()
                .decorate();
        super.onChildDrawOver(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);

    }
};

public void fabButton() {
    FloatingActionButton floatingActionButton = findViewById(R.id.fab2);
    floatingActionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder b = new AlertDialog.Builder(StudentListActivity.this);
            View view = getLayoutInflater().inflate(R.layout.dialogbox_frontpage, null);

            final EditText editText = view.findViewById(R.id.editText);
            b.setView(view);
            b.setTitle("Student name");
            b.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String text = editText.getText().toString().trim();

                    if (text.isEmpty()) {
                        Toast.makeText(StudentListActivity.this, "Please add subject name", Toast.LENGTH_SHORT).show();
                    } else {
                        insertData(text, t1, t2);
                        saveData();
                    }
                }
            });
            b.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            b.setCancelable(false);
            b.show();
        }
    });
}

}

This is the Adapter for above code...

public class AdapterForStudentList extends RecyclerView.Adapter<AdapterForStudentList.StudentViewHolder> {

Context context;
private ArrayList<ListOfNames> mListOfNames;

public static class StudentViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    public TextView studentName, attendence, percentage;
    CheckBox mCheckedBox;
    private ItemClickListener itemClickListener;

    public StudentViewHolder(@NonNull View itemView) {
        super(itemView);
        studentName = itemView.findViewById(R.id.studentName);
        attendence = itemView.findViewById(R.id.attendence);
        percentage = itemView.findViewById(R.id.percentage);
        mCheckedBox = itemView.findViewById(R.id.mCheckBox);
        mCheckedBox.setOnClickListener(this);
    }

    public void setItemClickListener(ItemClickListener ic) {
        itemClickListener = ic;
    }

    @Override
    public void onClick(View v) {
        itemClickListener.onItemClick(v, getLayoutPosition());
    }

    interface ItemClickListener {
        void onItemClick(View v, int position);
    }

}

public AdapterForStudentList(Context context, ArrayList<ListOfNames> listOfNames) {
    this.context = context;
    mListOfNames = listOfNames;
}

@NonNull
@Override
public StudentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.check_box_cardview, parent, false);

    return new StudentViewHolder(view);
}

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

    ListOfNames currentItems = mListOfNames.get(position);
    holder.studentName.setText(currentItems.getStudentName());
    holder.attendence.setText(currentItems.getAttendent());
    holder.percentage.setText(currentItems.getPercetage());
    holder.mCheckedBox.setChecked(currentItems.getChecked());


    holder.setItemClickListener(new StudentViewHolder.ItemClickListener() {
        @Override
        public void onItemClick(View v, int position) {
            CheckBox checkBox = (CheckBox) v;

            ListOfNames currentItems = mListOfNames.get(position);

            if (checkBox.isChecked()) {

                currentItems.setChecked(true);

            } else {
                currentItems.setChecked(false);
            }
        }
    });

}



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



Aucun commentaire:

Enregistrer un commentaire