简体   繁体   English

Android等待进度条无法在未调用Looper.prepare()错误的线程内创建处理程序

[英]Android Waiting progress bar Can't create handler inside thread that has not called Looper.prepare() error

In my android application, I copy some data from server database to local database.It may take over 15 minutes. 在我的android应用程序中,我将一些数据从服务器数据库复制到本地数据库,这可能需要15分钟以上的时间。 For slower connections, it may be exceeded. 对于较慢的连接,可能会超过该值。 So I want to display a waiting progress bar. 所以我想显示一个等待进度条。

The code is posted below. 该代码发布在下面。

refresh.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
final ProgressDialog progressDialog = ProgressDialog.show(login.this, "", "Please wait...");
new Thread() {
public void run() {
try{
mySQLiteAdapter.openToWrite();
mySQLiteAdapter.deleteAll();
radapter.openToWrite();
radapter.deleteAll();
uadapter.openToWrite();
uadapter.deleteAll();
        try
            {
                 HttpClient httpclient = new DefaultHttpClient();
                 HttpPost httppost = new HttpPost("http://xxxxxxxxxxxxxxxxxxxxx");
                 HttpResponse response = httpclient.execute(httppost);
                 HttpEntity entity = response.getEntity();
                  is = entity.getContent();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
            }

            try {
                jObj = new JSONObject(json);
                contacts = jObj.getJSONArray("get");
                for(int i = 0; i < contacts.length(); i++){
                JSONObject c = contacts.getJSONObject(i);
                    if(!c.isNull("rname"))// || c.getString("rcode").equals(null))
                    {
                        rname = c.getString("rname");
                        rcode = c.getString("rcode");
                        radapter.insert(rcode, rname);
                    }
                    else
                    {
                        rname = "";
                        rcode = c.getString("rcode");
                        radapter.insert(rcode, rname);
                    }
                }
                Toast.makeText(getBaseContext(), " Ryot BackUp completed", Toast.LENGTH_SHORT).show();

            } catch (JSONException e) {
                Toast.makeText(getBaseContext(), "Error"+e.toString(), Toast.LENGTH_LONG).show();
            }
                   progressDialog.dismiss();
               }
            }.start();
            adapter.deleteAll();
            oadapter.deleteAll();
            e2.setText("Back Up completed");
        }
            catch (Exception e) {
               Log.e("tag", e.getMessage());
               }
                   progressDialog.dismiss();
               }
            }.start();
       }

   });

When I'm running my application, the progress bar is displayed only for few seconds and the Catch block is executed, showing logcat error as 当我运行我的应用程序时,进度条仅显示几秒钟,并且执行了Catch块,显示logcat错误为

Logcat: Logcat:

02-26 14:26:07.151: E/tag(301): Can't create handler inside thread that has not called Looper.prepare()

Can someone explain what is the mistake in my code and how to solve it 有人可以解释我的代码中的错误是什么以及如何解决它

Toast.makeText(getBaseContext(), " Ryot BackUp completed", Toast.LENGTH_SHORT).show();

The problem is caused by the above code, this method will change UI, you can't update UI in a non-ui thread. 问题是由上面的代码引起的,此方法将更改UI,您不能在非UI线程中更新UI。 So you need to call it from main ui thread. 因此,您需要从主ui线程调用它。

Since it is a time-consuming work, I highly recommend you to use AsyncTask in Android. 由于这是一项耗时的工作,因此我强烈建议您在Android中使用AsyncTask

But if you only want to make a little change in your existing code, try to use 但是,如果您只想对现有代码进行一些更改,请尝试使用

context.runOnUiThread(new Runnable() {
  public void run() {
    Toast.makeText(...).show();
  }
});

or handler, you can take a look at How Handler Work in Android . 或处理程序,您可以查看Android中处理程序的工作方式 A basic example: 一个基本的例子:

public Handler mHandler = new Handler() {

    public void handleMessage(Message msg) {
           //show toast here
    }
}

protected void startLongRunningOperation() {

    Thread t = new Thread() {
        public void run() {
            //do something here
            //update the result
            mHandler.postDelayed(mUpdateResults, 200);}
            mHandler.post(mUpdateResults);
        }
    };
    t.start();
}

Instead of creating a new Thread make a HandlerThread - http://developer.android.com/reference/android/os/HandlerThread.html 而不是创建新的线程,而是创建一个HandlerThread- http://developer.android.com/reference/android/os/HandlerThread.html

Just replace "new Thread()" with "new HandlerThread("any string")" and it should work. 只需将“ new Thread()”替换为“ new HandlerThread(“ any string”)“,它就可以工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android线程错误-无法在未调用Looper.prepare()的线程内创建处理程序 - Android thread error - Can't create handler inside thread that has not called Looper.prepare() 使用 Android 的线程错误“无法在尚未调用 Looper.Prepare 的线程内创建处理程序” - Threading error “Can't create handler inside thread that has not called Looper.Prepare” with Android Android Studio错误:无法在尚未调用Looper.prepare()的线程内创建处理程序 - Android Studio Error: Can't create handler inside thread that has not called Looper.prepare() Unity to Android插件错误:无法在未调用Looper.prepare()的线程内创建处理程序 - Unity to Android plugin error: Can't create handler inside thread that has not called Looper.prepare() Android处理程序:无法在尚未调用Looper.prepare()的线程内创建处理程序 - Android handler: Can't create handler inside thread that has not called Looper.prepare() 无法在未调用Looper.prepare()Android的线程内创建处理程序 - Can't create handler inside thread that has not called Looper.prepare() Android Android无法在未调用looper.prepare()的线程内创建处理程序 - Android can't create handler inside thread that has not called looper.prepare() Android AsyncTask [无法在未调用Looper.prepare()的线程内创建处理程序 - Android AsyncTask [Can't create handler inside thread that has not called Looper.prepare()] java.lang.RuntimeException:无法在未在Android中调用Looper.prepare()的线程内创建处理程序 - java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() in Android Android致命异常:无法在未调用Looper.prepare()的线程内创建处理程序 - Android fatal exception: Can't create handler inside thread that has not called Looper.prepare()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM