if (myObject == null) { // do something }
检查 findViewById 是否正确 如果 findViewById 返回 null,则可能导致 NullPointerException。因此,需要确保指定的视图 ID 在布局文件中存在并正确。
检查数组/列表等数据结构 如果在数组/列表中访问 null 元素,则可能导致 NullPointerException。在访问数组/列表之前,请确保已经正确地初始化。
捕捉异常 在操作可能引发 NullPointerException 的代码段中,使用 try-catch 块来捕获异常,以防止 Android 应用程序终止并提供更好的用户体验。
try { // try to do something that can cause NullPointerException } catch (NullPointerException e) { // handle null pointer exception }
通过以上方法,可以从根本上修复 Android Activity 中的 NullPointerException,并更好地提高应用程序的稳定性。