gpt4 book ai didi

java - 启动 Intent 时上下文空指针

转载 作者:行者123 更新时间:2023-12-01 17:17:15 24 4
gpt4 key购买 nike

嗨,我是 android studio 的新手,我正在尝试开始一项新 Activity - 然而,我在获取上下文方面遇到了无尽的问题 - 我已经尝试了在堆栈溢出上发布的几种不同方法,但它只是不断抛出空指针请帮忙。请参阅下面的 onCreate 方法和异常。

AddRoutine.class 只是一个空白 Activity

主要 Activity

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivity.mContext = this.getApplicationContext();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Add Routine
FloatingActionButton fab = findViewById(R.id.addRoutine);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, AddRoutine.class));
}
});

generateRoutineListing(getAppContext());
//if returnListing.length > 0
// recyclerView.addItems
//else
// Show Jumbotron/Message board explaining that no routines have been created
}

异常

E/AndroidRuntime: FATAL EXCEPTION: main
Process: za.co.freelanceweb.routines, PID: 14648
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:130)
at android.content.Intent.<init>(Intent.java:5780)
at za.co.freelanceweb.routines.MainActivity$1.onClick(MainActivity.java:38)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24774)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6518)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

非常感谢

最佳答案

而不是:

 MainActivity.mContext = this.getApplicationContext();

用途:

Context mcontext = MainActivity.this;  //Also, set mcontext as a global variable.

另外,

而不是:

 generateRoutineListing(getAppContext());

用途:

 generateRoutineListing(mcontext);

关于java - 启动 Intent 时上下文空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61362158/

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