gpt4 book ai didi

java - 尝试调用虚拟方法时的 NPE

转载 作者:行者123 更新时间:2023-12-02 11:18:24 26 4
gpt4 key购买 nike

我明白了

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.ViewGroup.addView(android.view.View)' on a null object reference

这是我的代码:

 protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
b1=(Button)findViewById(R.id.btn);
f1=(FrameLayout)findViewById(R.id.frame_layout);
f1.addView(new myview(getApplicationContext()));
animation=
AnimationUtils.loadAnimation(getApplicationContext(),R.anim.translation);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
f1.startAnimation(animation);
}
});

错误显示在 f1.addView(new myview(getApplicationContext())); 行中。我创建了一个动画程序,在其中我想将其他类调用到代码中提到的框架布局中,因此当我运行此程序时,会显示运行时错误,如下所示。

at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2706)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1514)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6221)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.ViewGroup.addView(android.view.View)' on a null object reference
at com.cenet.animationclass.MainActivity.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:6875)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659

最佳答案

您需要首先向您的 Activity 添加布局:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.btn);
f1=(FrameLayout)findViewById(R.id.frame_layout);
}

关于java - 尝试调用虚拟方法时的 NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50102640/

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