I'm writing an Android app. I have a main method, which creates and runs a new Thread using an anonymous inner Runnable class. The run() method, when it's done, calls a method on it's parent class (in the main thread) that calls notifyDataSetChanged() so that the main thread can redraw the new data. This is causing all kinds of trouble (ViewRoot$CalledFromWrongThreadException).
The thing is, this method being called from the worker thread is on the class that's created in the UI thread. Shouldn't that be running on the UI thread? Or am I missing something?
Here's some code about what I'm talking about:
public class Mealfire extends Activity {
#Override
public void onCreate(Bundle icicle) {
(new Thread() {
public void run() {
// Do a bunch of slow network stuff.
update();
}
}).start();
}
private void update() {
myAdapter.notifyDatasetChanged();
}
}
Have you tried calling the UI updating code with Activity#runOnUiThread? Something like this:
private void update() {
runOnUiThread(new Runnable() {
public void run() {
myAdapter.notifyDatasetChanged();
}
}
}
Related
I have in my activity a Handler which does two things, for GAME_ACTIVITY_UPDATE_UI message, must do some calculations outside the main thread, and for GAME_ACTIVITY_REFRESH_UI must execute itself in the main thread. I have a separated thread outside my activity, which must call that handler for the two things, and in one case must respect that its outside the main thread, but for the other case must respect that must execute the code in the main thread.
The problem is that when my outside tread calls the handler of the activity, the code of the handleMessage is always executed in the main thread. How can I maintain the thread that has called handler sendEmptyMessage for the case of GAME_ACTIVITY_UPDATE_UI instead of executing the code in the main ui thread?
My activity handler:
Handler gameHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
switch (msg.what){
case GAME_ACTIVITY_UPDATE_UI:
updateUI();
break;
case GAME_ACTIVITY_REFRESH_UI:
refreshUI();
break;
}
}
};
My outside thread which calls the handler
public void run() {
while(true){
//a lot more stuff
gameHandler.sendEmptyMessage(GameActivity.GAME_ACTIVITY_UPDATE_UI);
gameHandler.sendEmptyMessage(GameActivity.GAME_ACTIVITY_REFRESH_UI);
//a lot more stuff
}
}
Remember that:
GAME_ACTIVITY_UPDATE_UI: must execute in the separate thread (not working)
GAME_ACTIVITY_REFRESH_UI: must execute in the main thread (currently working)
Have you looked at the AsyncTask? If your background task runs only for a few seconds then you should use this concept.
but if you are reluctant to change your code, I think you can do it like this
public class MainActivity extends AppCompatActivity implements CallBackListener {
View uiView;
private Handler gameHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
updateUiInBackground(MainActivity.this);
break;
case 1:
refreshUiInUiThread();
break;
}
}
};
private void updateUiInBackground(CallBackListener callBackListener) {
//do some task in background
//can not change uiView here
callBackListener.backgroundWorkFinished();
}
private void refreshUiInUiThread() {
//Do some task
uiView.someMetheode();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uiView = findViewById(R.id.ui);
new Thread(new Runnable() {
#Override
public void run() {
gameHandler.sendEmptyMessage(0);
}
}).start();
this.runOnUiThread(new Runnable() {
#Override
public void run() {
gameHandler.sendEmptyMessage(1);
}
});
}
#Override
public void backgroundWorkFinished() {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
uiView.someMethod();
}
});
}
}
and this is the callback Class
public interface CallBackListener {
void backgroundWorkFinished();
}
Currently in my Android Game there is a simple thread that runs, decreasing a horizontal progressbar by 1 every X milliseconds. I'm trying to implement a method so when the progressbar hits 0, a TextView changes to "Game Over". The app crashes whenever this function is called in this way. I have also initialized the variable correctly so the method should have no trouble seeing this TextView.
public class MyThread extends Thread{
#Override
public void run(){
while (counter > 0 && keepRunning){
counter = counter - 1;
android.os.SystemClock.sleep(calculateSleepTick());
mHandler.post(new Runnable() {
#Override
public void run() {
progressTest.setProgress(counter);
}
});
}
isGameOver();
}
}
public void isGameOver(){
scoreText.setText("Game Over");
}
Your isGameOver function sets the text of a UI element. You can't call functions of UI elements on a thread other than main. It needs to be posted to the UI thread to do that.
You cannot update UI in non UI threads. Call isGameOver() this way.
runOnUiThread(new Runnable() {
#Override
public void run() {
isGameOver();
}
});
I've got game based on CountDownTimer, which is continuously repeating countdowns. This countDown is counting time for user to react on some action related to number, if user reacts onFinish() is called by some clickListener or by itself if the time was up. Depending of succesCondition(), method success or fail is called and those methods are defining if game is still running.
OnCreate
loop = gameLoop(time).start();
MainActivity
public CountDownTimer gameLoop(int time){
return new CountDownTimer(time, time+100) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
if (!Conditions.succesCondition(number)) {
success();
} else {
fail();
}
}
};
}
public void success() {
loop.cancel();
scoreCount++;
animation.start();
}
public void fail(){
loop.cancel();
}
However this timer runs on Main thread and that provides well known issue skipped xx frames, your app might be doing too much work on its main thread and I found that this is common issue for CountDownTimer and replacing it with Handler is a solution.
I can't put this timer in AsyncTask because it performs mainly UI related tasks (TextViews, TextSwitcher, some progressBar etc. in success() method. I didn't put that in code in those methods for more clean view of the main problem. I'm trying to reconstruct CountDownTimer- like concept with handler and runnable to replace my Timer, but I'm actually stuck with nothing. As you can see I'm using only onFinish method, onTick is not necessary.
I suggest using a combination of java.util.Timer, java.util.TimerTask and Activity.runOnUiThread(). First create a Timer and call one of its schedule...()methods. Any action that needs to be done on the main (ui) thread can be wrapped in runOnUiThread(() -> { ...}). Be sure to call cancel() on TimerTask and Timer if those objects are no longer needed. Cancelling the Timer cancels the TimerTask as well.
Here is how this may look like:
public class TimerTaskActivity extends Activity {
Timer timer;
TimerTask timerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timertask);
...
}
#Override
protected void onStart() {
super.onStart();
timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(() -> {
....
});
}
};
timer.scheduleAtFixedRate(timerTask, 2000, 2000);
}
#Override
protected void onPause() {
super.onPause();
timer.cancel();
}
}
You may handle this situation using AsyncTask as well overriding the onProgressUpdate method.
Here's an example about how you can achieve the behaviour to interact with your main thread from AsyncTask. The example shows the update of a download which can be easily transformed to your specific problem of timer.
Update
In my case almost all code would be in onProgressUpdate, would it
still make any sense?
No, your code will not be in onProgressUpdate. The onProgressUpdate method will only be updating your timer in your UI. As far as I could understand, the success and the fail will be triggered based on user action as well. Then those actions are triggered, you can stop the AsyncTask to update your timer as well. You just need to AsyncTask to update the timer value time to time.
You will get a callback in your Activity when the AsyncTask finishes. See the mNotificationHelper.completed(); function in the above example. When you are notified in your Activity when the timer finishes, you might then execute the following task there.
public void completed() {
if (!Conditions.succesCondition(number)) {
success();
} else {
fail();
}
}
OK. I finally figured out how to handle it with handler (hehe):
public void startGameAction() {
//My game actions
handler = new Handler();
runnable = () -> {
if (!Conditions.succesCondition(number)) {
success();
} else {
fail();
}
};
handler.postDelayed(runnable,time);
}
public void success(){
handler.removeCallbacks(runnable);
handler = null;
scoreCount++;
//other stuff
startGameAction();
}
private void fail() {
handler.removeCallbacks(runnable);
//other stuff
}
onCreate only startGame call, handler and runnable defined as class fields
startGameAction();
I've seen some similar questions and got some information but they stop shy of telling me enough to get it working.
What I'm trying to do is make a simple rhythm game where the player taps a button at regular intervals (ie. beats). I wanted to set up a way of signalling when to tap by having the button change colour, and since this would be a repeated task at regular intervals I want to use a timer object with a schedule method.
But when I try calling on this method it tells me that I can't change the UI in a non UI thread. I've tried a few ways to write a method in the main thread that I can call from the timer object but I get the same error every time. I'm assuming that I just have the wrong idea about what counts as being from the UI thread, so I was hoping someone could clear it up.
Here's a snippet of one way I tried it, just to show what my code looks like:
OnClickListener clickButton = new View.OnClickListener() {
public void onClick(View v) {
if (startBeat == 0){
startBeat = System.nanoTime();
timerStart.scheduleAtFixedRate((new TimerTask()
{
public void run()
{
flashButton();
}
}), 0, beatTime);
timerEnd.schedule(new TimerTask()
{
public void run()
{
unflashButton();
}
}, beatTolerance*2, beatTime);
return;
}
};
public void flashButton(){
beatPrompt.setBackgroundColor(getResources().getColor(R.color.primary1transparent_very));
}
public void unflashButton(){
beatPrompt.setBackgroundColor(getResources().getColor(R.color.primary1));
}
To be clear, this is all contained within my MainActivity class along with the OnCreate class.
if you are in an activity all you need to do is use runOnUiThread() and then place the code to change the ui element in there
public void flashButton(){
runOnUiThread(new Runnable() {
#Override
public void run() {
beatPrompt.setBackgroundColor(getResources().getColor(R.color.primary1transparent_very));
}
});
}
You cannot, under any circumstances, touch a UI object from a non UI thread.
You can accomplish your intent using Handler.sendMessageDelayed
UI can only be touched by the main thread. You should post the actions you are performing on the ui thread via handler or via runOnUiThread
Try something similar to this
timerStart.scheduleAtFixedRate((new TimerTask()
{
public void run()
{
//replace MainActivity with your activity
//if inside a fragment use getActivity()
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
flashButton();
}
});
}
}), 0, beatTime);
If you are in an Activity you could surround flashButton() with an runOnUiThread.
...
runOnUiThread(new Runnable(){
public void run(){
flashButton();
}
});
...
use android.os.Handler Class. Change your code as follows:
private Handler handler=new Handler();
public void flashButton(){
handler.post(new Runnable(){
public void run(){
beatPrompt.setBackgroundColor(getResources().getColor(R.color.primary1transparent_very));
}
});
}
public void unflashButton(){
handler.post(new Runnable(){
public void run(){
beatPrompt.setBackgroundColor(getResources().getColor(R.color.primary1));
}
});
}
Intro: I have made a Base Activity to extend my other activities to. I have overriden several methods with runnables in the function bodies, for example:
#Override
protected void onStop(){
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
BaseActivity.super.onStop();
}
}, Fade.fadeDuration);
}
However, I get a SuperNotCalledException when I try to run the app. If I take the super.onStop() out of the runnable, I get no exception whatsoever.
Question: How do I call the super.onStop from a runnable in a base activity without causing a SuperNotCalledException?
Additional info: I am trying to add a fadeoutanimation which only fades out certain views. This takes about 700ms so I need to delay the onStop for 700ms as well. The problem is that this is a hassle to code in every activity. I want to make a base activity so I don't have to worry about the fading in every single activity.
If you are trying to simply delay execution of the super.onStop I would use a CountDownLatch.
Maybe something like this :
private void CountDownLatch latch;
private void long latchWait = 10L; // seconds
private void TimeUnit latchWaitUnit = SECONDS;
#Override
protected void onStop(){
try{
this.latch.await(this.latchWait, this.latchWaitUnit);
catch(InterruptedException e){
// Handle
}finally{
super.onStop();
}
}
public void startLatch(long wait){
this.latch = new CountDownLatch(1);
this.latchWait = wait;
}
public void releaseLatch(){
this.latch.countDown()
}
I did not test this code.