调用getSystemService()时出现NullPointerException

3
我的问题是,在MainActivity的onCreate()方法中,我创建了一个新的线程对象,想要将对这个活动的引用传递给它,然后在该线程中使用它来调用getSystemService()。但最终,当我启动应用程序时,它会崩溃,并且我会收到NullPointerException。
我已经发现问题可能是在super.onCreate()之前传递了对活动的引用,但在我的代码中,super.onCreate()是在传递引用之前执行的。
这是我的MainActivity的onCreate()方法。
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Instance which contains thread for obtaining wifi info
    final WifiInfoThread wifi_info = new WifiInfoThread(this);
....
}

这是Thread类,我正在尝试获取对系统服务的引用

public class WifiInfoThread extends Thread {
// Constructor for passing context to this class to be able to access xml resources
Activity activity;
WifiInfoThread(Activity current) {
    activity = current;
}

// Flag for stopping thread
boolean flag = false;
// Obtain service and WifiManager object
WifiManager current_wifi = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);

// Runnable object passed to UIThread
Runnable uirunnable = new Runnable() {
    @Override
    public void run() {
        // Get current wifi status
        WifiInfo wifi_info = current_wifi.getConnectionInfo();

        // Things with showing it on screen
        TextView tv_output = (TextView) activity.findViewById(R.id.tv_output);
        String info = "SSID: " + wifi_info.getSSID();
        info += "\nSpeed: " + wifi_info.getLinkSpeed() + " Mbps";
        tv_output.setText(info);
    }
};

public void run() {
    flag = true;

    for(; flag; ) {
        activity.runOnUiThread(uirunnable);
        try {
            this.sleep(500);
        }
        catch(InterruptedException e) {}
    }
}

}


亲爱的点踩者,该用户刚刚创建了一个账户并提出了问题,请不要匆忙地进行点踩。也许编辑或评论会更加友好。 - iceman
3个回答

3

在初始化activity之前,您正在使用activity.getSystemService。为了解决这个问题,请将下面的行移动到Constructor中。

// Obtain service and WifiManager object
WifiManager current_wifi = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);

WifiManager current_wifi;
WifiInfoThread(Activity current) {
    activity = current;
    current_wifi = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
}

1
将初始化current_wifi的代码移动到您的线程的Constructor中。
// Obtain service and WifiManager object
WifiManager current_wifi = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);

在您的情况下,activity 仍然是一个 null 引用。只有在构造函数中分配后,它才会得到有效引用。

0
其他答案已经告诉你如何解决这个问题。你还应该知道 为什么 会出现 NullPointerException:在Java中,代码的执行顺序并不是按照你编写的顺序执行的。所有写在成员函数(方法)之外的东西都会先执行(有点像)。然后才会调用构造函数。因此,你正在调用 activity 上的 Conetxt.getSystemService(),而它是 null
此外,对于后台工作,Android 有 AsyncTaskIntentService。请查阅相关资料。

感谢您的解释,也感谢您的建议,我已经寻找这些东西很长时间了。 - user5465676
欢迎来到stackoverflow! - iceman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接