This question already has answers here:
Can't create handler inside thread that has not called Looper.prepare()
(30 answers)
Threading - Can't create handler inside thread that has not called Looper.prepare()
(1 answer)
Closed 9 years ago.
I get the following error:
08-27 17:49:17.995: E/AndroidRuntime(10085): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
08-27 17:49:17.995: E/AndroidRuntime(10085): at android.os.Handler.<init>(Handler.java:121)
08-27 17:49:17.995: E/AndroidRuntime(10085): at android.widget.Toast$TN.<init>(Toast.java:361)
08-27 17:49:17.995: E/AndroidRuntime(10085): at android.widget.Toast.<init>(Toast.java:97)
08-27 17:49:17.995: E/AndroidRuntime(10085): at android.widget.Toast.makeText(Toast.java:254)
when running the first line of:
public static void alertUser(String str) {
Toast toast = Toast.makeText(mInstance.getApplicationContext(), str,
Toast.LENGTH_LONG);
toast.show();
}
how can i fix this?
Something like this should work:
public static void alertUser(String str) {
runOnUiThread(setErrorMessage);
}
private Runnable setErrorMessage = new Runnable() {
#Override
public void run() {
Toast toast = Toast.makeText(mInstance.getApplicationContext(), str,
Toast.LENGTH_LONG);
toast.show();
}
};
Related
I have a TimerTask in a library module I use, I have access to the source code and it worked independantly, however when I call the method startPoll()from the main application i get the following error, SensorPoll is the TimerTask:
E/AndroidRuntime: FATAL EXCEPTION: Timer-0
Process: com.app, PID: 29465
java.lang.ExceptionInInitializerError
at com.app.Utilities.SensorPoll.run(SensorPoll.java:55)
at java.util.TimerThread.mainLoop(Timer.java:562)
at java.util.TimerThread.run(Timer.java:512)
Caused by: java.lang.RuntimeException: Can't create handler inside thread Thread[Timer-0,5,main] that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:207)
at android.os.Handler.<init>(Handler.java:119)
at com.app.MainActivity.<clinit>(MainActivity.java:31)
at com.ap.Utilities.SensorPoll.run(SensorPoll.java:55)
at java.util.TimerThread.mainLoop(Timer.java:562)
at java.util.TimerThread.run(Timer.java:512)
The error is on the public void run(){ line in the TimerTask.
I need to be able to run this, i don't try to call it from an AsyncTask, just from inside onCreateView in a fragment. It's actaully called from within the onFinish() of a CountDownTimer(). How can i avoid this error and start my TimerTask on it's Thread? If you need anymore info please ask.
The Code:
The Call
new CountDownTimer(10000, 1000){
#Override
public void onTick(long millisUntilFinished) {
countdown.setText(String.valueOf(String.valueOf(counter)));
counter--;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onFinish() {
countdown.setText("Initialised");
srace.startSrace();
}
}.start();
The Method which calls the PollDirectly:
public void startSrace(){
sraceManager.startPoll();
}
The startPoll Method:(We are now in the Module Library)
public static void startPoll() {
TimerTask sensorPoll = new SensorPoll();
Timer timer = new Timer();
timer.scheduleAtFixedRate(sensorPoll, 0L, 9L);
}
SensorPoll - The TimerTask
public SensorPoll() {
}
#RequiresApi(
api = 24
)
//This is the error line-->
public void run() {
//Just gets sensor info in here
}
Not much too it. Thanks
i m new in android and trying to make simple program that can print variable in AsyncTask Class
here is my code
int a,b,c;
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
a =10;
b=10;
c=a+b;
Context ctx = null;
show(c, ctx );
return null;
}
public void show(int c2 ,Context c) {
// TODO Auto-generated method stub
Toast.makeText(c, "AsyncTask classs + c2 ", Toast.LENGTH_SHORT).show();
}
after running this program , i m getting run time Error
here us LogCat file view
Process: com.example.asycclass, PID: 2539
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:327)
at android.widget.Toast.<init>(Toast.java:92)
at android.widget.Toast.makeText(Toast.java:241)
at com.example.asycclass.MainActivity$AttemptLogin.show(MainActivity.java:74)
at com.example.asycclass.MainActivity$AttemptLogin.doInBackground(MainActivity.java:65)
at com.example.asycclass.MainActivity$AttemptLogin.doInBackground(MainActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
Move your show Toast code inside runOnUiThread like :
runOnUiThread(new Runnable() {
#Override
public void run() {
show(c, ctx );
}
});
I guess that the problem is that you're trying to create a Toast not from the main thread.
You must create a handler and Runnable for that and use handler.post()
For example
Runnable showToast = new Runnable() {
public void run() {
// Create your Toast here or whatever you want
}
}
Hi I am trying to use the service class for first time and have been facing problems. What I want is an infinitely running (unless killed by Android System) service with an active Network connection. I have written the code which works fine on Android 4.3 and 4.4 but the application crashes when I try running on Android 2.2. My code is as follows:
public class BackgroundMusicService extends Service {
private MediaPlayer mp;
private int id;
private static class BackgroundAsyncTaskClass extends AsyncTask<Void, Void, Void>{
protected Void doInBackground(Void... params) {
Log.v("Async","Async Called");
/*Network connection will be created here*/
return null;
}
}
private class ForThread implements Runnable{
public void run() {
while (true) {
try {
Log.v("ThreadSleeping","5 sec");
BackgroundAsyncTaskClass task = new BackgroundAsyncTaskClass();
task.execute();
Thread.sleep(5000);
} catch (InterruptedException e) {
}finally{
Log.v("Finally called","Finally called");
}
}
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v("onStartCommand Called","onStart Command Called");
Thread t;
ForThread ft = new ForThread();
t = new Thread(ft);
t.start();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
if(null != mp){
mp.stop();
mp.release();
Log.v("Destroyed","onDestroy Called");
}
}
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(),
this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(
getApplicationContext(), 1, restartServiceIntent,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext()
.getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
}
and the exception thrown by Android 2.2 is as follows:
04-28 09:51:41.435: W/dalvikvm(280): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
04-28 09:51:41.435: E/AndroidRuntime(280): FATAL EXCEPTION: Thread-8
04-28 09:51:41.435: E/AndroidRuntime(280): java.lang.ExceptionInInitializerError
04-28 09:51:41.435: E/AndroidRuntime(280): at com.example.backgroundservicedemo.BackgroundMusicService$ForThread.run(BackgroundMusicService.java:45)
04-28 09:51:41.435: E/AndroidRuntime(280): at java.lang.Thread.run(Thread.java:1096)
04-28 09:51:41.435: E/AndroidRuntime(280): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
04-28 09:51:41.435: E/AndroidRuntime(280): at android.os.Handler.<init>(Handler.java:121)
04-28 09:51:41.435: E/AndroidRuntime(280): at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
04-28 09:51:41.435: E/AndroidRuntime(280): at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
04-28 09:51:41.435: E/AndroidRuntime(280): at android.os.AsyncTask.<clinit>(AsyncTask.java:152)
Also, when I try using handler.post(new Runnable(){.... run(){}....} The UI hangs up but the background thread continues running and exits after it becomes out of memory.
Another thing that I have doubts about is:
When the application restarts, I want this active Service to stop, but how do I get a reference to this thread running in Background and how do I stop this? I would appreciate if anyone can redirect me to a suitable link/reference or could help me out with the code. Thanks
You have this inside a thread's run method
BackgroundAsyncTaskClass task = new BackgroundAsyncTaskClass();
task.execute();
Threading rules from the docs
The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
The task instance must be created on the UI thread.
execute(Params...) must be invoked on the UI thread.
Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
The task can be executed only once (an exception will be thrown if a second execution is attempted.)
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 8 years ago.
I make simply rss reader in android. I have the errors (I searched and tried some solutions but nothing):
Couldn't open http://pogoda.wp.pl/rss.xml
java.io.IOException: Couldn't open http://pogoda.wp.pl/rss.xml
at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:755)
at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:292)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:390)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:266)
at com.newsreader.RssReader.getItems(RssReader.java:23)
at com.newsreader.MainActivity$1$1.run(MainActivity.java:48)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4340)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
at java.net.InetAddress.getAllByName(InetAddress.java:220)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:753)
and activity:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(){
public void run(){
MainActivity.this.runOnUiThread(new Runnable(){
#Override
public void run() {
try{
RssReader reader = new RssReader("http://pogoda.wp.pl/rss.xml");
ListView items = (ListView) findViewById(R.id.listView1);
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(MainActivity.this, android.R.layout.simple_list_item_1, reader.getItems());
items.setAdapter(adapter);
Log.i("", ""+reader);
items.setOnItemClickListener(new ListListener(reader.getItems(), MainActivity.this));
}catch(Exception e){
Log.e("blad", e.getMessage(), e);
}
}
});
}
}.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I don't know what am I doing wrong. Maybe someone has got the same problem so please help.
Thanks
It is because you are performing network operation on main thread of activity. Using Async task will be a better option.
Caused by: android.os.NetworkOnMainThreadException
This speaks for itself.
Don't do networking on the main Thread!
AsyncTask to the rescue. Try it out it will work.
Always use AsyncTask to solve this issue.
BUT, if you're within the movie Swordfish, someone points a gun at you and say "fix it in 30 seconds", then change your targetSdkVersion to 9 in the Android Manifest and the exception will stop. Don't worry, it will run on devices with version higher than 9 too. Even so, correct your code later using AsyncTask.
Hi I am trying to execute the code below it suppose to open a loading dialog and dismiss it in the if statement.
here is the code:
loginBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
final ProgressDialog progress = ProgressDialog.show(thisActivity, "Please wait", "Loading please wait..", true);
Thread loginThread = new Thread(new Runnable()
{
#Override
public void run()
{
try
{
boolean userAllowed = login.loginUser(userEmail.getText().toString(), userPass.getText().toString());
if(userAllowed)
{
progress.dismiss();
startActivity(mainPage);
}
else
{
progress.dismiss();
Toast.makeText(context, "Invalide email and password", Toast.LENGTH_LONG).show();
}
}
catch (Exception e)
{
Toast.makeText(context, "There is some problem", Toast.LENGTH_LONG).show();
}
}
});
loginThread.start();
}
});
the logCat error output is:
05-09 22:37:26.508: E/AndroidRuntime(24820): FATAL EXCEPTION: Thread-1306
05-09 22:37:26.508: E/AndroidRuntime(24820): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
05-09 22:37:26.508: E/AndroidRuntime(24820): at android.os.Handler.<init>(Handler.java:197)
05-09 22:37:26.508: E/AndroidRuntime(24820): at android.os.Handler.<init>(Handler.java:111)
05-09 22:37:26.508: E/AndroidRuntime(24820): at android.widget.Toast$TN.<init>(Toast.java:324)
05-09 22:37:26.508: E/AndroidRuntime(24820): at android.widget.Toast.<init>(Toast.java:91)
05-09 22:37:26.508: E/AndroidRuntime(24820): at android.widget.Toast.makeText(Toast.java:238)
05-09 22:37:26.508: E/AndroidRuntime(24820): at com.shale.activities.MainActivity$1$1.run(MainActivity.java:93)
05-09 22:37:26.508: E/AndroidRuntime(24820): at java.lang.Thread.run(Thread.java:856)
My reference was this tutorial.
Thanks!
as in Log :
RuntimeException: Can't create handler inside thread that has not
called Looper.prepare()
means you are trying to update or access UI elements from non ui Thread . so you will need to use Activity.runOnUiThread , Handler or AsyncTask for updating or accessing UI from other Thread. do it as:
Your_Activity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
//update Ui elements here
}
});
You can't do anything UI related (including dismissing dialogs) unless you're on the UI thread. You need to offload that via a runOnUiThread or by passing a message to a handler on the UI thread. Or better yet- make that thread an AsyncTask and do it in the onPostExecute()
An alternative to the above would be to send a broadcast and have a BroadcastReceiver handle receiving that broadcast and act upon it as you wish.