Asynctask example with new design
1) Async Task
1) Async Task
public class IglHttpGet extends AsyncTask<String, Integer, String> {
private IglHttpGetListener listener; public String url=null; public final String TAG="HTTP_GET - "; public IglHttpGet(IglHttpGetListener listener){ this.listener=listener; } //required methods protected void onPreExecute() { listener.preExecute(); } @Override protected void onProgressUpdate(Integer...values){ } @Override protected void onPostExecute(String response){ if(response!=null) this.listener.callback(response); else this.listener.connectionFailed(); } @Override protected String doInBackground(String... params) { url=params[0]; String responseJson=null; // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); org.apache.http.client.methods.HttpGet httpGet = new org.apache.http.client.methods.HttpGet(url); BufferedReader in = null; try { // Add your data // Execute HTTP Get Request HttpResponse response = httpclient.execute(httpGet); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); responseJson = sb.toString(); } catch (ClientProtocolException e) { Crashlytics.logException(e); } catch (IOException e) { Crashlytics.logException(e); } return responseJson; } } |
2) Listener
public interface IglHttpGetListener {
public void preExecute();
public void onProgress(int i);
public void callback(String response);
public void connectionFailed();
}
|
3.Profile Details function
private void profileData() {
String url = ;
IglHttpGetListener iglHttpGetListener = new IglHttpGetListener() {
@Override
public void preExecute() {
}
@Override
public void onProgress(int i) {
}
@Override
public void callback(String response) {
setDetails(response);
}
@Override
public void connectionFailed() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Utility.networkToast(Activity.this);
}
}, 5000);
}
};
IglHttpGet httpGet = new IglHttpGet(iglHttpGetListener);
httpGet.execute(url, "");
}
//////
private void setDetails(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
nameText.setText(jsonObject.getJSONObject("details").getString("full_name"));
if (jsonObject.getJSONObject("details").getJSONArray("phone").length() > 0) {
MobileNumber = jsonObject.getJSONObject("details").getJSONArray("phone").getJSONObject(0).getString("phone_number");
}
areaText.setText(jsonObject.getJSONObject("details").getJSONObject("location").getString("type_name"));
} catch (JSONException e) {
Crashlytics.logException(e);
}
}
|
No comments:
Post a Comment