javaandroidnullpointerexceptiongetmethod

NullPointException when using GetMethods with one class but not another


I am trying to create a script that will let me change the current microphone focus and I am currently confused by the behavior of my script. I have two sections where I get all methods from two classes (separated into two catch processes). When using "AudioManager" I can getMethods() by using...

Method[] methods1 = audioManager.getClass().getMethods();

-or-

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

Both of which list the entire array of methods once they are broken down into a string.

However, if I run this same identical process against "AudioDeviceInfo" and use the same exact options, one of them will fail.

Method[] methods2 = audioDeviceInfo.getClass().getMethods(); (FAILS)

-or-

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

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 Error

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.

I would expect that both versions of each set would have the same results. Additional items of the code I want to use follow the format for using the variable audioManager and audioDeviceInfo rather than their core class type for the getMethod and I want to make sure I am not doing something entirely wrong further up the pipeline before digging deeper.


Solution

  • You need to initialize your variable audioDeviceInfo before you can use it.

    Probably you need something like following line:

    audioDeviceInfo = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS);
    

    Why does it work with audioManager?

    Because you assign a value to it:

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

    Why do the other cases work?

    In the other two cases you are using the class itself which will never be null:

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

    Please take a look at this answer: https://stackoverflow.com/a/218510/7450414