您可以幫助我在創建數據庫期間更改一段代碼以顯示progresDialog或一些信息。我試圖用Thread來做到這一點,但沒有成功。當我將大部分代碼放入線程時,出現錯誤,在創建數據庫之前只設置了db.createDataBase()「text」。progressDialog將創建數據庫
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myCalendar = new MyCalendar();
menu = (TextView) findViewById(R.id.poleMenu);
text = (TextView) findViewById(R.id.glownePoleTekstowe);
menu.setText(kalendarz.setCurrentDateOnView());
value = menu.getText().toString();
db = new DatabaseHandler(this);
try {
// separate class to load database
// MOST IMPORTANT
db.createDataBase();
} catch (IOException ioe) {
throw new Error("nie można utworzyć bazy danych");
}
dane = db.getDataFromDate(value);
db.close();
try {
log = dane.getTekst();
}catch(Exception e) {System.out.println(e);}
text.setText(log);
}
更新,與線程和處理程序:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kalendarz = new Kalendarz();
menu = (TextView) findViewById(R.id.poleMenu);
text = (TextView) findViewById(R.id.glownePoleTekstowe);
menu.setText(kalendarz.setCurrentDateOnView());
value = menu.getText().toString();
db = new DatabaseHandler(this);
// thread
ladujDane();
dane = db.getDaneFromDate(value);
db.close();
try {
log = dane.getTekst();
}catch(Exception e) {System.out.println(e);}
text.setText(log);
}
// --------------------------- ---------------
public void ladujDane() {
mLoadDBHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
progressDialog.dismiss();
}
};
progressDialog = ProgressDialog.show(
this,
"Ładowanie danych", "Proszę chwilkę poczekać",
true,
false);
Thread t = new Thread(new LoadDBThread());
t.start();
}
// -------------------------- --------------
private class LoadDBThread implements Runnable
{
public void run()
{
try {
db.createDataBase();
} catch (IOException ioe) {
throw new Error("nie można utworzyć bazy danych");
}
mLoadDBHandler.sendEmptyMessage(0);
}
}
什麼樣的錯誤:
從你的線程創建DB你叫呢?你在不工作的代碼中使用AsyncTask嗎? – piotrpo
致命異常:Thread-8 android.view.ViewRoot $ CalledFromWrongThreadException:只有創建視圖層次結構的原始線程可以觸及其視圖。 ///我使用線程 – Mirek