2014-01-15 67 views
1

我想讓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; 
} 
+0

你可以發佈日誌和堆棧行嗎? – iGio90

+1

getActivity現在返回null –

回答

2

getActivity返回null你應該初始化wifiMgronCreate

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); 

} 
+0

app runnig。謝謝 – user3199502

1

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

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

這裏這條線

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

將會是一個問題,因爲您在創建Activity之前調用getActivity()。移動該初始化,並因此將以下初始化移動到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); 
} 
相關問題