Search code examples
androidnullpointerexceptiononclicklistenergetview

NPE when trying catch onClickListener in listViewItem


i have listView with items, and each item have some buttons and textView and i want to catch clicks on current textView or buttom on current listItem and make some changes with them. to do this, I am using getView method inside cursorAdapter:

@Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        View rootView =  super.getView(position, convertView, parent);
        mCounter = (TextView) rootView.findViewById(R.id.textView_counter);


        mCounter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int counter = Integer.getInteger(mCounter.getText().toString());
                mCounter.setText(String.valueOf(counter + 1));
                }
            });
            return rootView;
        }

but when i am trying to do mCounter.getText().toString() i get NPE...

will be glad any ideas how to fix this :)


Solution

  • @Override
    public void onClick(View v) {
        TextView tv = (TextView)v;
        int counter = Integer.getInteger(tv.getText().toString());
        tv.setText(String.valueOf(counter + 1));
    }
    

    Make sure that v is always a TextView (which in your case is) or prepare to catch it with ClassCastException.

    UPDATE

    Alright, change the following line

    int counter = Integer.getInteger(tv.getText().toString());
    

    into

    int counter = Integer.parseInt(tv.getText().toString());
    

    UPDATE 2

    Make sure the value in TextView is number only or get ready to catch it with NumberFormatException.