-1

When I scroll the listView with the selected checkboxes they are unchecked when I scroll back. I know this is because of Recycler View but I don't know how to handle checkbox states. Kindly help me in this issue. I tried my best by seeing different tutorials and video's but not get what I need. I am new to android development. All the code is below. Kindly help me out.

Category.java

/**
 * Created by Ali on 14-06-2017.
 */

public class Category {

    private String categoryName;
    private int imageResourceId;
    private boolean isChecked;

    public Category(String categoryName, int imageResourceId)
    {
        this.categoryName = categoryName;
        this.imageResourceId = imageResourceId;
    }

    public Category(String categoryName, int imageResourceId, boolean isCheck)
    {
        this.categoryName = categoryName;
        this.imageResourceId = imageResourceId;
        this.isChecked = isCheck;
    }

    public void setCategoryName(String categoryName)
    {
        this.categoryName = categoryName;
    }
    public String getCategoryName()
    {
        return categoryName;
    }

    public void setImageResourceId(int imageResourceId)
    {
        this.imageResourceId = imageResourceId;
    }

    public int getImageResourceId()
    {
        return imageResourceId;
    }
    public boolean getIsChecked()
    {
        return this.isChecked;
    }
    public void setIsChecked(boolean value)
    {
        this.isChecked = value;
    }
}

CategoryAdapter.java

import android.app.Activity;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Ali on 14-06-2017.
 */

public class CategoryAdapter extends ArrayAdapter<Category> {

    private int imageResourceId;

    public CategoryAdapter(Activity context, ArrayList<Category> categories, int newImageResourceId) {

        super(context, 0, categories);


        imageResourceId = newImageResourceId;
    }

    public CategoryAdapter(CategoryActivityScreen activityScreen, ArrayList<Category> categories) {
        super(activityScreen, 0, categories);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Check if the existing view is being reused, otherwise inflate the view

        View listItemView = convertView;
        if (listItemView == null) {

            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);

        }

        //Below code is before the extra code is written

        // Get the {@link AndroidFlavor} object located at this position in the list
        Category currentCategory = getItem(position);
        ImageView imageView = (ImageView) listItemView.findViewById(R.id.image);

        imageView.setImageResource(currentCategory.getImageResourceId());
        imageView.setVisibility(View.VISIBLE);

        TextView categoryTextView = (TextView) listItemView.findViewById(R.id.categoryNames);
        // Get the version name from the current AndroidFlavor object and
        // set this text on the name TextView
        categoryTextView.setText(currentCategory.getCategoryName());


        CheckBox checkBox = (CheckBox) listItemView.findViewById(R.id.checkbox);
        //checkBox.setChecked(false);

        checkBox.setChecked(currentCategory.getIsChecked());


        return listItemView;

    }


}

CategoryActivityScreen.java

import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Ali on 14-06-2017.
 */

public class CategoryActivityScreen extends AppCompatActivity {


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

        //Currently dummy list is populated
        // Create a list of categories


        final ArrayList<Category> categories = new ArrayList<Category>();
        categories.add(new Category("Food", R.drawable.food_icon, false));
        categories.add(new Category("Theater", R.drawable.theater_icon, false));
        categories.add(new Category("Places", R.drawable.place_icon, false));
        categories.add(new Category("Games", R.drawable.game_icon, false));

        categories.add(new Category("Food", R.drawable.food_icon, false));
        categories.add(new Category("Games", R.drawable.game_icon, false));
        categories.add(new Category("Food", R.drawable.food_icon, false));
        categories.add(new Category("Theater", R.drawable.theater_icon, false));
        categories.add(new Category("Places", R.drawable.place_icon, false));
        categories.add(new Category("Games", R.drawable.game_icon, false));

        categories.add(new Category("Food", R.drawable.food_icon, false));
        categories.add(new Category("Games", R.drawable.game_icon, false));
        categories.add(new Category("Food", R.drawable.food_icon, false));
        categories.add(new Category("Theater", R.drawable.theater_icon, false));
        categories.add(new Category("Places", R.drawable.place_icon, false));
        categories.add(new Category("Games", R.drawable.game_icon, false));

        categories.add(new Category("Food", R.drawable.food_icon, false));
        categories.add(new Category("Games", R.drawable.game_icon, false));


        // Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The
        // adapter knows how to create list items for each item in the list.

        final CategoryAdapter adapter = new CategoryAdapter(this, categories);


        // Find the {@link ListView} object in the view hierarchy of the {@link Activity}.
        // There should be a {@link ListView} with the view ID called list, which is declared in the
        // word_list.xml layout file.
        ListView listView = (ListView) findViewById(R.id.list);


