gpt4 book ai didi

android - 调用 getSystemService() 时得到 NullPointerException

转载 作者:行者123 更新时间:2023-12-04 23:56:46 26 4
gpt4 key购买 nike

我的问题是,在我的 MainActivity 的 onCreate() 方法中,我正在创建新的 Thread 对象,我想将对 this Activity 的引用传递给该对象,然后在该线程中使用它来调用 getSystemService ().但最后,当我启动应用程序时,它崩溃了,我得到了 NullPointerException。

我已经发现问题可能是我在 super.onCreate() 之前传递了对 Activity 的引用,但在我的代码中,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) {}
}
}

最佳答案

在初始化 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);
}

关于android - 调用 getSystemService() 时得到 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33230556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com