"A little progress everyday adds up to big results"

Sunday 27 May 2012

Android: NullPointerException with findViewById

I was developing an android application for 'Speaker Recognition' at IIIT, Hyderabad under the guidance of Dr. Kishore S. Prahallad as my fellowship project. I was very new to the android development ( approximately one and half weeks ).

I had a scenario where, I had to show a custom toast with differing text when the Name field is empty or the name entered is existing. I wrote a function as follows and called it with the resource ids from R class. The application crashed unexpectedly on running.

    private void notifyError(int id)
    {
    LayoutInflater in = getLayoutInflater() ;
    View layout = in.inflate(R.layout.toast_layout, (ViewGroup) findViewById ( R.id.toast_layout_root ) ) ;
   
    ImageView im = ( ImageView ) findViewById ( R.id.image ) ;
    im.setImageResource(R.drawable.warning) ;
   
    TextView warn = ( TextView ) findViewById ( R.id.message ) ;
    warn.setText ( id ) ;
   
    Toast toast = new Toast ( getApplicationContext() ) ;
    toast.setView(layout) ;
    toast.setGravity(Gravity.CENTER, 0, 0) ;
    toast.setDuration(Toast.LENGTH_SHORT) ;
    toast.show() ;
    }

When I debugged, I found that null is being assigned to the im and warn objects. But, couldn't know what was the problem. I google it for about 3 hours, but of no use. Later on having a closer look, I found out, View.findViewById() is different from Activity.findViewById(). So, I changed the code to:

    ImageView im = ( ImageView ) layout.findViewById ( R.id.image ) ;
    im.setImageResource(R.drawable.warning) ;
   
    TextView warn = ( TextView ) layout.findViewById ( R.id.message ) ;
    warn.setText ( id ) ;

And then, it worked.

No comments:

Post a Comment