Reputation: 81
Hi i have this code to modify a text view but it keeps telling me : Only the original thread that created a view hierarchy can touch its views. here is my code :
public void Simulation()
{
ambientTemp = 20;
engTemp = 20;
mileage = 123456;
fuel = 100;
thread = new Thread()
{
menu1_Fragment f1 = new menu1_Fragment();
menu2_Fragment f2 = new menu2_Fragment();
menu3_Fragment f3 = new menu3_Fragment();
public void run()
{
for (int i=0; i<l; i++)
{
try {
Thread.sleep(99);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
speed = SPEED[i];
revs = ENGSPEED[i];
System.out.println(speed);
System.out.println(revs);
fuel -= 1;
System.out.println(fuel);
engTemp += 0.5;
System.out.println(engTemp);
mileage += 1;
System.out.println(mileage);
...
View item2 = findViewById(R.id.milage);
// f1.setMileage(item2,mileage);
View item3 = findViewById(R.id.ambienttemp);
f1.setAmbientTemp(item3,ambientTemp);
View item4 = findViewById(R.id.gear);
f1.setGear(item4,gear);
transaction.replace(R.id.container, f1);
transaction.commit();
}
f1.setMileage(item2,mileage); this one is causing the probleme ... how can i fix it please
Upvotes: 0
Views: 56
Reputation: 450
put all your codes related to a view inside a ui thread
runOnUiThread(new Runnable() {
@Override
public void run() {
View item2 = findViewById(R.id.milage);
// f1.setMileage(item2,mileage);
View item3 = findViewById(R.id.ambienttemp);
f1.setAmbientTemp(item3,ambientTemp);
View item4 = findViewById(R.id.gear);
f1.setGear(item4,gear);
transaction.replace(R.id.container, f1);
transaction.commit();
}
});
Your application must create other threads and put long running work on non-UI threads. There are options on how to accomplish the creation of alternate threads. You can create and start your own java.lang.Thread. You can create and start an AsyncTask - Android’s own thread simplification mechanism. The non-UI thread then handles long running processing – like downloading a file – while the UI thread sticks to displaying the UI and reacting to user events. Life seems good again.
However, there is a problem in paradise. Unfortunately, the user interface (UI) cannot be updated by non-UI threads. For example, after successfully downloading a file, a separate (non-UI) thread can’t show an AlertDialog, update a TextView widget, otherwise make a UI change to indicate the file has been successfully downloaded. If you attempt to update the UI from a non-UI thread, the application will compile, but you get a CalledFromWrongThreadException thrown from the point your non-UI thread attempts to make the UI change. As the exception message will inform you, “Only the original thread that created a view hierarchy can touch its views.”
for reference, click this link http://www.intertech.com/Blog/android-non-ui-to-ui-thread-communications-part-1-of-5/
Upvotes: 2