In my project. For almost every Activity I have to make an AsyncTask .. And Almost the work is same for all of them. I want to create a generic AsyncTask and extends it. And i also want to send the methods in the constructor like this. Then Whenever I a class extends it . Just it have to create a method and it will do our work easily . and less coding .. It is time consuming .. Thanks for help in Advance..
One of my asyncTask is
private class GetData extends AsyncTask<String, Void, JSONObject> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(Calendar.this,
"", "");
}
@Override
protected JSONObject doInBackground(String... params) {
String response;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse responce = httpclient.execute(httppost);
HttpEntity httpEntity = responce.getEntity();
response = EntityUtils.toString(httpEntity);
Log.d("response is", response);
return new JSONObject(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
progressDialog.dismiss();
if(result != null)
{
try
{
JSONObject jobj = result.getJSONObject("result");
String status = jobj.getString("status");
if(status.equals("true"))
{
JSONArray array = jobj.getJSONArray("data");
for(int x = 0; x < array.length(); x++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", array.getJSONObject(x).getString("name"));
map.put("date", array.getJSONObject(x).getString("date"));
map.put("description", array.getJSONObject(x).getString("description"));
list.add(map);
}
CalendarAdapter adapter = new CalendarAdapter(Calendar.this, list);
list_of_calendar.setAdapter(adapter);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(Calendar.this, "Network Problem", Toast.LENGTH_LONG).show();
}
}
}
I just want to change the code in the post execute for each AsyncTask.. If I create a generic class and pass the Particular Method
to it. It will be very helpful..
let all your activities
implements
an interface say Ixxx, that has a method,activityOnPostExecute(String json)
, and pass the caller activity at theasyncTask
constructor as typeIxxx
,GenerucTask(Ixxx caller)
, and atpostExecute()
of theGenerucTask
invokecaller.activityOnPostExecute(result);
now at every activity override the methodactivityOnPostExecute()
.EDIT: here is waht i mean
1- Create the
interface
that all activities should implement, with theonPoseExec()
method:2- Create the GenericAsyncTask class,
3- At your activity, override the method onPostExec()
4- At your activity
onClick()
, or somewhere execute theGenericAsyncTask