I am new in Kotlin, I have a first activity with login, and second activity with recycle view. The data of recicle view is taken from http3 method.
Sorry for my bad english.
How I can show a dialogPopUp when I have code 404, and return in previous one login activity?
OkHttp callbacks are executed on a background thread if you use enqueue and showing a dialog is a UI task therefor it needs to be run on the UI thread.
In your case you can easily do this by running your dialog code using runOnUiThread.
runOnUiThread {
dialogPopUp("Error parameters", mContext ).showDialog()
}
Just as you have done in your else block.
You can also achieve this by using a Handler which has been created on the UI thread.
Update: Taking a closer look at your code I realized you're running fetchJson in a background thread by using the doAsync function. When you use enqueue on a OkHttp.Call you're basically sending it to be executed on a background thread so no need to use doAsync.
If you remove the doAsync you don't need to use runOnUiThread anymore as the callback will be executed on the UI thread.
Can't create handler inside thread that has not called Looper.prepare()
This basically means that you need to use the UI thread when calling this code. The UI thread will need to be used for showing your dialog.
You can do:
runOnUiThread {
dialogPopUp("Error parameters", mContext ).showDialog()
}
Related
This question already has answers here:
How do we use runOnUiThread in Android?
(13 answers)
Closed 4 years ago.
In following code
The way we are using runOnUiThread
shouldn't this create issue with the existing UI Thread
hence creating an issue with the application , hence shouldnt be used
Thread thread = new Thread(new Runnable(){
#Override
public void run(){
//what is meant by the inside code of this run(), how is this updating the UI
runOnUiThread(new Runnable(){
#Override
public void run(){
}
})
}
})
In android,for long running task you should use separate thread such as AsyncTask() or service.Suppose you want to update your UI like you want to show any Toast to user then you should write runOnUiThread(),because only UI thread will allow to touch UI components.
getActivity().runOnUiThread(new Runnable()
{
#Override
public void run() {
Toast.makeText(getContext(), "API calling done!!", Toast.LENGTH_LONG).show();
}
});
There are two types of thread in Android.
1 is UI or Main thread on which your UI elements (layouts) are rendered.
2 is Worker Thread in which long task should be executed (like AsyncTask & Networking).
If you write some task in new Thread, that mean that task will be executed in worker thread.
Now you will use runOnUiThread or new Handler(Looper.getMainLooper()) because you can not touch UI elements in worker thread.
So basically when you are updating UI like setText(), or Toast or any UI operations, you will have to UI thread and you should use worker thread when you are doing some long executions.
Edit
Generally we don't have to manage threading in Android. Because all libraries we use are smart. Although in some cases we have to manage threading as well.
Example
Assume you are calling an web-service(api) in a new Thread, now when response comes you want show a Toast. If you just write Toast.show... directly in response inside worker Thread you will get exception.
Only the original thread that created a view hierarchy can touch its views.
Now to overcome this issue you have to use runOnUiThread, so that you can show Toast.
Whenever we have some Long running tasks we switch to some worker threads and avoid Main Thread and allow a smoother user experience and avoid ANR.
But, when the time comes to update the UI we must “return” to the
Main Thread, as only Main Thread is allowed to touch and update the application
UI.
we can achieve this by making a call to the Activity’s runOnUiThread() method:
Basically what runOnUiThread() will do is - Runs the specified action
on the UI thread. It will check the current thread and if it finds its
the MainThread it will execute that task immediately , otherwise first
it will switch you to app MainThread and then it will execute the
given task.
When a new Thread is created and executed, it does the task in the background thread. But the method runOnUiThread() is used for running the code on the main UI thread.
In your code, runOnUiThread() method is called and hence you are able to update the UI thread from the other thread.
when thread is running in the method runOnUiThread () will update the UI Components (textview .. etc..)
by calling runOnUiThread, you can update the status too
shouldn't this create issue with the existing UI Thread
Not at all. You said "existing UI Thread". There is only one UI thread. The runOnUiThread() will only add the runnable to a queue of tasks which the UI thread executed one by one. You can check the doc.
No worries! This is one of the standard way for updating UI components from a separate thread or even on UI thread itself on Android platform.
Also, runOnUiThread is an method of Activity class, it 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.
Another standard way is using Handler and Message as officially documented by Android Developer here https://developer.android.com/training/multiple-threads/communicate-ui
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)
Is there any callBack to setContentView in Android, since i'm doing a heavy operation right after setContentView line, and it seems to skip that setContentView.
So i was thinking of moving the heavyOperation to the callBack of setContentView.
Thanks
EDIT:
Pseudo Code:
AudioRecord Finishes
SetContentView(1) //To show a "Processing" screen with no buttons
FFT analysis
SetContentView(2) //On FFT analysis DONE.
In my case "SetContentView(1)" NEVER occurs.
EDIT # 2:
I did the heavy operation in another Thread, and used Handler to send a Message after heavy operation finishes to treat it as a callBack.
Thanks for all the help guys
Short answer: No callback for the setContentView.
If you are doing network operation then you can use the AsyncTask for this.
If you are doing any more heavy operation and want to update the UI then you can do that using the Service and BroadCastReceiver.
For this you have to make your own callback using the interface.
heavy work should be done in asynk tasks or as a service or on other threads
Don't do any heavy calculations on the main UI thread where onCreate() and such are run.
What happens that the first setContentView() posts a "layout and draw" message to the UI thread message queue. Then your calculation blocks the UI thread, preventing messages in the queue from being processed. The second setContentView() posts another message to the queue. When the control eventually returns to the message loop, both messages are processed and you'll get the layout set up by the last call to setContentView().
For heavy computations, use a separate thread. For example, an IntentService or an AsyncTask make threading easier.
My hack.
final Handler handler = new Handler();
setContentView(layoutResID); // This posts some messages to message queue.
handler.post(new Runnable() { // Post another message at the end.
#Override
public void run()
{
// Called after layout has changed.
// If you want to skip some more works (like transitions),
// call another handler.post() here.
}
});
To see what happens, set a break point at the line Message msg = queue.next(); in Looper.loop() may help.
I was facing a quite similar problem a day ago, but I figured it out. (I know your problem is solved, just offering a different approach which doesn't require a handler or callback.
Most Suitable for running U.I. functions :
If you need to do something like this :runTask() then
setContentView() (or any other ui function) you can run the task on different thread by using AsyncTask or you can set a timer for when the task is completed (if your task takes a certain time), the User Interface functions will be called.
But since the Timer class, runs the functions on a different thread, you can not run the setContentView() inside it. So you can use a runOnUiThread(Runnable action) method inside the overloaded run() function of Timer class. You just need to define a function that returns a runnable. Define your Ui operations in the runnable action.
Hope it helps someone.
I have a thread which is started in onCreate() and this thread fetches some data.
Is it possible that before the thread is terminated should be able to update the ListView?
Now as the thread is not the UI thread, it cannot directly update the listview array adapter.
Is there a way out?
I was thinking that is it possible to trigger a Handler from thread whose runnable gets executed on main UI thread.
Not sure if I understood your problem completely, but I believe there are two ways to achieve what you want:
1- Start an AsyncTask instead of a thread. AsyncTask's onPostExecute() will run in the UI thread, which means you can do anything UI-related in there. You can start the AsyncTask in onCreate(), and, once it finished, it calls a method on your activity which does:
myAdapter.notifyDataSetChanged();
2- Use runOnUIThread()
Use your Activity's runOnUiThread(Runnable action)
link
Can someone explain to me what exactly the UI thread is?
On developer.android.com it says about the runOnUiThread function
public final void runOnUiThread (Runnable action)
Since: API Level 1 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.
Does the UI thread mean that this will be run everytime the activity is pushed the the background by some ui activity like incoming call or screen dimming etc.? If not, what exactly does the UI thread include ?
Thank you
The UIThread is the main thread of execution for your application. This is where most of your application code is run. All of your application components (Activities, Services, ContentProviders, BroadcastReceivers) are created in this thread, and any system calls to those components are performed in this thread.
For instance, let's say your application is a single Activity class. Then all of the lifecycle methods and most of your event handling code is run in this UIThread. These are methods like onCreate, onPause, onDestroy, onClick, etc. Additionally, this is where all of the updates to the UI are made. Anything that causes the UI to be updated or changed HAS to happen on the UI thread.
For more info on your application's Processes and Threads click here.
When you explicitly spawn a new thread to do work in the background, this code is not run on the UIThread. So what happens if this background thread needs to do something that changes the UI? This is what the runOnUiThread is for. Actually you're supposed to use a Handler (see the link below for more info on this). It provides these background threads the ability to execute code that can modify the UI. They do this by putting the UI-modifying code in a Runnable object and passing it to the runOnUiThread method.
For more info on spawning worker threads and updating the UI from them click here
I personally only use the runOnUiThread method in my Instrumentation Tests. Since the test code does not execute in the UIThread, you need to use this method to run code that modifies the UI. So, I use it to inject click and key events into my application. I can then check the state of the application to make sure the correct things happened.
For more info on testing and running code on the UIThread click here
If you execute blocking code (e.g. a Http-Request) in a separate Thread, consider using AsyncTask. Its doInBackground-Method runs on a separate Thread. AsyncTask provides you with methods onProgressUpdate and onPostExecute which are guaranteed to run on the UI thread.
If you need GUI-progress updates (e.g. via a progressbar) call publishProgress inside doInBackground. This leads to a subsequent call of onPublishProgress which is also guaranteed to run on the UI thread.
onPostExecute is automatically called after doInBackground returns.
All UI drawings etc. happen in a separate thread. Its called the UIThread. If you want to make any change to UI u must use make sure it happens in UIThread's context.
Easiest way of doing it is to make use of runOnUiThread