This question already has answers here:
What is a NullPointerException, and how do I fix it?

(12个答案)


在10个月前关闭。





我正在尝试创建一个脚本,该脚本可以让我更改当前麦克风的焦点,并且当前我对脚本的行为感到困惑。我有两个部分,分别从两个类(分为两个catch进程)获取所有方法。当使用“ AudioManager”时,我可以使用...

Method []方法1 = audioManager.getClass()。getMethods();

-要么-

Method []方法1 = AudioManager.class.getMethods();

一旦将方法分解为字符串,这两个方法都会列出整个方法数组。

但是,如果我对“ AudioDeviceInfo”运行相同的过程,并使用相同的确切选项,则其中之一将失败。

Method []方法2 = audioDeviceInfo.getClass()。getMethods(); (失败)

-要么-

Method [] methods2 = AudioDeviceInfo.class.getMethods(); (成功)

package com.example.myfirstapp;

import android.content.Context;
import android.media.AudioDeviceInfo;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Switch sw1;
    TextView slvtxt;
    Button btnGet;
    Context context;
    AudioManager audioManager;
    AudioDeviceInfo audioDeviceInfo;

    private static List<String> getFieldNamesOne(Method[] methods1) {
        List<String> fieldNames1 = new ArrayList<>();
        for (Method method1 : methods1)
            fieldNames1.add(method1.getName());
        return fieldNames1;
    }

    private static List<String> getFieldNamesTwo(Method[] methods2) {
        List<String> fieldNames2 = new ArrayList<>();
        for (Method method2 : methods2)
            fieldNames2.add(method2.getName());
        return fieldNames2;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getApplicationContext();
        audioManager = ((AudioManager)getSystemService(Context.AUDIO_SERVICE));
        setContentView(R.layout.activity_main);
        slvtxt = findViewById(R.id.slaveText);
        sw1 = findViewById(R.id.switch1);
        btnGet = findViewById(R.id.getBtn);
        btnGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    Method[] methods1 = audioManager.getClass().getMethods();
                    //Method[] methods1 = AudioManager.class.getMethods();
                    List<String> actualFieldNames1 = getFieldNamesOne(methods1);
                    Log.d("tag","FOUND METHOD RETURN: " + Arrays.toString(actualFieldNames1.toArray()));

                    Method methodVar1 = audioManager.getClass().getMethod("setWiredDeviceConnectionState", Integer.TYPE, Integer.TYPE, String.class, String.class);
                    Log.d("tag","Method: " + methodVar1.getName());
                    methodVar1.setAccessible(true);


                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                    Log.d("tag","No Such Method : WiredDevice");
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    Log.d("tag","Null Point : WiredDevice");
                }

                try {
                    Method[] methods2 = audioDeviceInfo.getClass().getMethods();
                    List<String> actualFieldNames2 = getFieldNamesTwo(methods2);
                    Log.d("tag","FOUND METHOD RETURN: " + Arrays.toString(actualFieldNames2.toArray()));

                } catch (NullPointerException e) {
                     e.printStackTrace();
                    Log.d("tag","Null Point : GetAddress");
                }
            }
        });
    }
}


LogCat错误

W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
        at com.example.myfirstapp.MainActivity$1.onClick(MainActivity.java:91)
        at android.view.View.performClick(View.java:5610)
        at android.view.View$PerformClick.run(View.java:22265)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
D/tag: Null Point : GetAddress
Process 4630 terminated.


我希望每个集合的两个版本都有相同的结果。我想使用的其他代码项遵循使用变量audioManager和audioDeviceInfo的格式,而不是getMethod的核心类类型,并且我想确保在深入研究之前,我不会在上游做任何完全错误的事情。

最佳答案

您需要先初始化变量audioDeviceInfo,然后才能使用它。

可能您需要以下代码:

audioDeviceInfo = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS);




为什么它可以与audioManager一起使用?

因为您为其分配了一个值:

audioManager = ((AudioManager)getSystemService(Context.AUDIO_SERVICE));


为什么其他情况有效?

在另外两种情况下,您将使用永远不会为null的类本身:

Method[] methods1 = AudioManager.class.getMethods();
Method[] methods2 = AudioDeviceInfo.class.getMethods();




请查看以下答案:https://stackoverflow.com/a/218510/7450414

07-28 02:11
查看更多