0

I have an ExpandableListView where each row consists of a CheckBox and a TextView. When the group is expanded, I need to initialize each of the check boxes based on data pulled from a sqlite database (and stored in an ArrayList). I've got the array list. That's easy.

What I am unable to do is get a handle on each of these checkboxes. Right now, now matter what I do, I continue to get null pointer errors when I try to refer to any of them. Here is my code (which is inside of my onCreate method for the activity):

expandableList.setOnGroupClickListener(new OnGroupClickListener() {

    @Override
    public boolean onGroupClick(ExpandableListView parent, View v, int groupPostition, long id) {

        //this initializes to 0 
        int i = expandableList.getLastVisiblePosition() - expandableList.getFirstVisiblePosition();

        for (MySettings thisSetting : settingsList) {
            System.err.println(i);
            View view = parent.getChildAt(i);
            CheckBox checkBox = (CheckBox) view.findViewById(R.id.check_box); //<--null pointer error
            System.err.println(thisSetting.getIsSelected());
            checkBox.setChecked(thisSetting.getIsSelected());
            i++;
        }

        return false;
    }

});

I get the null pointer error on the line where I declare the checkBox variable. I've used almost identical code to handle the onChildClick event, so I don't understand how this is different. Thanks for any help. Let me know if you need additional code.

1 Answer 1

1

I will try to explain the way I did it on my application.

You first have to create your own custom adapter that will allow you to initialize the lists with your list, array or whatever you use:

public class CustomELVAdapter extends BaseExpandableListAdapter {


private LayoutInflater mInflater;
private ArrayList<AttributeFilter> mParent;//List containing the groups to display

public CustomELVAdapter(Context context, ArrayList<AttributeFilter> parent){
    mParent = parent;
    mInflater = LayoutInflater.from(context);
}


@Override
//counts the number of groups in the exapndable list
public int getGroupCount() {
    return mParent.size();
}

@Override
//counts the number of children items contained in a specific group
public int getChildrenCount(int groupPosition) {
    return mParent.get(groupPosition).getArrayChildren().size();
}

@Override
//gets the title ofa group
public Object getGroup(int groupPosition) {
    return mParent.get(groupPosition).getTitle();
}

@Override
//gets a child object in a group
public Object getChild(int groupPosition, int childPosition) {
    //return mParent.get(groupPosition).getArrayChildren().get(childPosition);
    return mParent.get(groupPosition).getArrayChildren().valueAt(childPosition);
}

@Override
public long getGroupId(int i) {
    return i;
}

@Override
public long getChildId(int i, int i1) {
    return i1;
}

@Override
public boolean hasStableIds() {
    return true;
}

@Override
//in this method you must set the text to see the parent/group on the list
public View getGroupView(int groupPosition, boolean b, View view, ViewGroup viewGroup) {

    if (view == null) {
        view = mInflater.inflate(R.layout.filter_list_parent, viewGroup,false);
    }

    TextView textView = (TextView) view.findViewById(R.id.filter_list_parent_textview);
    TextView detailsTV = (TextView) view.findViewById(R.id.filter_list_parent_details);

    Object parentObject = mParent.get(groupPosition);
    AttributeFilter attributeFilter = (AttributeFilter) parentObject;
    //"i" is the position of the parent/group in the list
    textView.setText(getGroup(groupPosition).toString());
    detailsTV.setText(attributeFilter.getDetails());

    //return the entire view
    return view;
}

@Override
//set a child in a group
public View getChildView(int groupPosition, int childPosition, boolean b, View view, ViewGroup viewGroup) {
    ViewHolder holder;
    if (view == null) {
        view = mInflater.inflate(R.layout.filter_list_child, viewGroup,false);
        holder = new ViewHolder();
        //holder.imageView = (ImageView) view.findViewById(R.id.filter_list_child_imageview);
        holder.checkbox = (CheckBox) view.findViewById(R.id.filter_list_child_checkbox);
        holder.title = (TextView) view.findViewById(R.id.filter_list_child_textview);

        view.setTag(holder);
    }
    else {  
        holder = (ViewHolder) view.getTag();  
    }   

    try {
        Attribute attribute = mParent.get(groupPosition).getArrayChildren().valueAt(childPosition);

        holder.checkbox.setChecked(attribute.isSelected());
        holder.title.setText(attribute.getName());

        view.setTag(R.string.filter_attribute_id, attribute.getID());
    } catch (Exception e) {
        Log.e(RateDayApplication.LOG_ERROR,"CustomELVAdapter - getChildView - attribute is null");
    }

    //return the entire view
    return view;
}

@Override
public boolean isChildSelectable(int i, int i1) {
    return true;
}

@Override
public void registerDataSetObserver(DataSetObserver observer) {
    /* used to make the notifyDataSetChanged() method work */
    super.registerDataSetObserver(observer);
}

static class ViewHolder {
    CheckBox checkbox;
    TextView title;
    //ImageView icon; NOT NEEDED YET
}

}

In my example, the children in mParent are all contained in SparseArray, it is convenient for me because I need to access the children with a specific ID, not just a position. But in your case you can of course you anything, if you use a list for example you will have to modify the code to modify the valueAt by a get (valueAt is a function available for SparseArrays but not for lists).

