Displaying toast message in a text View android -
i trying display toast message in textview needs update every second in order display package names (every second) i'm getting error in code saying "cannot refer non-final variable pnum inside inner class defined in different method"
in line "msgto.settext("optimized " + procinfos.get(pnum).processname);"
// display package names activitymanager actvitymanager = (activitymanager) getapplicationcontext() .getsystemservice(getapplicationcontext().activity_service); list<runningappprocessinfo> procinfos = actvitymanager .getrunningappprocesses(); (int pnum = 0; pnum < procinfos.size(); pnum++) { if ((procinfos.get(pnum)).processname.contains("android") || (procinfos.get(pnum)).processname.contains("system") || (procinfos.get(pnum)).processname.contains("huawei") || (procinfos.get(pnum)).processname.contains("adil")) { } else { new thread(new runnable() { @override public void run() { try { thread.sleep(2000); //do thing here textview msgto = (textview) findviewbyid(r.id.optimizedapp); msgto.settext("optimized " + procinfos.get(pnum).processname); } catch (interruptedexception e) { e.printstacktrace(); } } }).start(); } } }
i tried putting whole code in thread getting error in log cat (after 2 sec thread time)
06-30 06:35:15.379: e/androidruntime(5281): fatal exception: thread-12964 06-30 06:35:15.379: e/androidruntime(5281): process: com.example.xtremenetbooster, pid: 5281 06-30 06:35:15.379: e/androidruntime(5281): android.view.viewrootimpl$calledfromwrongthreadexception: original thread created view hierarchy can touch views. // thread new thread(new runnable() { @override public void run() { try { thread.sleep(2000); // thing here // display package names activitymanager actvitymanager = (activitymanager) getapplicationcontext() .getsystemservice( getapplicationcontext().activity_service); list<runningappprocessinfo> procinfos = actvitymanager .getrunningappprocesses(); (int pnum = 0; pnum < procinfos.size(); pnum++) { if ((procinfos.get(pnum)).processname .contains("android") || (procinfos.get(pnum)).processname .contains("system") || (procinfos.get(pnum)).processname .contains("huawei") || (procinfos.get(pnum)).processname .contains("adil")) { // toast.maketext(getapplicationcontext(), // "system apps", // toast.length_short).show(); } else { textview msgto = (textview) findviewbyid(r.id.optimizedapp); msgto.settext("optimized " + procinfos.get(pnum).processname); } } // } catch (interruptedexception e) { e.printstacktrace(); } } }).start(); } // thread
your error coming trying access pnum
@ msgto.settext("optimized " + procinfos.get(pnum).processname);
when pnum defined inside for
loop
Nice article. There are good example regarding java variable Click Here
ReplyDelete