vendredi 5 février 2021

How to save the state of a checkbox in a nested recyclerView(Parent->Child)

enter image description here

This is how it looks

I used Sharedpreferences, it did save the instance of a particular position of checkbox but it also saves the other itemlist(child list) at the different parent list. Is there a way to solve this or i need to use different method on saving the state of each checkbox? I hope someone can give a detailed answer as I'm still a beginner.

This is my code..

MainActivity.java

public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
ParentAdapter parentAdapter;
ArrayList<parentObj> parentObjList= new ArrayList<>();
ArrayList<childObj> childObjList;

Button addChecklist;
EditText listNameEdit;

private static ArrayList<String> itemName=new ArrayList<>();
private static String listName;

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

    listNameEdit=(EditText) findViewById(R.id.listName);

    addChecklist =(Button) findViewById(R.id.addList);
    addChecklist.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String getListName=listNameEdit.getText().toString();
            listName=getListName;
            addCheckList();
            saveData();
            listNameEdit.setText("");

            Intent a=new Intent(MainActivity.this,createList.class);
            startActivityForResult(a,1);
        }
    });


    setParentAdapter(parentObjList);
}

private void addCheckList(){
    childObjList= new ArrayList<>();
    parentObjList.add(new parentObj(listName,childObjList));
    parentAdapter.notifyDataSetChanged();
}

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
        if (resultCode == RESULT_OK) {
            ArrayList<String> returnItemName=data.getStringArrayListExtra("itemName");
            itemName=returnItemName;

            int size=itemName.size();
            for (int i=0;i<size;i++){
                childObjList.add(new childObj(itemName.get(i)));
                parentAdapter.notifyDataSetChanged();
            }
            saveData();
        }
    }
}

private void setParentAdapter(ArrayList<parentObj> parentLists){
    recyclerView=findViewById(R.id.parentRView);
    RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    parentAdapter=new ParentAdapter(this,parentLists);
    recyclerView.setAdapter(parentAdapter);
}

private void saveData() {
    SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    Gson gson = new Gson();
    String json = gson.toJson(parentObjList);
    editor.putString("task list", json);
    editor.apply();
}
private void loadData() {
    SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", Context.MODE_PRIVATE);
    Gson gson = new Gson();
    String json = sharedPreferences.getString("task list", null);
    Type type = new TypeToken<ArrayList<parentObj>>() {}.getType();
    parentObjList = gson.fromJson(json, type);
    if (parentObjList == null) {
        parentObjList = new ArrayList<>();
    }
}

}

createList.java

public class createList extends AppCompatActivity {

Button addItem;
Button done;
EditText itemName;
ArrayList<String> itemLists=new ArrayList<>();

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

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    int width=dm.widthPixels;
    int height=dm.heightPixels;
    getWindow().setLayout((int)(width*.99),(int)(height*.30));

    WindowManager.LayoutParams params = getWindow().getAttributes();
    params.gravity= Gravity.CENTER;
    params.x=0;
    params.y=20;
    getWindow().setAttributes(params);

    itemName=(EditText) findViewById(R.id.itemName);
    addItem=(Button) findViewById(R.id.addItem);
    addItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String getItemName=itemName.getText().toString();
            itemLists.add(getItemName);

            Intent a=new Intent();
            a.putExtra("itemName",itemLists);
            setResult(MainActivity.RESULT_OK,a);
            itemName.setText("");
        }
    });
    done=(Button) findViewById(R.id.done);
    done.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
}

}

parentObj.java

public class parentObj {
String parentName;
ArrayList<childObj> childItemList;

public parentObj(String parentName,ArrayList<childObj> childItemList){
    this.parentName=parentName;
    this.childItemList=childItemList;
}

public List<childObj> getChildItemList(){
    return childItemList;
}

public void setChildItemList(ArrayList<childObj> childItemList){
    this.childItemList=childItemList;
}

public String getParentName(){
    return parentName;
}

public void setParentName(String parentName){
    this.parentName=parentName;
}

}

ParentAdapter.java

