Android - 显示进度条时出现 'Cant create handler' 错误

标签 android

我试图在我的应用程序中显示进度条,但遇到线程问题。这是我用来执行此操作的代码:

package com.integrated.mpr;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class Progess extends Activity {

   static String[] display = new String[Choose.n];
   private static final int Progress = 0;

   ProgressBar bar;
   TextView label;
   Handler handler = new Handler();

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      // TODO Auto-generated method stub
      super.onCreate(savedInstanceState);
      setContentView(R.layout.progress);

      bar = (ProgressBar) findViewById(R.id.progBar);

      new Thread(new Runnable() {

         int i = 0;
         int progressStatus = 0;

         public void run() {
            while (progressStatus < 100) {
               progressStatus += doWork();
               try {
                  Thread.sleep(500);
               } catch (InterruptedException e) {
                  e.printStackTrace();
               }

               // Update the progress bar
               handler.post(new Runnable() {
                  public void run() {
                     bar.setProgress(progressStatus);
                     i++;
                  }
               });
            }
         }

         private int doWork() {
            display = new Logic().finaldata();
            return i * 3;
         }

      }).start();

      Intent openList = new Intent("com.integrated.mpr.SENSITIVELIST");
      startActivity(openList);
   }
}

我收到以下 logcat 消息:

05-30 12:38:00.082: E/AndroidRuntime(17332): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

请帮助我,我是线程新手。

最佳答案

与其以这种方式实现线程,我建议您实现 AsyncTask 被称为 Painless Threading在 Android 中。

  1. onPreExecute()中显示进度条
  2. doInBackground()
  3. 中执行后台任务
  4. 关闭 onPostExecute() 中的进度条
  5. onProgressUpdate() 内更新进度条

关于Android - 显示进度条时出现 'Cant create handler' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10811777/

相关文章:

android - 在 Android 上的 Realm 中,我收到 "Field already exists"错误,但它是全新安装的吗?

java - Android模态对话框堆叠

Android Google Maps 获取边界坐标

android - 移动设备上的列表上传应用程序

java - 如何在使用字节数组更改后将图像字节数组转换为位图

android - 每次我在 andriod 中单击不同的图像时,如何更改 AlertDialog 中的消息?

java - 错误 : This fragment should provide a default constructor (a public constructor with no arguments)

android - 将私钥嵌入到 Android 中的应用程序代码中

Eclipse中的Android配置问题

java - 从两次选择器中获取总小时数