Timer Thread To Refresh The Fragment On Android
I have implemented a thread in android which refresh the fragment (some text list ) for every 1 second . its giving the runtime error while calling the fragment method at thread ,
Solution 1:
I think you have to do the refreshing in
yourActivity.runOnUiThread(new Runnable() {
publicvoidrun() { /* here */ });
Or via a Handler
, or via a post()
or in an AsyncTask
's onProgress()
Solution 2:
You are having errors because you are doing UI operations in a not UI thread. If you change the code into something like this, you will not have that error:
publicclassRunThreadExtendedextendsActivityimplementsRunnable
{
publicvoidrun() {
while(true)
{ try {
Thread.sleep(1000);
AndroidListFragmentActivity.strup++;
RunThreadExtended.this.runOnUiThread(newRunnable() { //Use the runOnUIThread method to do your UI hanlding in the UI Threadpublicvoidrun() {
MyListFragment1fragmentB= (MyListFragment1)getFragmentManager().findFragmentById(R.id.fragment1);
fragmentB.updatefrag();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}}}
Solution 3:
You can't update the UI on any thread except for the UI thread. If you want to update the thread you can use a handler that you send a message to every second (handlers handle all messages on the main UI thread).
See
Solution 4:
You could also broadcast an Intent (context.sendBroadcast(intent)) in a thread and receive it in your Activity: Broadcast Receiver
Solution 5:
maybe you can do all the work inside a fragment. here are the steps.
- define the Handler and Runnable in the fragment.
- create the Handler and Runnable in the onCreate() and onAttach()
- post the Runnable job in the Handler in onStart().
- remove the Runnable job out of the Handler in onStop().
below are the code snippet.
publicclassJobDetailFragment {
privateHandler m_Handler;
privateRunnable m_Runnable;
@OverridepublicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
m_Runnable = newRunnable() {
@Overridepublicvoidrun() {
updateJobStatus();
}
};
}
@OverridepublicvoidonAttach(Activity activity) {
super.onAttach(activity);
m_Handler = newHandler();
}
@OverridepublicvoidonStart() {
super.onStart();
if (m_Handler != null) {
m_Handler.postDelayed(m_Runnable, PrinterOnUIConstants.PRINT_JOB_AUTO_UPDATE_INTERVAL);
};
}
@OverridepublicvoidonStop() {
super.onStop();
// cancel the potential enqueued callback.if (m_Handler != null) {
m_Handler.removeCallbacks(m_Runnable);
}
}
Post a Comment for "Timer Thread To Refresh The Fragment On Android"