AndroidGuy
AndroidGuy

Reputation: 21

NULL Pointer Exception while implementing Touch Listener in Android

I am trying to create simple app through Drag and Touch Listeners. But when I am setting the TouchListener to the TextView Control through inner class, getting NullPointerException : Here is the code.

public class MainActivity extends Activity 
{

private TextView option1,  choice1; 

protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    option1 = (TextView)findViewById(R.id.option_1);        
    setContentView(R.layout.activity_main);
        option1.setOnTouchListener(new ChoiceTouchListener());  [NULLPOINTER]   
}

private final class ChoiceTouchListener implements OnTouchListener
{

    @Override
    public boolean onTouch(View arg0, MotionEvent arg1) {
        // TODO Auto-generated method stub

        if(arg1.getAction() == MotionEvent.ACTION_DOWN)
        {

ClipData clipdata = ClipData.newPlainText("","");
DragShadowBuilder shadowbuilder = new DragShadowBuilder(arg0);
arg0.startDrag(clipdata, shadowbuilder, arg0, 0);
return true;
        }
        else
        {
        return false;
        }
    }

}
}

Upvotes: 1

Views: 814

Answers (1)

Raghav Sood
Raghav Sood

Reputation: 82543

Change:

protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    option1 = (TextView)findViewById(R.id.option_1);        
    setContentView(R.layout.activity_main);
    option1.setOnTouchListener(new ChoiceTouchListener());   
}

To

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    option1 = (TextView)findViewById(R.id.option_1);  
    option1.setOnTouchListener(new ChoiceTouchListener());   
}

findViewById() looks for a View with the supplied ID in the currently inflated layout. However, you try to use findViewById() before calling setContentView(), which results in option1 getting a null value as there is no currently inflated layout. Reordering the statements should fix this

Upvotes: 6

Related Questions