Oprea Serban
Oprea Serban

Reputation: 11

Android listview checkedtextview

I have a problem with an Android app. I'm trying to create a listview containing a textview and a checkedtextview per row. I have done the layout and the adapter and it displays all the items correctly, but the problem I have is the folowing: I can check perfectly the first 7 items(the ones that are visible initialy) but when i scroll down to check one of the folowing item(one that is not visible initialy) i get a null pointer exception. What should I do?

Adapter Code:

private class myAdapter extends ArrayAdapter<Orders> {

private ArrayList<Orders> items;

public myAdapter(Context context, int resource, ArrayList<Orders> items) {
    super(context, resource, items);
    this.items = items;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = getLayoutInflater().inflate(R.layout.orderslist_row,
                null);
    }

    Orders o = items.get(position);

    CheckedTextView txtSymbol = (CheckedTextView) convertView
            .findViewById(R.id.checkedTextView1);
    txtSymbol.setText(o.getInstrumentID());

    CheckedTextView txtQuantity = (CheckedTextView) convertView
            .findViewById(R.id.checkedTextView2);
    Double qty = o.getQuantity();
    txtQuantity.setText(FormatNumber.Number(qty, 0));

    if (o.getStatus().toString().equals("Rejected"))
        txtQuantity.setTextColor(Color.RED);
    if (o.getStatus().toString().equals("Active"))
        txtQuantity.setTextColor(Color.GREEN);

    return convertView;
}

}

And OnItemClickCode:

public void onItemClick(AdapterView<?> adapter, View view, int position,
    long id) {
View v = (View)lstOrders.getChildAt(position);
CheckedTextView ctv = (CheckedTextView) v.findViewById(R.id.checkedTextView2);
ctv.toggle();

}

Upvotes: 1

Views: 1876

Answers (1)

mango
mango

Reputation: 5636

getChildAt(i) works off of the set of indexes that are visible. When you scroll and position 3 becomes the first visible row, that has become position 0 for the method. So, at any given moment, you're only allowed up to about an index of 7, if that's how many listview rows can fit on the screen. if you're continuing with this method, there's a way tip the scales how you'd like it, you find out what the first visible row index is and then subtract from the total. the listview has such a method.

    public void onItemClick(AdapterView<?> adapter, View view, int position,
            long id) {
        View v = (View)lstOrders.getChildAt(position - lstOrders.getFirstVisiblePosition());
        CheckedTextView ctv = (CheckedTextView) v.findViewById(R.id.checkedTextView2);
        ctv.toggle();
}

Upvotes: 1

Related Questions