Null pointer Exception - findViewById()

后端 未结 10 2722
情歌与酒
情歌与酒 2020-11-21 04:16

Can anyone help me to find out what can be the issue with this program. In the onCreate() method the findViewById() returns null for all ids and th

相关标签:
10条回答
  • 2020-11-21 04:48

    What @Warlock said above is right , you should initial LinearLayout layout1, layout2, layout3 by the right way:

    LinearLayout layout1 = (LinearLayout) View.inflate(this, R.layout.first_View, null);
    LinearLayout layout2 = (LinearLayout) View.inflate(this, R.layout.second_View, null);
    LinearLayout layout3 = (LinearLayout) View.inflate(this, R.layout.third, null);
    

    wish my advise help you

    0 讨论(0)
  • 2020-11-21 04:51

    In my case, it was a stupid mistake on my part. I had written code in the OnCreate method but it was above the setContentView line of code. Once I moved my code below this line the application started working fine.

    setContentView(R.layout.activity_main);
    
    0 讨论(0)
  • 2020-11-21 04:57

    Sometimes you need clean your project in Eclipse (Project - Clean..).

    0 讨论(0)
  • 2020-11-21 04:58

    I have gotten this error today and it was so simple to clear, that I "facepalmed".

    Just try to add the UI element to your layout xml File in your res/layout-port directory!!!

    0 讨论(0)
  • 2020-11-21 04:59

    Emphasis added

    For those cases within an Activity class.

    Activity.findViewById(int id)

    Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle).


    Otherwise, such as an Fragment, Adapter, a View from a LayoutInflater, etc.

    View.findViewById(int id)

    Look for a child view with the given id. If this view has the given id, return this view.


    Either case,

    Returns
    The view if found or null otherwise.


    Now, re-check your XML files. Make sure you put the right value into setContentView or inflater.inflate.

    In the case of an Activity, call findViewById after setContentView.

    Then, make sure there is a View you are looking for with android:id="@+id/..." in that layout. Make sure the + is at @+id, which will add the resource to the R.id values to ensure you can find it from Java.

    0 讨论(0)
  • 2020-11-21 05:00

    findViewById() returns a View if it exists in the layout you provided in setContentView(), otherwise it returns null and that's what happening to you.

    Example if you setContentView(R.layout.activity_first); and then call findViewById(R.id.first_View); it will return a View which is your layout.

    But if you call findViewById(R.id.second_View); it will return null since there is not a view in your activity_first.xml layout called @+id/second_View.

    0 讨论(0)
提交回复
热议问题