gpt4 book ai didi

java.lang.NullPointerException : Attempt to invoke virtual method 'int android.view.ViewGroup.getPaddingLeft()' on a null object reference 异常

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:16:58 25 4
gpt4 key购买 nike

我正在尝试使用 Intent 启动 Activity,但提到的错误发生在第二个 Activity 的 setContentView() 上;

这是我的代码和布局文件。

itemactivity.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">

</LinearLayout>

主要 Activity :

Intent i=new Intent(MainActivity.this,ItemActivity.class);
startActivity(i);

项目 Activity :

@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.itemactivity); // this is where error occurs
super.onCreate(savedInstanceState);
}

这是完整的错误日志:

java.lang.RuntimeException: Unable to start activity         ComponentInfo{bertaberim.team.beertaberim/bertaberim.team.beertaberim.ItemActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.ViewGroup.getPaddingLeft()' on a null object reference
11-04 23:01:20.621 20634-20634/? E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3119)
11-04 23:01:20.621 20634-20634/? E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3218)
11-04 23:01:20.621 20634-20634/? E/AndroidRuntime: at android.app.ActivityThread.access$1000(ActivityThread.java:198)
11-04 23:01:20.621 20634-20634/? E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1676)
11-04 23:01:20.621 20634-20634/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
11-04 23:01:20.621 20634-20634/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:145)
11-04 23:01:20.621 20634-20634/? E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:6837)
11-04 23:01:20.621 20634-20634/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-04 23:01:20.621 20634-20634/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
11-04 23:01:20.621 20634-20634/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
11-04 23:01:20.621 20634-20634/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

最佳答案

在设置 View 之前,您需要先调用 super.onCreate() 以对 Activity 执行任何必要的初始化。只需翻转这两行:

super.onCreate(savedInstanceState);
setContentView(R.layout.itemactivity); // this is where error occurs

有关此方法的作用的更多信息,请查看 this answer .

关于java.lang.NullPointerException : Attempt to invoke virtual method 'int android.view.ViewGroup.getPaddingLeft()' on a null object reference 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33531212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com