android - 异步任务卡住 UI

标签 android listview uiview android-asynctask cursor

我的异步任务遇到了问题。我有一些正常的操作要在后台完成并在完成后查看结果,但是 UI 卡住了,尽管我的代码在 doinbackground block 中。请帮助我!

下面是我的代码。

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 中的错误:

12-20 04:41:38.469: E/AndroidRuntime(440): Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

我还使用以下命令运行它:new DownloadFileFromURL2().execute("");

最佳答案

不要不要不要AsyncTask 中执行此操作

runOnUiThread(new Runnable() {
        public void run() {

AsyncTask 中的每个方法在 UI Thread 上运行除了 doInBackground() .在doInBackground()做你的工作(您的计算、网络操作等)然后从中得到结果并更新 UIonProgressUpdate()调用publishProgress()或者,如果后台工作完全完成,返回结果给onPostExecute()你可以在那里更新。

如果这不能解决您当前的问题,请发布您如何调用该任务...希望不要使用 .get() .

编辑

此外,您应该再次查看文档,您实际上并没有将任何内容传递给 doInBackground()但是一个空的String.execute()

new DownloadFileFromURL2().execute("");

所以你可以改变第一个 param Void 的声明

class DownloadFileFromURL extends AsyncTask<Void, Void, String> {

并且不传递任何东西

new DownloadFileFromURL2().execute();

除非您计划稍后更新。你也没有通过 onPostExecute()来自 doInBackground() 的任何东西与

return null;

所以你可以改变params它需要。所以现在我们有

class DownloadFileFromURL extends AsyncTask<Void, Void, Void> {

 @Override
protected void onPostExecute(Void result) {

然后你又得到了你的onProgressUpdate()没有 params在你的任务类声明中(第二个 param )

class DownloadFileFromURL extends AsyncTask<Void, Void, Void> {

应该是这样的

 protected void onProgressUpdate(Void... progress) {
    // setting progress percentage

}

当然,这些都取决于您计划传递给它们的内容,您需要传递一些内容来更新 UI从您的 Calculate() 获得结果后方法。

关于android - 异步任务卡住 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20694959/

相关文章:

java - 将 ListView 中的复选框状态保存到 ArrayList 中

swift - 动画视频 UIView 像 YouTube 应用程序一样全屏显示

android - Android上GC的日志

Android:需要记录麦克风输入

android - Facebook SDK 3.5 通过应用程序登录不起作用

iphone - 将 UIView 保留在 Circle Objective-C 中

ios - 可以拥有单例 UIView 子类吗?

android - 如何在 android 中使用内键排序检索 firebase 数据

listview - 从 Listview Control 复选框中获取通知代码

c# - Wpf Listview不显示数据