This particular error occurs mainly when working with threads in an Android project. Β So straight to the point, no stories.
WHAT IT MEANS
I’m not going to go into all the technicalities of threading, what this error simply means is that you are trying to manipulate or show a User Interface component from a non-UI thread. Β A simple example:
1 2 3 4 5 6 |
Thread thread = new Thread(){ public void run(){ Toast.makeText(TimelineActivity.this, "Finco is Daddy", Toast.LENGTH_LONG); } }; thread.start(); |
Running the above code will result in the “Can’t create handler inside thread that has not called Looper.prepare()” error.
SOLUTION
- Use activity.runOnUiThread(): Β When manipulating or showing a UI component from a non UI Thread, simply use theΒ runOnUiThread() method. Β For example:
12345678910Thread thread = new Thread(){public void run(){runOnUiThread(new Runnable() {public void run() {Toast.makeText(TimelineActivity.this, "Finco is Daddy", Toast.LENGTH_LONG);}});}};thread.start(); - Use Looper: Β Here’s another very simple solution:
1234567891011121314Thread thread = new Thread(){public void run(){Looper.prepare();//Call looper.prepare()Handler mHandler = new Handler() {public void handleMessage(Message msg) {Toast.makeText(TimelineActivity.this, "Finco is Daddy", Toast.LENGTH_LONG);}};Looper.loop();}};thread.start();
There are many other solutions but I personally find these 2 very easy to implement.
REFERENCE
This StackOverflow question thought me a lot about this Android Error:
https://stackoverflow.com/questions/3875184/cant-create-handler-inside-thread-that-has-not-called-looper-prepare
Feel free to ask any questions or contribute to this post in the comment section below.
1 Comment