Only the original thread that created a view hierarchy can touch its views. The reason is:The related views and controls in Android are NOT thread-safe and must be processed separately. I use handler to solve the problem.
Handler official description:
A handler allows you to send and ProcessMessage
And
Runnable objects associated with a thread'sMessageQueue
.
Each handler instance is associated with a single thread and that thread's message queue. when you create a new handler, it is bound to the thread/message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables
To that message queue and execute them as they come out of the Message Queue
Handler usage:
1. To schedule messages and runnables to be executed
As some point in the future;
Schedule messages and runnables to be executed at a certain time point in the future.
2. To enqueue an action to be passed med on a different
Thread than your own.
Bind the action to the queue for execution in a different thread. That is, inter-thread communication can be realized. For example, when you create a sub-thread, you can obtain the handler object created in the parent thread in your sub-thread to send messages to the Message Queue of the parent thread. Because Android requires updating the interface in the UI thread, you can update the interface in other threads through this method.
My usage is,
Declare a member variable: Private
Handler handler = NULL;
In the oncreate () method:
Handler = new handler ()
{
@ Override
Public void handlemessage (Message MSG)
{
If (msg. arg1 = 1)
{
Adapter = new movielistadapter (listactivity. This, movieinfos );
Gridview. setadapter (adapter );
}
}
};
Set up another thread to complete database operations and then update the UI.
New thread (New runnable (){
@ Override
Public void run ()
{
Message MSG = handler. obtainmessage ();
Movieinfos = movieutils. getmovieinfos (listactivity. This );
MSG. arg1 = 1;
Handler. sendmessage (MSG );
}
}). Start ();