android - Cannot import views from xml sheet into MainActivity.java -


i've got bunch of views in xml sheet need manipulate in mainactivity.java file. here how trying in mainactivity.java file:

import android.app.activity; import android.os.bundle; import android.view.view; import android.widget.button; import android.widget.checkbox; import android.widget.edittext; import android.widget.progressbar;  public class mainactivity extends activity {   @override protected void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.activity_main);   }   edittext txt_username = (edittext) findviewbyid(r.id.txtview_username);  edittext txt_password = (edittext) findviewbyid(r.id.txtview_password);  button btn_login = (button) findviewbyid(r.id.button_login);  checkbox chkbox_remembermypassword = (checkbox) findviewbyid(r.id.checkbox_rememberpassword);  checkbox chkbox_logmeinautomatically = (checkbox) findviewbyid(r.id.checkbox_logmeinautomatically);  progressbar progressbar_login = (progressbar) findviewbyid(r.id.progressbar_login);  } 

this not work, , when go test code, none of views loaded. blank activity background , crashes.

am putting variable declarations in right spot? i'm confused here, think.

try:

public class mainactivity extends activity {      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_main);          edittext txt_username = (edittext) findviewbyid(r.id.txtview_username);         edittext txt_password = (edittext) findviewbyid(r.id.txtview_password);         button btn_login = (button) findviewbyid(r.id.button_login);         checkbox chkbox_remembermypassword = (checkbox) findviewbyid(r.id.checkbox_rememberpassword);         checkbox chkbox_logmeinautomatically = (checkbox) findviewbyid(r.id.checkbox_logmeinautomatically);         progressbar progressbar_login = (progressbar) findviewbyid(r.id.progressbar_login);     } } 

you had variable initialization outside of method block, means run before method of activity. since findviewbyid() looks views in inflates layout, app crash nullpointerexception there no inflated layout. layout inflated after setcontentview() has been called.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -