我有一个线程,它在从txt文件中获取数据后将数据更新到SQLite DB中,我想显示一个对话框,其中相应的进度会更新。
以下代码正常工作,即使runOnUiThread也适用于dismiss,但Progress不是更新。
Thread thread = new Thread(){
@Override
public void run() {
Log.d("THREAD", "in run");
// TODO Auto-generated method stub
try {
Log.d("DATABASE", "Creating Database");
SQLiteDatabase db = openOrCreateDatabase("WordDatabase", MODE_PRIVATE, null);
Log.d("DATABASE", "Checking table exist");
Cursor tableName = db.rawQuery("SELECT DISTINCT tbl_name FROM sqlite_master WHERE tbl_name='Words'",null);
if(tableName.getCount() < 1){
Log.d("DATABASE", "Creating Table");
db.execSQL("CREATE TABLE IF NOT EXISTS Words (Word TEXT);");
ContentValues cv = new ContentValues();
float totalWords = 5000;// 144895;
float wordsSelected = 0;
Log.d("CONTENT", "Entering Values");
Scanner scanner = new Scanner(getApplicationContext().getAssets().open("english.txt"));
while(scanner.hasNext()){
int i=0;
while(scanner.hasNext() && i<500 ){
cv.put("Word", scanner.next());
db.insert("Words", null, cv);
i++;
wordsSelected++;
final float percent = (wordsSelected/totalWords)*100;
Log.d("PROGRESS", Float.toString((int)percent));
runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.setProgress((int) percent);
if(percent == 100) dialog.dismiss();
}
});
}
cv.clear();
Log.d("CONTENT", "inserting");
}
Log.d("CONTENT", "Completed");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
};
thread.start();
答案 0 :(得分:1)
runOnUiThread在这里不起作用,您应该使用Handler
。如果你定义了thread
。
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int percent = msg.what;
dialog.setProgress((int) percent);
if (percent == 100) dialog.dismiss();
}
};
现在,thread
您可以拨打handler
:
// ...
final float percent = (wordsSelected/totalWords) * 100;
Log.d("PROGRESS", Float.toString((int) percent));
handler.sendEmptyMessage((int) percent));
// ...