Update Ui From Another Thread In Android
i want to change UI in android. my main class make a second class then second class call a method of main class.method in main class should update UI but program crash in runtime.
Solution 1:
You can't call UI methods from threads other than the main thread. You should use Activity#runOnUiThread() method.
publicclassFileObserverActivityextendsActivity
{
/** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("new world");
MyFileObserver myFileObserver = newMyFileObserver("/sdcard/", this);
myFileObserver.startWatching();
}
String mySTR = "";
TextView tv ;
publicvoidevent(String absolutePath,String path,int event)
{
runOnUiThread(action);
}
privateRunnable action = newRunnable() {
@Overridepublicvoidrun() {
mySTR = absolutePath+path+"\t"+event;
tv.setText(mySTR);
}
};
}
publicclassMyFileObserverextendsFileObserver
{
publicString absolutePath;
FileObserverActivity fileobserveractivity;
publicMyFileObserver(String path,FileObserverActivity foa)
{
super(path, FileObserver.ALL_EVENTS);
absolutePath = path;
fileobserveractivity = foa;
}
@OverridepublicvoidonEvent(int event, String path)
{
if (path == null)
{
return;
}
elseif(event!=0)
{
fileobserveractivity.event(absolutePath, path, event);
}
else
{
return;
}
}
}
Solution 2:
Try as follows
publicclassFileObserverActivityextendsActivity
{
/** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("new world");
MyFileObserver myFileObserver = newMyFileObserver("/sdcard/", this);
myFileObserver.startWatching();
registerReceiver(onBroadcast,newIntentFilter("abcd"));
}
String mySTR = "";
TextView tv ;
publicvoidevent(String absolutePath,String path,int event)
{
mySTR = absolutePath+path+"\t"+event;
tv.setText(mySTR); // program crash here!
}
@OverrideprotectedvoidonDestroy() {
super.onDestroy();
unregisterReceiver(onBroadcast);
}
private final BroadcastReceiver onBroadcast = newBroadcastReceiver() {
@OverridepublicvoidonReceive(Context ctxt, Intent i) {
// do stuff to the UIevent(absolutePath, path, event);
}
};
}
publicclassMyFileObserverextendsFileObserver
{
publicString absolutePath;
FileObserverActivity fileobserveractivity;
publicMyFileObserver(String path,FileObserverActivity foa)
{
super(path, FileObserver.ALL_EVENTS);
absolutePath = path;
fileobserveractivity = foa;
}
@OverridepublicvoidonEvent(int event, String path)
{
if (path == null)
{
return;
}
elseif(event!=0)
{
context.sendBroadcast(newIntent("abcd"));
//fileobserveractivity.event(absolutePath, path, event);
}
else
{
return;
}
}
}
Post a Comment for "Update Ui From Another Thread In Android"