簡體   English   中英

Android等待進度條無法在未調用Looper.prepare()錯誤的線程內創建處理程序

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

在我的android應用程序中,我將一些數據從服務器數據庫復制到本地數據庫,這可能需要15分鍾以上的時間。 對於較慢的連接,可能會超過該值。 所以我想顯示一個等待進度條。

該代碼發布在下面。

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();
       }

   });

當我運行我的應用程序時,進度條僅顯示幾秒鍾,並且執行了Catch塊,顯示logcat錯誤為

Logcat:

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

有人可以解釋我的代碼中的錯誤是什么以及如何解決它

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

問題是由上面的代碼引起的,此方法將更改UI,您不能在非UI線程中更新UI。 因此,您需要從主ui線程調用它。

由於這是一項耗時的工作,因此我強烈建議您在Android中使用AsyncTask

但是,如果您只想對現有代碼進行一些更改,請嘗試使用

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

或處理程序,您可以查看Android中處理程序的工作方式 一個基本的例子:

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();
}

而不是創建新的線程,而是創建一個HandlerThread- http://developer.android.com/reference/android/os/HandlerThread.html

只需將“ new Thread()”替換為“ new HandlerThread(“ any string”)“,它就可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM