This code is too add a timer on the code.. but i am having a problem with my code when it comes to the timer code... How will i improve the code for the timer inside the for loop of my code.. Hopefully you understand the my code.. and have improved my code.. Thanks!!!!
package com.thesis.americansignlanguage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class AlphabetCompareClass extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.alphabetcompare);
final String get;
Bundle gotWord = getIntent().getExtras();
get = gotWord.getString("key");
TextView Word = (TextView)findViewById(R.id.textView1);
final ImageView img = (ImageView)findViewById(R.id.image_alpha) ;
Word.setText(get);
for(int x = 0; x > gotWord.getString("key").length(); x++) {
final InputStream is;
Timer timer = new Timer();
TimerTask timertask = new TimerTask() {
@Override
public void run() {
try {
is = getResources().getAssets().open(get + ".png");
Bitmap bitmap = BitmapFactory.decodeStream(is);
img.setImageBitmap(bitmap);
} catch (IOException e) {
return;
}
}
};
}
};
}
TimerTask runs on a different thread. Ui can be updated only from ui thread.
This img.setImageBitmap(bitmap);
should be executed on the ui thread
Use runOnUiThread
. You can also use a Handler
. Also i do not understand the need for the for
loop.
runOnUiThread(new Runnable() {
@Override
public void run() {
img.setImageBitmap(bitmap);
}
});
Two problem found in current code:
First : Not using timer
instance to schedule timerTask
. do it as:
timer.schedule(timertask, 500, 3000);
Second : Updating UI from non- ui thread inside run
method of TimerTask
Use runOnUiThread or Handler for updating Ui from run method of TimerTask
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.