This is my problem. In my android application I have a process which is execute by the Thread class. During this process I need to send a message to the user to get confirm he needs to do it further. In my Thread class I have only Service instance and don't have an activity instance. So I used separate dialog activity to display a AlertDialog to the user. Now I need to get the answer that the user chose in this dialog activity box.
I know we can use Messages and Handlers for sending messages between thread class to Activity. But my problem is different than that.
Is there any way to get the user answer to thread class or else is there any way to display a message box to user inside the thread class rather that using dialogActivity ?
Do you have any other suggestion to solve this issue? Any clue or help would be appreciated.
Related
Ok first of all android is really confusing. The scenario is I have about two runnable classes which are created from a Login View and if logged in it will create another view which will have other data and even more activities can be created from there
Now I can pass the the Login view context when creating a thread for the runnable class and edit out UI elements in them like this:
((Activity)someContext).runOnUiThread(new Runnable(){
public void run()
{
TextView txtErr = (TextView) ((Activity)someContext).findViewById(R.id.errMsg);
txtErr.setText("Some message");
}
});
But the issue is there will be more activities that will be created and the runnable class is created at the time of logging in, and I can't keep passing contexts.
Is there a better way for accessing the UI elements of different activities from different threads?
P.S: the threads which will be accessing the UI elements doesn't extend Activity and are running in a separate thread.
EDIT
I think I need to make my question more clear... I am developing a client app for a messenger... The process goes this way... User clicks on login button which creates a thread in a separate class named ClientThread for handling socket connection and keeping the connection alive till the user logs out or connection drops. The ClientThread class loops till the socket is connected and whenever some data is received the data is passed to another thread in a class named ProcessDataThread which do the parsing of data and will update the UI accordingly.
Now in a response from server if the user is logged in I want to create an activity from that class and keep a context to that activity in ProcessDataThread as I will be updating UI on further responses from server. And if login fails ProcessDataThread will display a message on the main activity saying login failed, now I was able to achieve the later by passing the context from the MainActivity to the two threads when clicked on Login like this:
global_constants.clientObject = new ClientThread(this);
global_constants.clientThread = new Thread(global_constants.clientObject);
global_constants.clientThread.start();
And then from ClientThread to ProcessDataThread
global_constants.updateConversationHandler.post(new ProcessDataThread(SharedBuff, cntxt));
But how will I create more activities from a non-activity class and do all update them or find a UI element etc...
Not sure if I understand you, but it sounds like you are trying to control the view of an activity from outside of the Activity. This sounds hacky to me. I'd let each Activity manage its own UI.
A good way of doing decoupled communication between objects is the observer pattern, aka an "event bus" or "event dispatcher" system. An example of how to do this on Android is here: http://www.therealjoshua.com/2012/03/event-dispatching-sending-messages/
Basically, the code that's generating the error should dispatch a message. The Activity can listen for this message, and then update its own UI as needed.
EDIT
Thanks for the clarification. I think the observer pattern can still help here. Basically, your data processing threads shouldn't know anything about the UI. Just have them post an event for the error, optionally with additional info on the error. If you want, your event dispatcher class could even make the actual event calls on the UI thread itself using a Runnable like you showed, so that the listener can always assume that they are being called on the UI thread, if this is important for your design. This way you don't have to pass the context to the thread at all (at least not for purposes of updating the UI) - let the worker thread just be responsible for the work, and the activity can be responsible for its own UI.
Another option you could use is an android Handler (see http://developer.android.com/reference/android/os/Handler.html)
In this case, the work is still done in another thread, but the Activity receives a handleMessage callback from the thread at the appropriate time. I haven't used this myself but from the documentation it looks like it can get the job done for what you need.
In either case IMO, the responsibility for updating the UI should lie with the Activity, not the worker thread.
I want to show up pop up window after an activity has been launched. It is just like after a few seconds delay pop up should come. How can I implement that?Any ideas or examples?? If so I will be helpful ..Thanks in advance.
Many ways to do so.
If you have a list of Activities where you want to show the POP-up, you can uses two ways:
Create a service which actively checks for the foreground [Top most activities] in the stack and if the activity on which you want to show the pop-up, just send the broadcast to show the pop-up.
Create a Class which extends a Asynctask class, which waits for Xsecs in doinbackground and shows a pop-up over onpostexecute, Just call the execute of the Asynctask class while oncreate ends if you want to show only one time.
Asynctask class will be the best to use in such scenario. By this you can re-use this asynctask class every where in the project.
new Handler().postDelayed(new Runnable(){ #Override
public void run() {
// This method will be executed once the timer is over
//call your toast here.
//TIME_OUT is no of milliseconds you want to wait before Toast is popped.
} },TIME_OUT);
Hope this helps.
Okay, I am using pro android 3 book as reference and implemented modal dialog box exactly the way stated in the book. However, I am having hard time getting string from textedit entered in the dialog box to main (calling) thread which calls the dialog box.
FIrst, book tells to implement independent class for implementing the android.content.DialogInterface.OnClickListener. In this case the text will not received by main thread as process is asynchronous which is what book tells.
And it tells that the solution is the calling activity will directly implement the callback in android.content.DialogInterface.OnClickListener which will solve the issue of premature update of string in the main thread. That is main thread will receive the return string only after dialog box is closed.
So I re-architected my application but still it is not working. The main thread is returning the string as 'NULL immediately before the submit button is clicked. Can anyone explain what else I have to do? Thanks
I am using Handler for communicating between Current Activity and a subclass of Application.
Subclass is having a thread which processes web service calls.
Subclass may also have a ProgressDialog instance.
I want to show ProgressDialog when http call is starting and dismiss dialog when call is finished.
For this to happen, I need to access Activity from Handler. And then assign activity to Dialog using setOwnerActivity.
Is this possible? I tried and cant not get activity from Handler. The max Handler can give is Thread which sent message.
Have you tried sending the Instance of the Activity using a Message with parameter msg.obj?
Btw, I think you should be using a AsyncTask instead of riddling it with complicated code.
The application class is unaware of what activity is running.
The only thing that can be done is to let application class know about activity is by a setter method which is not recommended as it may lead to memory problems.
I have a comment activity that loads a Thread and sends some data to a server; the activity is immediately finished once the submit button is pressed.
The user is then free to do other things in my application.
When the server responds an AlertDialog is shown.
The problem is that since the initial context has been destroyed, my application crashes.
I tried getApplicationContext() but still get an exception.
Put your network stuff in a Service, then show a status bar notification instead of a dialog.
Take a look at AsyncTask
From JavaDocs:
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.