Asynctask-
for Activity-
for Fragment-
public class ConfirmKitAsync extends AsyncTask<String,String,String > { static MediaType JSON = MediaType.parse("application/json; charset=utf-8"); String url; RestUserId restUserId; ProgressDialog progressDialog; IConfirmKitListener responseListener; Context context; // String path = null; public interface IConfirmKitListener { public void callbackConfirmKit(String response); } public void setConfirmKitListener (IConfirmKitListener listener){ this.responseListener = listener; } public ConfirmKitAsync(Context context, String url, RestUserId restUserId) { this.context = context; this.url = url; this.restUserId = restUserId; // path = Uri.parse(url).getPath();
// responseListener = (IConfirmKitListener) context;
} @Override
protected void onPreExecute() { super.onPreExecute(); progressDialog = new ProgressDialog(context); progressDialog.setMessage("Loading..."); progressDialog.setCanceledOnTouchOutside(false); progressDialog.setCancelable(false); progressDialog.show(); } @Override
protected String doInBackground(String... strings) { String responseString = null; if (isCancelled()) { return null; } else { try { Request.Builder builder = new Request.Builder().url(url); RequestBody body = RequestBody.create(JSON, new Gson().toJson(restUserId)); builder.post(body); OkHttpClient client = CommonTask.getCommonOkHttpCient(); client.setConnectTimeout(2, TimeUnit.MINUTES); client.setReadTimeout(5, TimeUnit.MINUTES); Response response = client.newCall(builder.build()).execute(); responseString = response.body().string(); return responseString; } catch (SocketTimeoutException e) { } catch (Exception e) { e.printStackTrace(); } } return responseString; } @Override
protected void onPostExecute(String result) { if (result != null) { super.onPostExecute(result); try { responseListener.callbackConfirmKit(result); } catch (Exception e) { e.printStackTrace(); } } if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } } }
for Activity-
ConfirmKitAsync async= new ConfirmKitAsync (context, url, restUserId); async.execute();
for Fragment-
ConfirmKitAsync async= new ConfirmKitAsync(context, uri, restUserId); async.setConfirmKitListener(this); async.execute();
Callback-
@Override
public void callbackConfirmKit(String jsonStr) { try { if (jsonStr != null && jsonStr.length() > 0) { JSONObject jsonObj = new JSONObject(jsonStr); JSONObject jObj = jsonObj.getJSONObject("Data"); jsonArray = jObj.getJSONArray("RestWeapon"); for (int i = 0; i < jsonArray.length(); i++) {}}}catch (JSONException e){ e.getMessage(); } }
No comments:
Post a Comment