        //Code for adding footer to listView where list ends. Show's button at the end for next screen
        //---Strats here-----
        LayoutInflater inflater = getLayoutInflater();
        ViewGroup footer = (ViewGroup) inflater.inflate(R.layout.footer_categories_button, listView, false);
        listView.addFooterView(footer, null, true);
        //---Ends here------

        // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the
        // {@link ListView} will display list items for each {@link Word} in the list.

        //// listView.setAdapter(adapter);

    }


}

category_list.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:orientation="horizontal"
    android:minHeight="60dp">


    <ImageView
        android:layout_width="88dp"
        android:layout_height="88dp"
        android:id="@+id/image" />

    <LinearLayout
        android:id="@+id/text_container"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:orientation="vertical"
        android:paddingLeft="16dp"
        android:layout_toRightOf="@+id/image">

        <TextView
            android:id="@+id/categoryNames"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            tools:text="Food"
            android:textAppearance="?android:textAppearanceMedium"
            android:textColor="#000000"
            android:textStyle="bold"
            android:gravity="center" />



    </LinearLayout>

    <CheckBox
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="16dp"
        android:id="@+id/checkbox"
        />

</RelativeLayout>
Ali Ashraf
  • 31
  • 3
  • 2
    You never update the "checked" status in your category model item. You should attach listener to your checkbox and update the model on the "checked/unchecked" event. Also there is no recyclerView used in this code only the old "listview". – mhenryk Jun 19 '17 at 11:06
  • @mhenryk you mean I set the status to "True" or "False" in the memeber boolean variable? – Ali Ashraf Jun 19 '17 at 11:11
  • @mhenryk if possible please let me know where to make the changes. In which class or else – Ali Ashraf Jun 19 '17 at 11:33
  • You must use `setOnCheckedChangeListener`. Example [setOnCheckedChangeListener](https://stackoverflow.com/questions/8386832/android-checkbox-listener). – Aslan Debishev Jun 19 '17 at 20:18
  • You need onCheckedChangeListener or OnClickedListener for your checkbox. In the listener, update your data list and then call notifyDataSetChanged(). I've blog about ListView: http://programandroidlistview.blogspot.com/. Take a look at the sample for simple adapter. Hope that help! – i_A_mok Jun 20 '17 at 09:17
  • Can someone help me in my code. I tried everything but failed. Waiting for some genius to help me out. – Ali Ashraf Jun 20 '17 at 13:04

2 Answers2

0

CategoryAdapter

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    /* Some need code here */ 

    CheckBox checkBox = (CheckBox) listItemView.findViewById(R.id.checkbox);
    checkBox.setChecked(currentCategory.getIsChecked());
    checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

           @Override
           public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                if(isChecked){
                    currentCategory.setIsChecked(true)
                }else{
                    currentCategory.setIsChecked(false)
                }
           }
       }
    );
    return listItemView;
}
0

After a long long long search I found my answer on vogella. These people are awesome. If I say I search hundered's of tutorials I am not wrong. At last finally vogella helped me out.

CategoryAdapter.java

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

public class CategoryAdapter extends ArrayAdapter<Category> {

    private final ArrayList<Category> list;
    private final Activity context;

    public CategoryAdapter(Activity context, ArrayList<Category> list) {
        super(context, R.layout.list_item, list);
        this.context = context;
        this.list = list;
    }

    static class ViewHolder {
        protected ImageView imageView;
        protected TextView text;
        protected CheckBox checkbox;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
            view = inflator.inflate(R.layout.list_item, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.imageView = (ImageView) view.findViewById(R.id.image);
            viewHolder.text = (TextView) view.findViewById(R.id.categoryNames);
            viewHolder.checkbox = (CheckBox) view.findViewById(R.id.checkbox);
            viewHolder.checkbox
                    .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(CompoundButton buttonView,
                                                     boolean isChecked) {
                            Category element = (Category) viewHolder.checkbox
                                    .getTag();
                            element.setIsChecked(buttonView.isChecked());

                        }
                    });
            view.setTag(viewHolder);
            viewHolder.checkbox.setTag(list.get(position));
        } else {
            view = convertView;
            ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
        }
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.imageView.setImageResource(list.get(position).getImageResourceId());
        holder.text.setText(list.get(position).getCategoryName());
        holder.checkbox.setChecked(list.get(position).getIsChecked());
        return view;
    }
}
Ali Ashraf
  • 31
  • 3