multithreading - I'm getting a NullPointerException in android , what's wrong with my code? -
i'm java/android beginner. nullpointerexception when trying run below app. want access points using getscanresults() null when don't use thread used it. can tell me what's wrong code?thanks in advance!
public class mainactivity extends activity implements view.onclicklistener { button btn; wifimanager wifi; final string tag = "connecttowifi"; string[] wifis; listview list; wifiscanreceiver wifireciever; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); btn = (button) findviewbyid(r.id.button_id); btn.setonclicklistener(this); if (wifi.iswifienabled()) { btn.settext(r.string.on_label); } else { btn.settext(r.string.off_label); } new thread(new runnable() { @override public void run() { // todo auto-generated method stub wifi = (wifimanager) getsystemservice(wifi_service); list = (listview) findviewbyid(r.id.listview1); wifi = (wifimanager) getsystemservice(context.wifi_service); wifireciever = new wifiscanreceiver(); wifi.startscan(); } }).start(); } @override public void onclick(view v) { // todo auto-generated method stub if (wifi.iswifienabled()) { wifi.setwifienabled(false); btn.settext(r.string.off_label); } else { log.d(tag, string.valueof(wifi.getwifistate())); wifi.startscan(); log.d(tag, string.valueof(wifi.getscanresults())); wifi.getscanresults(); wifi.setwifienabled(true); log.d(tag, string.valueof(wifi.getwifistate())); btn.settext(r.string.on_label); log.d(tag, string.valueof(wifi.getwifistate())); } } class wifiscanreceiver extends broadcastreceiver { public void onreceive(context c, intent intent) { try { list<scanresult> wifiscanlist = wifi.getscanresults(); wifis = new string[wifiscanlist.size()]; (int = 0; < wifiscanlist.size(); i++) { wifis[i] = ((wifiscanlist.get(i)).tostring()); } } { list.setadapter(new arrayadapter<string>(getapplicationcontext(), android.r.layout.simple_list_item_1, wifis)); } } }
}
you didn't initialize wifi
before use it.
make wifi = (wifimanager) getsystemservice(wifi_service);
before first use wifi, wifi.iswifienabled()
.
and also, pay attention logcat. tell exact reason why happened. :
11-14 21:30:52.517: e/androidruntime(18929): caused by: java.lang.nullpointerexception 11-14 21:30:52.517: e/androidruntime(18929): @ com.kay.mainactivity.oncreate(mainactivity.java:88)
Comments
Post a Comment