Android Development: Getviewbyid return null for reason positioning

Source: Internet
Author: User

Recent research and development of some Android -based appshas encountered some problems. One of the keys is to get the Button object in the onCreate () method in Activity . The code is probably for example the following:

Private Button Mtruebutton;

@Override

Public void OnCreate(Bundle savedinstancestate){

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.activity_quiz);

Mtruebutton = (Button) Getviewbyid (R.id.true_button);

Mtruebutton.setonclicklistener (...);

}

The code was modified based on an Android Programming Guide, but unexpectedly. Once running, theapp prompts for system errors, terminates the operation, and discovers via debug trace:mtruebutton is null, the system runs to Mtruebutton.setonclicklistener throws java.lang.NullPointerException, It is very obvious that at this point the call Getviewbyid cannot get to the Button this View object, and then start searching the data online. There are several possible reasons for this:

One, the exception caused by improper call order

The main reason for this view is that Getviewbyid 's call was placed before Setcontentview . For example, the following:

Super.oncreate (savedinstancestate);

Mtruebutton = (Button)Getviewbyid (R.id.true_button);

Setcontentview (R.layout.activity_quiz);

The reason: When the activity calls Setcontentview (), Android will draw the elements on the layout and allocate memory for it.

Only after allocating memory, talent continues to run, Findviewbyid (); Talent gets a reference, otherwise a null reference, a null reference means that there is a problem with the object that will be interviewed when the corresponding variable is used later.

And once the activity is Setcontentview () again, the memory of those previously drawn controls is extinguished.

So, if through setcontentview to achieve the purpose of screen switching. Be aware that once again the drawing is made again after the reference

Two. Getviewbyid context objects do not match

In this way, I think of the document.getElementByIdin Javascript , the two have very high similarity,getElementById calls need to specify the corresponding The document object. Represents the acquisition of an element from the document object, in the same vein, the full invocation of Getviewbyid inAndroid is View.getviewbyid. Therefore, you need to focus on the default context object for this method. This is usually the current Activity. But sometimes it may not, such as:

Userdialog=new Dialog (addevent.this);

Userdialog.setcontentview (r.layout.user_list);

userdialog.settitle (" Please select");

ListView lv= (ListView) Userdialog . Findviewbyid (r.id.userlist);

Lv.setadapter (New Myadapter ());

Userdialog.show ();

As above, the LV must be instantiated with Userdialog.findviewbyid () specified and not directly Findviewbyid (). Otherwise you will find r.id.userlist from the activity instead of the dialog layout file, which will of course return NULL, running Lv.setadapter (New Myadapter ()); There will be nullpointexception anomalies

three. problems caused by development tools Eclipse

It is assumed that the GetView method in the custom Adapter has similar code such as the following:

View Rowview = (view) inflater.inflate (R.layout.rowview, parent, false);

TextView tv_contact_id = (TextView) Rowview.findviewbyid (r.id.tv_contact_id);

TextView tv_contactname = (TextView) Rowview.findviewbyid (r.id.tv_contactname);

Sometimes it turns out that Rowview is not empty. But both tv_contact_id and tv_contactname are null. Look at the code carefully. I can't see the mistake. What is the cause of it? The answer is Eclipse -caused. To resolve the issue. This project needs to be clean once (Project menu, Clean submenu ), so it's OK .

Four. the new version number SDK cannot be called in the onCreate method - The author's question causes this.

Important Environmental accountability: just learn Android. The new version of ADT and the new SDK , which are downloaded on the website, assume that your minimum build number (MINIMUMREQUIREDSDK) is supported when creating a project in the new version of the IDE (ADT) 4.0 The following version, and the target version number is (4.0+), then the IDE will create a compatibility package for you (APPCOMPAT_V7) after the project is created, this time in the generated project master activity is not the kind of inherited activity, but the inheritance of actionbaractivity.

At this point, assuming that you are still using the old method to call Getviewbyidin onCreate , then nullis returned because: in the new layout The file is not stored in the default (res/layout/activity_quiz.xml) file, but is stored in the (res/layout/fragment_quiz.xml) file. So to find the corresponding ID in fragment_quiz.xml , and the new IDE -generated code is loaded (fragment_quiz.xml The file is loaded in an internal class, so one way is: we can get the Buttonin the internal class loading place.

/**

* A placeholder fragment containing a simple view.

*/

public static class Placeholderfragment extends Fragment {

View Rootview = null;

Public Placeholderfragment () {

}

@Override

Public View Oncreateview (layoutinflater inflater, ViewGroup container,

Bundle savedinstancestate) {

Rootview = Inflater.inflate (R.layout.fragment_quiz, container, false);

Mtruebutton = (Button) Rootview.findviewbyid (R.id.true_button);

System.out.println (button);

return rootview;

}

}

      The second approach is to assume that you are familiar withActivityThe life cycle of people can know:onCreateThe layout object is not actually constructed at the time of the call, sonot inonCreategets the control in the function. But can be inOnStartfunction, get: ( The author's plan is obtained in the onStart method )

@Override
protected void OnStart () {
   Super.onstart ();
   Mtruebutton = (Button) Findviewbyid (R.id.true_button);
   
   Mtruebutton.setonclicklistener (New Android.view.View.OnClickListener () {
  Public void OnClick (Android.view.View v) {
   //todo ...
  }
  });
}

Android Development: Getviewbyid return null for reason positioning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.