【问题标题】:TelephonyManager throws Null Pointer Exception in MainActivityTelephonyManager 在 MainActivity 中抛出空指针异常
【发布时间】:2017-03-23 04:38:26
【问题描述】:

我想在MainActivity 中声明TelephonyManager 而不是OnCreate。在OnCreate 中没有问题,但是当我在MainActivity 中使用时,它给出了一个空指针异常。 我的代码结构需要在MainActivity 中声明TelephonyManager

public class MainActivity extends Activity {


    TelephonyManager mngr = (TelephonyManager) getApplicationContext().getSystemService(getApplicationContext().TELEPHONY_SERVICE);//Error line here.
    String imei = mngr.getDeviceId();

 protected void onCreate(Bundle savedInstanceState) {
//My jobs
}
}

如何解决这个问题?

【问题讨论】:

  • 添加此onCreate 部分
  • 因为getApplicationContext()在类级别使用时返回null
  • 我不应该添加 onCrate。因为我应该在 MainActivity 中给出imei号
  • 你必须把 mngr 放在 onCreate 方法中

标签: java android nullpointerexception telephonymanager imei


【解决方案1】:

将此行复制到您的onCreate 方法中:

TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

您所在的类扩展了ActivityActivity 扩展了Context),因此您可以直接从您的类中调用Context 的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-13
    • 2020-11-22
    • 2020-08-10
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多