Once this adapter is done, you have to prepare in your activity the data to provide. In my case, I have 3 groups (fixed) all containing a different number of children:

ArrayList<AttributeFilter> arrayParents = new ArrayList<AttributeFilter>();//Initialize of the parents array that will be provided to the adapter.

    //Preparation of the first group (AttributeFilter is a custom type I created holding the `SparseArray` with the children and the group title)
    AttributeFilter categoriesFilter = new AttributeFilter();
    categoriesFilter.setTitle(getResources().getString(R.string.categories));
    categoriesFilter.setDetails(Tools.getLabelsStringFromSparseArray(categoriesSparseArray, prefs.getCategories()));
    categoriesSparseArray = Tools.initializeSparseArray(categoriesSparseArray, prefs.getCategories());
    categoriesFilter.setArrayChildren(categoriesSparseArray);

    //Preparation of the second group
    AttributeFilter emotionsFilter = new AttributeFilter();
    emotionsFilter.setTitle(getResources().getString(R.string.emotions));
    emotionsFilter.setDetails(Tools.getLabelsStringFromSparseArray(emotionsSparseArray, prefs.getEmotions()));
    emotionsSparseArray = Tools.initializeSparseArray(emotionsSparseArray, prefs.getEmotions());
    emotionsFilter.setArrayChildren(emotionsSparseArray);

    //Preparation of the third group
    AttributeFilter ratingsFilter = new AttributeFilter();
    ratingsFilter.setTitle(getResources().getString(R.string.ratings));
    ratingsFilter.setDetails(Tools.getLabelsStringFromSparseArray(ratingsSparseArray, prefs.getRatings()));
    ratingsSparseArray = Tools.initializeSparseArray(ratingsSparseArray, prefs.getRatings());
    ratingsFilter.setArrayChildren(ratingsSparseArray);

    //in this array we add the Parent object. We will use the arrayParents at the setAdapter
    arrayParents.add(categoriesFilter);
    arrayParents.add(emotionsFilter);
    arrayParents.add(ratingsFilter);

    //sets the adapter that provides data to the list.
    filtersELV.setAdapter(new CustomELVAdapter(this,arrayParents));//the adapter is applied on my `ExpandableListView`.

Here is the custom type definition FilterAttribute (FYI):

public class AttributeFilter {
private String mTitle;
private String mDetails;
private SparseArray<Attribute> mArrayChildren;

public String getTitle() {
    return mTitle;
}

public void setTitle(String mTitle) {
    this.mTitle = mTitle;
}

public String getDetails() {
    return mDetails;
}

public void setDetails(String mDetails) {
    this.mDetails = mDetails;
}

public SparseArray<Attribute> getArrayChildren() {
    return mArrayChildren;
}

public void setArrayChildren(SparseArray<Attribute> mArrayChildren) {
    this.mArrayChildren = mArrayChildren;
}

}

Just in case, the class Attribute:

public class Attribute {

private int id;
private String name;
private boolean selected;
private int drawableID;

// constructor
public Attribute(int _id, String _name, int _drawable_id, boolean _selected){
    id = _id;
    name = _name;
    drawableID = _drawable_id;
    selected = _selected;       
}

public int getID() {
    return id;
}

public void setID(int _id) {
    this.id = _id;
}

public String getName() {
    return name;
}

public void setName(String _name) {
    this.name = _name;
}

public int getDrawableID() {
    return drawableID;
}

public void setDrawableID(int _drawable_id) {
    this.drawableID = _drawable_id;
}

public boolean isSelected() {
    return selected;
}

public void setSelected(boolean _selected) {
    this.selected = _selected;
}

}

One thing important for the layout, you must set the checkbox as non focusable, otherwise you will never be able to make the checkbox toggle work:

<?xml version="1.0" encoding="utf-8"?>

<CheckBox android:id="@+id/filter_list_child_checkbox"
       android:focusable="false"
       android:focusableInTouchMode="false"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>

<TextView
    android:id="@+id/filter_list_child_textview"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:padding="10dp"
    android:layout_weight="1" />

I hope it is not too difficult to digest

7
  • I'm not talking about handling item clicks. This is to initialize the state of the checkboxes BEFORE a user would click on any of them.
    – AndroidDev
    Jun 4, 2013 at 5:39
  • You get a null pointer because you try to get the checkboxes on the group, not on the children. I think it is better to initialize the checkboxes in your custom adapter, by overriding the getChildView function. Jun 4, 2013 at 5:44
  • Thanks. I was thinking along those same lines. That changes my problem, though. I need to pass a string in order to execute the query that populates my array list. I don't know how to pass data into an adapter.
    – AndroidDev
    Jun 4, 2013 at 5:49
  • I could use shared preferences or even a small sqlite table and then retrieve that data within the adapter. Is there a better way?
    – AndroidDev
    Jun 4, 2013 at 5:55
  • If the data keeping the information checked/unckecked is in settingsList, you should provide it when you create your new adapter. I can post my custom BaseExpandableListAdapter if you need. Jun 4, 2013 at 5:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.