2015-10-20 61 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

相关问题