我需要在活动开始时从一个数据库中检索一些大数据。为了防止用户冻结窗口,我决定在处理数据时运行ProgressDialog。
从OnCreate我调用我的initDb类:
new initDb()。execute();
然后为了做到这一点,我在我的活动课程中有一个课程:
public class initDb extends AsyncTask<Void, Void, Void> {
ProgressDialog mDialog = new ProgressDialog(ClientsReg.this);
@Override
protected void onPreExecute() {
mDialog.setMessage("Please wait...");
mDialog.show();
}
@Override
protected Void doInBackground(Void... voids) {
opendb();
listCities();
return null;
}
@Override
protected void onPostExecute(Void unused) {
// Pass the result data back to the main activity
mDialog.dismiss();
}
}
设置适配器时发生了真正的问题:
private void listCities() {
mRedrawHandler.sleep(100000);
c = db.executeSQL("SELECT * FROM RegDB WHERE Reg_Type = 1 AND cad_uzkow = 0 ORDER BY _id DESC");
//add some list items
ArrayList<String> finalList = new ArrayList<String>();
c.moveToFirst();
while (!c.isAfterLast()){
finalList.add(c.getString(0) + ")"+ c.getString(5));
c.moveToNext();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.row, R.id.itemShow, finalList);
sp.setAdapter(adapter);
}
它总是碰巧在sp.setAdapter(适配器)上崩溃;
有什么想法吗?
谢谢!
答案 0 :(得分:0)
你应该致电:
sp.setAdapter(adapter);
在主UI线程中。例如在onPostExecute()
函数中。请记住,只能从主线程访问视图(例如ListView
)。
答案 1 :(得分:0)
您无法从创建UI的线程以外的其他线程访问UI。所以在AsyncTask中,你不能为此目的使用doInBackground()。
答案 2 :(得分:0)
尝试将finalList作为initDb类的属性,这样就可以在doInBackground方法上填充它,然后在onPostExecute上使用它,如下所示:
public class initDb extends AsyncTask<Void, Void, Void> {
ProgressDialog mDialog = new ProgressDialog(ClientsReg.this);
ArrayList<String> finalList;
@Override
protected void onPreExecute() {
mDialog.setMessage("Please wait...");
mDialog.show();
}
@Override
protected Void doInBackground(Void... voids) {
opendb();
listCities();
return null;
}
@Override
protected void onPostExecute(Void unused) {
// Pass the result data back to the main activity
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.row, R.id.itemShow, finalList);
sp.setAdapter(adapter);
mDialog.dismiss();
}
private void listCities() {
mRedrawHandler.sleep(100000);
c = db.executeSQL("SELECT * FROM RegDB WHERE Reg_Type = 1 AND cad_uzkow = 0 ORDER BY _id DESC");
//add some list items
finalList = new ArrayList<String>();
c.moveToFirst();
while (!c.isAfterLast()){
finalList.add(c.getString(0) + ")"+ c.getString(5));
c.moveToNext();
}
}