I am trying to implement a thread that changes something on the UI in a Fragment
. Therefore I need to refer to the main thread.
Based on my research, I've found that the following code should do the trick:
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(menuActivity, "HELLO", Toast.LENGTH_SHORT).show();
}
});
This will execute only once though, even if the Looper
should normally keep the thread alive. Trying to invoke Looper.prepare()
inside the Handler
will cause a RuntimeException
as only one Looper
is allowed per thread.
Edit: My goal is to update a TextView permanently each second.
I have also tried the following:
Thread t = new Thread() {
@Override
public void run() {
menuActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
System.out.println("-----------TEST");
}
});
}
};
t.start();
But this will execute only once too.
I've also read this article, but I guess my first snippet of code is just a shorter version of the code shown in the article.
Where may my mistake be in any of these snippets of code?
This question is not a duplicate, due to the fact that I presented a totally different snippet of code which is the base of the problem I had. Furthermore, the Looper is explained more in depth in this thread.