【问题标题】:NullPointerException with inherited function from a classNullPointerException 具有从类继承的函数
【发布时间】:2013-04-15 19:05:41
【问题描述】:

我试图从一个类继承一个函数,但它返回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)

【问题讨论】:

  • telephonyManager 和 myPhoneStateLister 在哪里初始化?
  • 这是你的第 176 行
  • 问题可能是上下文。您需要将上下文传递给 Main 构造函数,并使用该上下文初始化 telephonyManager 变量。
  • 我的回答对你有用吗?
  • 感谢您的回答,确实解决了我的问题!但是,myPhoneStateListener 在从 Main 类继承后不起作用。我已将 telephonyManager 移至 readData(), telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);对于 myPhoneStateListener,我在 Main.java 的 OnCreate() 中对其进行了初始化

标签: android nullpointerexception


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-11
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 2012-05-12
    • 2019-06-27
    • 2012-03-06
    相关资源
    最近更新 更多