How to Handle NullPointerException in android?

前端 未结 2 1597
春和景丽
春和景丽 2021-01-22 13:01
01-18 02:08:05.271: E/AndroidRuntime(24688): FATAL EXCEPTION: main
01-18 02:08:05.271: E/AndroidRuntime(24688): java.lang.NullPointerException
01-18 02:08:05.271: E/Andr         


        
2条回答
  •  生来不讨喜
    2021-01-22 13:39

    When you use setContentView(R.layout.exchange_message), the layout R.layout.exchange_message will be inflated and associated to your activity. If you want to retrieve a View from that layout, you just call findViewById(R.id.MyId);.

    But if your View is not inside the layout, you will have a NPException.

    To retrieve views from another layout, you have to inflate it first, and then call myView.findViewById(R.id.MyId).

    For instance, according to your case, if you want to use the ListView from the popup.xml layout file :

        View popupView = layoutInflater.inflate(R.layout.popup, null);
        ListView list = popupView.findViewById(R.id.listOfUserOnline);
    

提交回复
热议问题