我正面臨着我的異步任務的問題。我有一些正常的操作要在後臺完成,並在完成後查看結果,但UI凍結,儘管我的代碼在doinbackground塊內。請幫幫我!異步任務凍結UI
下面是我的代碼。
class DownloadFileFromURL extends AsyncTask<String, Void, String> {
/**
* Before starting background thread Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(Interface.this, null, "Loading...", true);
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
//
// Toast.makeText(getApplicationContext(), "Executing",
// 3000).show();
runOnUiThread(new Runnable() {
public void run() {
Calculate();
}
});
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
}
/**
* After completing background task Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
pd.dismiss();
}
}
private void Calculate()
{
curs = mDb.query(MyDbHelper.TABLE_NAME, columns, MyDbHelper.COL_Common
+ "=" + "?", new String[] { From[xxxto] + From[xxxfrom] },
null, null, null);
cursD = mDb.query(MyDbHelper.TABLE_NAME, columns, MyDbHelper.COL_Common
+ "=" + "?", new String[] { From[xxxfrom] + From[xxxto] },
null, null, null);
curs.moveToFirst();
cursD.moveToFirst();
double selection = curs.getDouble(curs
.getColumnIndex(MyDbHelper.COL_Currone));
double selection2 = cursD.getDouble(cursD
.getColumnIndex(MyDbHelper.COL_Currone));
Long myNum = Long.parseLong(valval.getText().toString().trim());
double myNum3 = Double.parseDouble(new DecimalFormat("#.######")
.format(myNum * selection2));
valval2.setText(String.valueOf(myNum3));
/*
Cursor B = mDb
.query(MyDbHelper.TABLE_NAME, columns, MyDbHelper.COL_CurrFavor
+ "=? And " + MyDbHelper.COL_Currsecond + "=?",
new String[] { "YES", "EUR" }, null, null, null);
*/
Cursor B = mDb.rawQuery("select * from "
+ MyDbHelper.TABLE_NAME + " where " + MyDbHelper.COL_CurrFavor + " = ? AND "
+ MyDbHelper.COL_Currsecond + " = ?", new String[] { "YES", "EUR" });
for (int s = 0; s < 4 - 1; s++)
{
B.moveToPosition(s);
String ZVZV = B.getString(0);
int BSBS = B.getInt(9);
Cursor curcur = mDb.query(MyDbHelper.TABLE_NAME, columns,
MyDbHelper.COL_Common + "=" + "?",
new String[] { From[xxxfrom] + From[BSBS - 1] }, null,
null, null);
curcur.moveToFirst();
double calcal = curcur.getDouble(6);
ContentValues args = new ContentValues();
double formattedNumber = Double.parseDouble(new DecimalFormat(
"#.######").format(myNum * calcal));
args.put(MyDbHelper.COL_Currsum, formattedNumber);
mDb.update(MyDbHelper.TABLE_NAME, args, "_id =" + ZVZV, null);
}
cursm.requery();
}
這裏是在logcat的錯誤:
4月12日至20日:41:38.469:E/AndroidRuntime(440):android.view.ViewRoot $ CalledFromWrongThreadException:由僅引起的創建視圖層次結構的原始線程可以觸及其視圖。
另外我運行它使用:new DownloadFileFromURL2()。execute(「」);
感謝您提供寶貴的信息。我試圖刪除runnable,但是由於附加到主要問題,我得到了錯誤。 –
因爲您還沒有從'Calculate()'方法中刪除'UI'東西('Toasts'等) – codeMagic
OK我會嘗試修改代碼,這取決於新的方法,並刪除doInbackground之外的不必要的UI內容。將更新你有點:)謝謝你的幫助! –