2016-02-07 41 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 
      } 
     }); 
    }