NullPointerException,具有来自类的继承函数

时间:2013-04-15 19:05:42

标签: android nullpointerexception

我试图从类继承一个函数,但它返回NullPointerException。有人可以帮忙吗?

这是我尝试在Main.java中继承的功能。此功能在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);
}

这是我另一个班级的编码:

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

错误日志:

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 个答案:

答案 0 :(得分:1)

问题是openFileInput()需要Context。您需要在类中创建一个构造函数,将context作为param

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

然后通过您的Context

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

然后在调用此函数时使用它

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

注意 如果此类中有任何其他方法需要它,您将需要使用此Context

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