2016-11-05 39 views
0

我有一個FullRest API,它返回一個StatusCode,並且我成功了,問題是無法從AsyncTask調用進度對話框,我只想「顯示」用戶發生了什麼,if(statusCode == 201) ..成功發佈,至今:如何在AsyncTask中創建進度對話框?

PostBaseClass ..

public class PostBase { 

private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); 
private String Url="http://192.168.0.101:3000/"; 

OkHttpClient client = new OkHttpClient(); 

int POST(final PostModel model) throws IOException{ 
    Gson gson = new Gson(); 
    String modelJson = gson.toJson(model); 

    RequestBody body = RequestBody.create(JSON,modelJson); 
    Request request = new Request.Builder() 
      .url(Url + "api/gone/POST") 
      .post(body) 
      .build(); 
    Response response = client.newCall(request).execute(); 
    return response.code(); 
} 

MainActivity ..

public void MakePost(final PostModel postModel){ 
    new AsyncTask<Void,Void,Void>(){ 
     @Override 
     protected Void doInBackground(Void... params) { 
      try { 
       PostBase postBase = new PostBase(); 
       statusCode = postBase.POST(postModel); 
       if(statusCode == 201){ 
        //TODO 
       }else { 
        //TODO 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 

      } 
      return null; 
     } 
    }.execute(); 
} 

回答

4

https://developer.android.com/reference/android/os/AsyncTask.html

onPreExecuteonPostExecute UI線程,同時,因爲它運行在後臺線程不能更新從doInBackground UI上運行

onPreExecute所以顯示對話框,並在doInBackgroundonPostExecute

返回駁回對話一定的價值,做什麼根據返回的值在onPostExecute中必要。

如果你想顯示上傳進度,你可以做,使用onProgressUpdate

new AsyncTask<Void,Void,String>(){ 

    @Override 
    protected void onPreExecute() 
    { 
     super.onPreExecute() 
     // runs on the ui thread 
     // show dialog 
    } 
    @Override 
    protected String doInBackground(Void... params) { 
     try { 
      PostBase postBase = new PostBase(); 
      statusCode = postBase.POST(postModel); 
      if(statusCode == 201){ 
       return "successful"; 
      }else { 
       return "notsuccessful" 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 

     } 
     return "something"; 
    } 

    @Override 
    protected void onPostExecute(String result) 
    { 
     super.onPostExecute(); 
     // dismiss dialog 
     if(result.equals("successful") 
     { 
     // do something on successful 
     // runs on the ui thread so do update ui 
     } 
    } 
}.execute(); 

除的AsyncTask代碼,它看起來像你正在使用Retrofit。您也可以使用相同的方式進行異步調用。

+0

太謝謝你了! –

2

將您ProgressDialog在onPreExecute,下面的示例代碼:

private ProgressDialog pd; 

@Override 
protected void onPreExecute(){ 
    super.onPreExecute(); 
     pd = new ProgressDialog(yourContext); 
     pd.setMessage("Loading..."); 
     pd.show();  
} 

@Override 
protected void onPostExecute(String result){ 
    super.onPostExecute(result); 
     pd.dismiss(); 
} 

感謝

+0

謝謝你:) –

+0

歡迎親愛的! – Androider