我已经阅读了一些相关的问题,但是他们都建议我使用我正在使用的处理程序和线程,但是在运行此代码时仍然会出现黑屏,进度条无法看到移动并且几秒后屏幕变黑了。然而,过了一会儿,这个过程就完成了。
代码:
public void onRunButtonClicked(View view) throws IOException
{
// prepare for a progress bar dialog
progressBarStatus = 0;
progressBar = new ProgressDialog(view.getContext());
progressBar.setCancelable(true);
progressBar.setMessage("Updating...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(97);
progressBar.show();
// bulk insert books
bulkInsertBooks(this.getApplicationContext());
}
private void bulkInsertBooks(final Context context) throws IOException
{
// setup progressbar
progressBar.setMax(5000);
new Thread(new Runnable()
{
public void run()
{
// delete existing rows
db.execSQL("DELETE FROM Book");
// load csv from assets
InputStream is = null;
try
{
is = context.getAssets().open("books.dat");
}
catch (IOException e)
{
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// now insert into db
String sql = "INSERT INTO Book VALUES (?,?,?,?,?,?);";
SQLiteStatement statement = db.compileStatement(sql);
db.beginTransaction();
String line;
try
{
while ((line = reader.readLine()) != null)
{
String[] RowData = line.split("\\|");
statement.clearBindings();
statement.bindString(1, RowData[0]);
statement.bindString(2, RowData[1]);
statement.bindString(3, RowData[2]);
statement.bindString(4, RowData[3]);
statement.bindString(5, RowData[4]);
statement.bindString(6, RowData[5]);
statement.execute();
// Update the progress bar in every iteration
progressBarHandler.post(new Runnable()
{
public void run()
{
progressBar.setProgress(progressBarStatus++);
}
});
}
}
catch (IOException e)
{
e.printStackTrace();
}
// finish
db.setTransactionSuccessful();
db.endTransaction();
if (is != null)
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}).start();
}