public class ParentAdapter extends RecyclerView.Adapter<ParentAdapter.ViewHolder> {

private Context context;
private ArrayList<parentObj> parentObjList;
private onClickListener listener;

public interface onClickListener{
    void strikeIt(int position);
}

public void setOnClickListener(onClickListener listener){
    this.listener=listener;
}

public ParentAdapter(@NonNull Context context,ArrayList<parentObj> parentObjList) {
    this.context=context;
    this.parentObjList=parentObjList;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.parent_item, parent, false),listener);
}

@Override
public void onBindViewHolder(@NonNull ParentAdapter.ViewHolder holder, int position) {
    holder.parentName.setText(parentObjList.get(position).getParentName());
    setChildRV(holder.childList, (ArrayList<childObj>) parentObjList.get(position).getChildItemList());
}

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

public static final class ViewHolder extends RecyclerView.ViewHolder {

    TextView parentName;
    RecyclerView childList;

    public ViewHolder(@NonNull View itemView, final onClickListener listener) {
        super(itemView);

        parentName=itemView.findViewById(R.id.parentRVName);
        childList=itemView.findViewById(R.id.childRView);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        listener.strikeIt(position);
                    }
                }
            }
        });
    }
}

private void setChildRV(RecyclerView recyclerView,ArrayList<childObj> childObjList){
    childAdapter childAdapter=new childAdapter(context,childObjList);
    recyclerView.setLayoutManager(new LinearLayoutManager(context,RecyclerView.VERTICAL, false));
    recyclerView.setAdapter(childAdapter);
}

}

childObj.java

public class childObj {
String childName;
public boolean isChecked;

public childObj(String childName){
    this.childName=childName;
}

public String getChildName(){
    return childName;
}

public void setChildName(String childName) {
    this.childName = childName;
}

public boolean setSelected() {
    return isChecked;
}

}

childAdapter.java

public class childAdapter extends RecyclerView.Adapter<childAdapter.ViewHolder> {

private Context context;
private ArrayList<childObj> childObjList;
private onClickListener listener;

private boolean isMyValueChecked;
SharedPreferences sharedPreferences;

public interface onClickListener{
    void strikeIt(int position);
}

public void setOnClickListener(onClickListener listener){
    this.listener=listener;
}

public childAdapter(Context context,ArrayList<childObj> childObjList) {
    this.context=context;
    this.childObjList=childObjList;
}

public static final class ViewHolder extends RecyclerView.ViewHolder {

    CheckBox strikeIt;
    TextView childName;

    public ViewHolder(@NonNull View itemView,final onClickListener listener) {
        super(itemView);

        this.setIsRecyclable(false);

        strikeIt=(CheckBox) itemView.findViewById(R.id.strikeIt);
        childName=itemView.findViewById(R.id.childItemTV);

        strikeIt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (strikeIt.isChecked()){
                    childName.setPaintFlags(childName.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG);
                } else {
                    if ((childName.getPaintFlags()&Paint.STRIKE_THRU_TEXT_FLAG)==Paint.STRIKE_THRU_TEXT_FLAG){
                        childName.setPaintFlags(childName.getPaintFlags()&(~Paint.STRIKE_THRU_TEXT_FLAG));
                    }
                }
            }
        }); //end of listener

    } //end of viewHolder constructor
} //end of viewHolder class

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater=LayoutInflater.from(context);
    View view=inflater.inflate(R.layout.child_item,null);
    sharedPreferences= view.getContext().getSharedPreferences("My preference",Context.MODE_PRIVATE);
    isMyValueChecked= sharedPreferences.getBoolean("checkbox",false);

    return new ViewHolder(view,listener);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    holder.childName.setText(childObjList.get(position).getChildName());

    final childObj obj=childObjList.get(position);

    final String preferenceKey = "checkbox" + position;
    boolean isMyValueChecked= sharedPreferences.getBoolean(preferenceKey,false);
    holder.strikeIt.setChecked(isMyValueChecked);

    holder.strikeIt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean newState) {
            sharedPreferences.edit().putBoolean(preferenceKey, newState).apply();
        }
    });
}

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

}




Aucun commentaire:

Enregistrer un commentaire