不幸的是,<project name =“”>已停止</project>

时间:2014-01-15 19:45:46

标签: java android android-wifi

我希望Android获得Wifi路由器名称。 MainActivity.java有此代码。但当我运行时,我得到以下错误不幸的是,已经停止。感谢

WifiManager wifiMgr = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
String WifiName = wifiInfo.getSSID();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView outputWifiName = (TextView) findViewById(R.id.sysInf);

    outputWifiName.setText(WifiName);

}

private Activity getActivity() {
    // TODO Auto-generated method stub
    return null;
}

3 个答案:

答案 0 :(得分:2)

您的getActivity返回null,您应该在wifiMgr内初始化onCreate

WifiManager wifiMgr =null;
WifiInfo wifiInfo = null;
String WifiName = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
     wifiMgr= (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
     wifiInfo = wifiMgr.getConnectionInfo();
    WifiName = wifiInfo.getSSID();
    TextView outputWifiName = (TextView) findViewById(R.id.sysInf);

    outputWifiName.setText(WifiName);

}

答案 1 :(得分:1)

你在这一行中调用getActivity' but at the same time override it to return null . This results in a NullPointerException`:

WifiManager wifiMgr = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);

答案 2 :(得分:0)

这一行

WifiManager wifiMgr = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);

将成为一个问题,因为您在创建getActivity()之前调用Activity。将该初始化以及随后的初始化移至onCreate()

String WifiName;
WifiInfo wifiInfo;
WifiManager wifiMgr;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Move those guys to here
    wifiMgr = (WifiManager)    
    getActivity().getSystemService(Context.WIFI_SERVICE);
    wifiInfo = wifiMgr.getConnectionInfo();
    WifiName = wifiInfo.getSSID();

    TextView outputWifiName = (TextView) findViewById(R.id.sysInf);
    outputWifiName.setText(WifiName);
}