2015-10-20 236 views
1

我的問題是,在我的MainActivity的onCreate()方法中,我創建了一個新的Thread對象,我想將該對象傳遞給this活動,並且在該線程中使用它來調用getSystemService ()。但最終,當我啓動應用程序時,它崩潰,我得到NullPointerException。調用getSystemService()時得到NullPointerException異常

我已經發現問題可能是我傳遞引用的活動befor 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); 
.... 
} 

這是我想獲得參考系統服務

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) {} 
    } 
} 

}

+0

親愛的downvoter,用戶剛剛創建了一個帳戶,並提出了一個問題,不要急於下調。也許編輯或評論會受到歡迎。 – iceman

回答

2

您正在使用Thread類activity.getSystemService在初始化之前activity。要獲得此程,移動以下行成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

舉動在你的線程的Constructor的initialitation current_wifi

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

activity仍然是一個null參考。它得到一個有效的一個,然後你在構造函數中指定它

1

其他答案告訴你如何解決這個問題。你也應該知道什麼NullPointerException的原因:在java中,你的代碼不會按照你寫的順序執行。每個寫在成員函數(方法)之外的東西都會先執行(有點)。然後調用構造函數。因此,您致電Conetxt.getSystemService()activity,這是null

另外爲了後臺工作,android有AsyncTaskIntentService。看看他們。

+0

感謝您的解釋,也請教,我一直在尋找這些東西很長時間 – silicoin

+0

歡迎來到stackoverflow! – iceman