Android development: locate the reason why getViewById returns null. androidgetviewbyid

Source: Internet
Author: User

Android development: locate the reason why getViewById returns null. androidgetviewbyid

Recently, I have been researching and developing some Android-based apps and encountered some problems. One of the most important problems is to obtain the Button object in the onCreate () method of the Activity. The code is roughly as follows:

 

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 according to an android programming guide, but unexpectedly, upon execution, the app prompts a system error and stops running. The debug trace found that mTrueButton is null, the system runs to mTrueButton. setOnclickListener throwJava. lang. NullPointerException,Obviously, when getViewById is called at this time, the View object "Button" cannot be obtained. Therefore, you can search for materials online. The possible reasons are as follows:

1. Exceptions caused by improper Call Sequence

The main reason for this is that the call to getViewById is placed before setContentView, as shown below:

Super. onCreate (savedInstanceState );

MTrueButton = (Button) getViewById (R. id. true_button );

SetContentView (R. layout. activity_quiz );

 

The reason is: when the activity calls setContentView (), android will draw each element on layout and allocate memory to it. The execution can continue only after the memory is allocated. findViewById (); can be referenced. Otherwise, an empty reference means that, when the corresponding variable is used later, the accessed object does not exist.

In addition, after the Activity is re-setContentView (), the memory of the previously drawn controls will be destroyed.

Therefore, if you use setContentView to achieve screen switching, you must re-draw and re-obtain the reference.

 

 

2. The context object of getViewById does not match

This method reminds me of the document in Javascript. getElementById has a very high similarity between the two. To call getElementById, you must specify the corresponding document object to obtain elements from the document object. Similarly, the complete call to getViewById in Android is View. getViewById, so you need to pay attention to the default context object of this method, which is usually this, that is, the current Activity, but sometimes it may not be like this, for example:

 

UserDialog = new Dialog (addevent. this );

UserDialog. setContentView (R. layout. user_list );

UserDialog. setTitle ("select ");

ListView lv = (ListView)UserDialog. FindViewById (R. id. userList );

Lv. setAdapter (new MyAdapter ());

UserDialog. show ();

As shown above, userDialog must be specified during lv instantiation. findViewById () instead of findViewById (). Otherwise, R will be found in the layout file of Activity rather than Dialog. id. userList. At this time, null is returned and lv is executed. setAdapter (new MyAdapter (); NullPointException exception

 

Iii. problems caused by development tool Eclipse

Assume that the getView method of the custom Adapter has the following code:

 

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 we can find that rowview is not empty, but both TV _contact_id and TV _contactname are null! I can't see any errors even though I look at the code carefully. What is the cause? The answer is caused by Eclipse. To solve this problem, you need to clean the Project once (Project menu-> Clean sub-menu), so that it is OK.

 

 

4. The new SDK version cannot be called in the onCreate method-the author's problem is caused by this.

Important Environment Description: I just learned about Android. I downloaded the new version of ADT from the official website and the new version of the SDK. If your minimum version (minimumrequiredSDK) is used to create a project in the new IDE version) to support versions earlier than 4.0 and the target version is (4.0 +), the IDE will create a compatible package (appcompat_v7) for you after creating a project, at this time, the generated project main Activity is not the previous inherited Activity, but the inherited ActionBarActivity.

At this time, if you still use the old method to call getViewById in onCreate, null will be returned because the new layout file is not stored in the default (res/layout/activity_quiz.xml) file, but stored in the (res/layout/fragment_quiz.xml) file. Therefore, you need to find the corresponding ID in fragment_quiz.xml, And the loaded (fragment_quiz.xml) file in the code generated by the new IDE is loaded in an internal class, so one method is: we can get the Button at the internal class loading.

/**

* 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;

}

}

Another method is: If you are familiar with the lifecycle of the Activity, you can know that the layout object has not been constructed when onCreate is called. Therefore, you cannot obtain the control in the onCreate function, however, you can obtain the following information in the onStart function:(The solution 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...
}
});
}

 

 

 

Related Article

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.