Question

I have a very weird problem I am having with ViewBinder's setViewValue(View, Cursor, columnIndex). In setViewValue I am trying to access a button in the layout for each item in my listview.

I am able to access and change text of the TextView, but when I try to set the text of the button I get a NullPointerException. The button has an id and I am correctly using the name, the button is also a sibling of textview so if the root view can find the textview, it should be able to find the button.

I tried cleaning the project with no success.

Any other suggestions?

EDIT: Here is the code for the ViewBinder (setViewValue) and for the layout for each item in the listview:

private class CustomViewBinder implements ViewBinder {

    @Override
    public boolean setViewValue(View view, Cursor cursor, int columnIndex) {

            int upvoted_index=cursor.getColumnIndex("upvote");
            int is_upvoted = cursor.getInt(upvoted_index);
            if (is_upvoted == 1) {

                Button likeButton = (Button) view.findViewById(R.id.voteButton);
                likeButton.setText("Upvoted");
                return true;
            }
            return false;
    }

}

Layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="20dip"
android:background="@drawable/profile_styling" >

    <TextView
    android:id="@+id/title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="30sp"
    android:gravity="center" />


<Button
android:id="@+id/voteButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@string/like"
android:background="#00FFFF"
android:paddingTop="20dp"
 />

</LinearLayout>
Was it helpful?

Solution

You can use:

ViewGroup superView = (ViewGroup)view.getParent();
Button btn = (Button) superView.findViewById(R.id.votewButton);

Also using the array of view ids that you pass to the adapter's constructor would be a good alternative:

String[] from = {/*any collumns that you may have*/, "_id"}; // just bind a column, we don't use it
int[] = {/*any collumns that you may have*/, R.id.voteButton};

The in the ViewBinder you'll have:

@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
    // only if we're binding the Button
    if (view.getId == R.id.voteButton) {
        int upvoted_index=cursor.getColumnIndex("upvote");
        int is_upvoted = cursor.getInt(upvoted_index);
        if (is_upvoted == 1) {
            Button likeButton = (Button) view;
            likeButton.setText("Upvoted");
            return true;
        }
    }
    return false;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top