2016-02-07 43 views
1

我想補充progressdialog到okhttp(異步,不是的AsyncTask)的Android okhttp異步progressdialog

,但我得到這個錯誤:

Error: Can't create handler inside thread that has not called Looper.prepare()

如何將它固定在一個適當的方式?我想確保這是做到這一點的最佳方式。

client.newCall(request).enqueue(new Callback() { 
     @Override 
     public void onFailure(Call call, IOException e) { 
      Log.d("TAG_response", " brak neta lub polaczenia z serwerem "); 
      e.printStackTrace(); 
     } 

     @Override 
     public void onResponse(Call call, Response response) throws IOException { 
       progress = ProgressDialog.show(SignUp.this, "dialog title", 
        "dialog message", true); 
      try { 
       Log.d("TAGx", response.body().string()); 
       if (response.isSuccessful()) { 
        Headers responseHeaders = response.headers(); 
        for (int i = 0, size = responseHeaders.size(); i < size; i++) { 
         //System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); 
         Log.d("TAG2", responseHeaders.name(i)); 
         Log.d("TAG3", responseHeaders.value(i)); 

        } 
        Log.d("TAG", response.body().string()); 
        progress.dismiss(); 
        main_activity(); 
       } 
       else{ 
        progress.dismiss(); 

        alertUserAboutError(); 
       } 
      } 
      catch (IOException e){ 
       Log.d("TAG", "error"); 
      } 

     } 

    }); 
+2

您應該用於顯示對話框排隊請求之前,移動代碼,並在onFailure處和onResponse解僱。 – thetonrifles

回答

2

OkHttp在與http調用相同的後臺線程上運行onResponse方法。因爲你正在做一個異步調用,這意味着它不會是Android主線程。

若要從onResponse你可以使用一個處理程序和可運行在主線程代碼:

client.newCall(request).enqueue(new Callback() { 

    Handler handler = new Handler(SignUp.this.getMainLooper()); 

    @Override 
    public void onFailure(Call call, IOException e) { 
     //... 
    } 

    @Override 
    public void onResponse(Call call, Response response) throws IOException { 

     handler.post(new Runnable() { 
      @Override 
      public void run() { 

       // whatever you want to do on the main thread 
      } 
     }); 
    }