Reputation: 20132
I want to display letters using textview. and the letter should display in textview after some time interval.
i used following code....
String a="Apple";
String b="";
.......
.......
public void run() {
for (int i = 0; i < 5; i++) {
b=b+""+a.charAt(i);
mTextView.setText(b); //Problem here
Log.d("Letters",""+b);
try {
sleep(2000);
} catch (InterruptedException e) {}
}
Log cat Result:
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Any Solution?
Upvotes: 2
Views: 1245
Reputation: 74790
You can not change UI controls from other threads. Update your code in a next way:
public void run() {
for (int i = 0; i < 5; i++) {
b=b+""+a.charAt(i);
//one of the ways to update UI controls from non-UI thread.
runOnUiThread(new Runnable()
{
@Override
public void run()
{
mTextView.setText(b); //no problems here :)
}
});
Log.d("Letters",""+b);
try {
sleep(2000);
} catch (InterruptedException e) {}
}
}
Upvotes: 2
Reputation: 4024
You cannot update the textview in the thread since UI updation is not Thread safe.
use this
public void run() {
for (int i = 0; i < 5; i++) {
b=b+""+a.charAt(i);
Log.d("Letters",""+b);
try {
sleep(2000);
handler.post(updateMessgae)
} catch (InterruptedException e) {}
}
private final Runnable updateMessgae= new Runnable()
{
public void run()
{
try
{
Log.d("Letters",""+b);
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
private final Handler handler = new Handler();
Upvotes: 2