简体   繁体   English

在空对象引用上接收“ android.content.Context android.content.Context.getApplicationContext()”

[英]Receiving 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

I am new to android development and scripting with java. 我是Android开发和使用Java编写脚本的新手。 I am trying to create an app that allows me to toggle the internal microphone on and off via a switch. 我正在尝试创建一个应用程序,该应用程序允许我通过开关打开和关闭内部麦克风。 I found two scirpts (a switch script and a microphone control script) and I have peaced them together, correcting any debugging issues as I go and currently the script shows up clean. 我找到了两个脚本(一个切换脚本和一个麦克风控制脚本),并且将它们放在一起,在我进行调试时纠正了所有调试问题,当前该脚本显示为干净。 However when it is run on a phone or simulator it crashes immediately posting the following error, 但是,当它在手机或模拟器上运行时,它立即崩溃并发布以下错误,

android.content.Context android.content.Context.getApplicationContext()' on a null object reference"focused around my use of import android.content.Context;. android.content.Context android.content.Context.getApplicationContext()在“空对象引用”上针对我对import android.content.Context;的使用。

The error appears to be based on the Context.getApplicationContext request failing to find a result and thus posting NULL. 该错误似乎是由于Context.getApplicationContext请求未能找到结果而导致发布NULL所致。

I have looked at a long list of other people suffering from similar areas, but all solutions seem to focus on changes to different areas of their code which I cannot relate back to my own scripts. 我看过一长串其他遭受相似领域困扰的人,但是所有解决方案似乎都集中在对他们代码不同领域的更改上,这些更改我无法与自己的脚本相关。

package com.example.myfirstapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;

public class MainActivity extends AppCompatActivity {

    private Switch sw1;
    Button btnGet;
    Context context = getApplicationContext();
    AudioManager audioManager = ((AudioManager)context.getSystemService(Context.AUDIO_SERVICE));
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        audioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sw1 = findViewById(R.id.switch1);
        btnGet = findViewById(R.id.getBtn);
        btnGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sw1.isChecked()) {
                    audioManager.setMicrophoneMute(false);
                }
                else {
                    audioManager.setMicrophoneMute(true);
                }

            }
        });
    }
}

The expected result, even if the script doesn't work, is that I am able to run the app, currently the app crashes on startup and posts the following error message... 即使脚本不起作用,预期结果也是我能够运行该应用程序,当前该应用程序在启动时崩溃并发布以下错误消息...

[Logcat] [logcat的]

2019-08-20 13:23:01.710 5559-5559/com.example.myfirstapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myfirstapp, PID: 5559
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
        at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
        at com.example.myfirstapp.MainActivity.<init>(MainActivity.java:16)
        at java.lang.Class.newInstance(Native Method)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
        at android.app.ActivityThread.-wrap12(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:154) 
        at android.app.ActivityThread.main(ActivityThread.java:6077) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 

Your issue is that you are attempting to retrieve the context at initialization ie. 您的问题是您试图在初始化即检索上下文。

Context context = getApplicationContext();

There is no guarantee that getApplicationContext(); 不能保证getApplicationContext(); will return a valid value until the activity has been created. 将返回有效值,直到创建活动为止。 In this case it is null and when you attempt to access it on the next line you get a null pointer exception. 在这种情况下,它为null,当您尝试在下一行访问它时,将获得null指针异常。 You need to instead assign the variable context within the onCreate() along with the audio manager. 您需要在onCreate()和音频管理器中分配变量context

For example, like so: 例如,如下所示:

    Context context;
    AudioManager audioManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getApplicationContext();
        audioManager = ((AudioManager)context.getSystemService(Context.AUDIO_SERVICE));
    ...
    }

Another thing to note is that the Activity class is a subclass of Context , so you do not need to retrieve the application context you can instead write 还要注意的另一件事是, Activity类是Context的子类,因此您无需检索应用程序上下文,而可以编写

    AudioManager audioManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        audioManager = ((AudioManager)getSystemService(Context.AUDIO_SERVICE));
    ...
    }

I guess, the problem here is this line: 我想,这里的问题是这一行:

Context context = getApplicationContext();

Instead of initializing it as a class field, initialize it inside onCreate() method. 不用将其初始化为类字段,而是在onCreate()方法中对其进行初始化。 For Example: 例如:

public class MainActivity extends AppCompatActivity {

private Switch sw1;
Button btnGet;
Context context;
AudioManager audioManager;
@Override
protected void onCreate(Bundle savedInstanceState) {


    super.onCreate(savedInstanceState);
    audioManager = ((AudioManager)getSystemService(Context.AUDIO_SERVICE));
    audioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
    context = getApplicationContext();

    setContentView(R.layout.activity_main);
    sw1 = findViewById(R.id.switch1);
    btnGet = findViewById(R.id.getBtn);
    .
    .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试在空对象引用上调用虚拟方法&#39;android.content.Context android.content.Context.getApplicationContext()&#39; - Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference 尝试调用虚拟方法&#39;android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()&#39;android - Attempt to invoke virtual method 'android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext()' android 为什么在应用程序的构造函数中调用 android.content.Context.getApplicationContext() 时会得到 NPE? - Why do I get NPE when I invoke android.content.Context.getApplicationContext() within Application's constructor? NotificationManagerCompat中的(android.content.Context)无法应用于 - (android.content.Context) in NotificationManagerCompat cannot be applied to 导入 android.content.Context 后无法解析上下文; 吐司 - cannot resolve context after importing android.content.Context; The Toast 找不到符号“上下文”,android.content.Context - Cannot find symbol 'Context', android.content.Context 空对象引用上的android.content.Context.getPackageName()导致应用崩溃 - app crash with android.content.Context.getPackageName()' on a null object reference android.content.Context.getResources() 在空对象引用上 - android.content.Context.getResources() on a null object reference android.content.Context.getPackageName() 在 null object 参考 - android.content.Context.getPackageName() on a null object reference 可运行的ListViewAdapter导致“无法转换为android.content.Context”错误 - runnable ListViewAdapter causes a “cannot be cast to android.content.Context” error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM