How to Handle NullPointerException in android?

前端 未结 2 1598
春和景丽
春和景丽 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);
    
    0 讨论(0)
  • 2021-01-22 14:02

    You need to learn to read the Log to solve your errors like the NPE. java.lang.NullPointerException at com.example.tava.EchangingMessage$LoadData.onPostExecute*(EchangingMessage.java:178)*

    Your error is most likely on this row. To show Line number in eclipse right click on the edge to the left and choose "Show Line Number" Also the Key command Ctrl+L will let you jump to the specific line.

    Invoke findViewById on your popupWindow instead. Extract the variable to the class level or pass it to the AsyncTask so it can be referenced.

    popupWindow.findViewById();
    
    0 讨论(0)
提交回复
热议问题