Android App Crashing after calling method in a thread? - java

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();
}
});

Related

Replacing CountDownTimer with Handler and Runnable for better performance

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();

Update a textView in real time (using a for)

So I have an android app where I want to decrement a value and display it in a textview. I start from 1000 and decrement it by 1 from 1 to 1 seconds. This acts as a score that decreases in time if you stay more on the level. This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
timeText = (TextView) findViewById(R.id.textView5);
runOnUiThread(new Runnable() {
#Override
public void run() {
for(time=1000;time>=0;time--){
try {
TimeUnit.SECONDS.sleep(1);
timeText.setText(String.valueOf(time));
System.out.println(time);
}
catch(Exception e)
{
System.out.println("Error on delay");
}
}}
});
}
My error is that whenever I enter this activity, the screen turns black. The console is printing the values from second to second and if i comment the "for" the textView displays properly the value 1000 (if i declare int time = 1000 of course). I am really not sure what the problem is here. Does somebody know what i'm doing wrong?
You can't just loop on the UI thread like that. Inside Android there's a message loop on the UI thread. When it needs to draw, it sends a message to that message loop. Until you process that message the changes won't appear on screen. And to process a message, your code must finish and return to the message loop.
If you want to do this, you can't use a for loop on the UI thread. You need to send individual messages to a Handler for each draw you want to make.
You are pausing the UI in that for loop.
To achieve what you want, either use a Handler
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//update textview here
}
},1000);
OR
use a Timer
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//update
}
},1000,0);
I don't know much about handlers but you don't need a for loop in timer.
In your case:
long time=1000;
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable(){
timeText.setText(String.valueOf(time))
time--;
});
}
},1000,0).start();
Good luck

Google Glass Immersion - OnClick not working inside a separate thread

My problem is pretty simple. I am creating a card based on the result of a HTTP query performed inside a separate thread. The card also has an onclick method and is defined inside a runOnUiThread() located inside the separate thread. However, when the device is tapped, the onclick event isn't fired.
Here is my code:
private void login() {
Runnable r = new Runnable() {
#Override
public void run() {
// irrelevant code
runOnUiThread(new Runnable() {
#Override
public void run() {
setContentView(buildError(code));
}
}
}
Thread t = new Thread(r);
t.start();
}
private View buildError(String code) {
CardBuilder card = new CardBuilder(this, CardBuilder.Layout.ALERT);
card.setIcon(R.drawable.ic_warning_150);
if (code.equals("1"))
card.setText("Incorrect credientals");
else
card.setText("Unexpected error");
card.setFootnote("Tap to try again");
View cView = card.getView();
cView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Event", "Clicked"); // This is what isn't triggering
}
});
cView.setFocusable(true);
cView.setFocusableInTouchMode(true);
return cView;
}
Even though the snippet of code contains an error (can't be compiled, missing ; at the Runnable statement), you were on the right track.
The View simply needs to request the focus in order to be clickable right away. Otherwise you'll have to move the focus manually.
cView.setFocusable(true);
cView.setFocusableInTouchMode(true);
cView.requestFocus();
Reference

Editing a Button's colour in a nonUI thread (Android)

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));
}
});
}

Java Thread Message Passing

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();
}
}
}

Categories