Creating a new object from Android update() loop - android

I am trying to create an Android game, but am running into trouble with one part. I started with the Android LunarLander example project, so instead of pasting my confusing code, I will just identify the relevant section in the sample code. In the updatePhysics method, I try to create a new FlyingObject (a class I created). I receive this error for the line where I try to create the FlyingObject:
E/AndroidRuntime(201): Uncaught handler: thread Thread-9 exiting due to uncaught exception
E/AndroidRuntime(201): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
I have Googled around, and cannot figure out how I can dynamically create objects in my game.
Any help would be greatly appreciated. Thanks!

Well this error mostly comes when you are trying to Update the UI from a Non-UI thread. So, probably use Handler or runOnUiThread() to update your UI thread from a Non-UI thread.

Related

Difference between android runOnUiThread and simple code in java

I am a beginner in android application development.I am working with threads in android.I have read about a runOnUiThread which run code on main UI(if i am not wrong?i guess.).
My question is what is the difference between normal code on main UI and code inside runOnIUThread.
Example:1
class A
{
getDataFromServer(foo);//Code on mainUI
}
Example:2
getActivity.runOnUiThread(new Runnable(){
#Override
public void run(){
getDataFromServer(foo);
}
});
What is difference in both example.Please help me.Your response will be a new learning for me.
Assuming that you meant simple code for UIThread code,
What is a thread ?
A thread defines a process running
First runOnUiThread ..
Runs the specified action on the UI thread. If the current thread is
the UI thread, then the action is executed immediately. If the current
thread is not the UI thread, the action is posted to the event queue
of the UI thread.
What is UIThread
Main thread of execution for your application
Most of your application code will run here onCreate, onPause, onDestroy, onClick, etc.
So simply Anything that causes the UI to be updated or changed HAS to happen on the UI thread
When you explicitly spawn a new thread to do work in the background, this code is not run on the UIThread.Now what if you want to do something that changes the UI?
Then you are welcome to runOnUiThread
You have to use runOnUiThread() when you want to update your UI from a Non-UI Thread. For eg- If you want to update your UI from a background Thread. You can also use Handler for the same thing.
Normally your code is executed on your UI thread. For longer taking tasks (such as network requests, etc...) you will use a background tasks (Handler, AsyncTask, Thread, ...).
As your Views can only be touched from a UI thread, you use runOnUiThread() if you are executing code in a background thread and you need to update your views, from this background thread.
To explain 'why' Android has the 'runOnUiThread()' option, it is important to understand that java is only used to create the bytecode (dex) that Android uses. The code running on the phone is NOT java.
Additionally, Android threads 'can' have a thing called a 'looper'. This 'looper' is what handles 'tasks(technically runnables and messages)' in order via a queue. The 'main ui thread' has by default a looper already attached to it.
That means that your runnable you created was put onto the looper's queue of the main UI thread. (this is why the runnable is NOT instantaneously ran, but will be ran 'quickly'/'soon')
The reason you'd use a runnable to run code on the UI thread is because you are in some other 'background thread' that you created... and want to update the UI in some way. (Only the UI thread can interact with the UI)

Android - myLooper() vs getMainLooper()

Just clarifying but in an Android activity on MAIN Thread if I call Looper.myLooper() vs Looper.getMainLooper() the return the same reference, right? they are the same thing? I know I would never have to call these usually as Android takes care of this but I'd like to know how they differ when being called from the main thread?
if from the main thread I call
Looper.myLooper().quit();
// or
Looper.getMainLooper().quit();
They both give the same runtime exception so I'm assuming they are the same reference:
Caused by: java.lang.RuntimeException: Main thread not allowed to quit.
can anyone confirm?
You have it described in the docs:
getMainLooper()
Returns the application's main looper, which lives in the main thread of the application.
myLooper()
Return the Looper object associated with the current thread. Returns null if the calling thread is not associated with a Looper.
As for whether getMainLooper() is of any use, I can assure you it really is. If you do some code on a background thread and want to execute code on the UI thread, e.g. update UI, use the following code:
new Handler(Looper.getMainLooper()).post(new Runnable() {
// execute code that must be run on the UI thread
});
Of course, there are other ways of achieving that.
Another use is if you want to check if the currently executed code is running on the UI thread, e.g. you want to throw/assert:
boolean isUiThread = Looper.getMainLooper().getThread() == Thread.currentThread();
or
boolean isUiThread = Looper.getMainLooper().isCurrentThread();
Looper.getMainLooper() is convenience API to get looper which is attached to the main thread of the activity.It is usefull when you want to excute some code on main thread from a background thread.
It is usually used as follows:
new Handler(Looper.getMainLooper()).post(task);
Looper.myLooper() is api to get looper attached to current thread
If you call these two methods in the main thread, they are the same object! You can find answers in the source code of ActivityThread.java, Looper.java and ThreadLocal.java.

Android: make AudioRecord onPeriodicNotification be called in another thread

So, i am using ExtAudioRecorder: http://i-liger.com/sites/default/files/ExtAudioRecorder.java
My problem is that onPeriodNotification is called on the UI thread. What would be an ellegant sollution to this. Making new thread in every onPeriodNotification call seems very excessive. I tried initializing the recorder in new Thread(), but calls were still made on the UI thread.
You can't. But what you can do is post a message to the second thread in the onPeriodNotification, and then return.

Android 2.3.3 (API level 8) AsyncTask weirdness

I Have several activities handling diferent screens with information that is loaded asynchrounously via AsyncTask.
All data fetching are done in doInBackground()
All UI operations are done in onPostExecute()
In some instances I get the error: "Can't create handler inside thread that has not called Looper.prepare()"
If I do the Looper.prepare(), it crashes if a new activity is instanced for this class.
It's a weird behaviour that I'm able to find why it happens. The other screens with similar behaviour work as expected. There are no differences between them that I can find.
Has anyone had this behaviour?
"Can't create handler inside thread that has not called Looper.prepare()" means that you are trying to call AsyncTask.execute() outside of the UI thread.
There are few rules you should follow using AsyncTask:
The task instance must be created on the UI thread.
execute(Params...) must be invoked on the UI thread.
Also it can mean than you are creating Handler object inside doInBackground method.

Long running process in separate thread updating UI

I noticed a similar problem for dot NET, but my problem is for Android, so perhaps solution looks different.
The process is activated by clicking button. The process was running as part of UI thread and at the end it did updating UI. I have added progress dialog to be more user friendly, so I instantiate a thread running the process and at the end it updates UI and dismisses progress dialog. Unfortunately UI update is failing with the exception below:
07-19 21:14:04.602: ERROR/Atjeews(283): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
If I try to block UI thread and release it after long process finishes to update UI, the progress dialog doesn't get shown. Should I try to show progress dialog in a separate thread instead, or there is another simpler solution?
please check http://developer.android.com/resources/articles/painless-threading.html
Taken from the Android Developers Processes and Threads page:
To fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:
Activity.runOnUiThread(Runnable)
View.post(Runnable)
View.postDelayed(Runnable, long)
You can just instantiate an anonymous Runnable as the argument, like post(new Runnable(){doWhatever();}), that will do whatever you want on the UI thread instead.

Categories

Resources