NullPointerException with inherited function from

2019-09-09 23:31发布

问题:

I am trying to inherit a function from a class, but it returns NullPointerException. Can anyone please help?

This is the function I try to inherit in Main.java. This function operates well in Main.java.

public void readData() {
    String readString = "";

    try {
        FileInputStream fIn = openFileInput("user.txt");
        InputStreamReader isr = new InputStreamReader(fIn);
        BufferedReader buffreader = new BufferedReader(isr);

        readString = buffreader.readLine();
        isr.close();

    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    telephonyManager.listen(myPhoneStateListener,
                            PhoneStateListener.LISTEN_CALL_STATE);
}

Here is the coding in my another class:

Main main =new Main();
main.readData();

Error log:

04-16 02:58:23.812: E/AndroidRuntime(8125): java.lang.NullPointerException
04-16 02:58:23.812: E/AndroidRuntime(8125):   at android.content.ContextWrapper.openFileInput(ContextWrapper.java:167)
04-16 02:58:23.812: E/AndroidRuntime(8125):   at com.test.Main.readData(Main.java:176)

回答1:

The problem is that openFileInput() needs a Context. You need to create a constructor in your class that takes context as a param.

public void ClassWithFunction
{
   Context mContext;
    public ClassWithFunction (Context context)
    {
         mContext = context
    }
}

then pass your Context

Main main =new Main(this);
main.readData();

then use that when you call this function

FileInputStream fIn = mContext.openFileInput("user.txt");  //mContext is context sent from Activity

Note You will want to use this Context if you have any other methods in this class that need it

Here is an answer of mine on SO about the same thing