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.
what should i do?
my main class :
public class FileObserverActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("new world");
MyFileObserver myFileObserver = new MyFileObserver("/sdcard/", this);
myFileObserver.startWatching();
}
String mySTR = "";
TextView tv ;
public void event(String absolutePath,String path,int event)
{
mySTR = absolutePath+path+"\t"+event;
tv.setText(mySTR); // program crash here!
}
}
and my second class :
public class MyFileObserver extends FileObserver
{
public String absolutePath;
FileObserverActivity fileobserveractivity;
public MyFileObserver(String path,FileObserverActivity foa)
{
super(path, FileObserver.ALL_EVENTS);
absolutePath = path;
fileobserveractivity = foa;
}
@Override
public void onEvent(int event, String path)
{
if (path == null)
{
return;
}
else if(event!=0)
{
fileobserveractivity.event(absolutePath, path, event);
}
else
{
return;
}
}
}
You can't call UI methods from threads other than the main thread. You should use Activity#runOnUiThread() method.
Try as follows