I'm executing AsyncTask that fetch data from my web host. In order for me to retrieve data, I need to re-open my app. How can I fetch data every second? I know that AsyncTask could only be executed once, but I needed it not only for my app but also to learn about this problem. Hope to learn from you guys.
By the way this is my code:
class AsyncDataClass2 extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", params[1]));
nameValuePairs.add(new BasicNameValuePair("password", params[2]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
if (result.equals("") || result == null)
{
Toast msg = Toast.makeText(MapsActivity.this, "connection failed", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, 0, 0);
msg.show();
}
else
{
Toast msg = Toast.makeText(MapsActivity.this, "connected", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER,0,0);
msg.show();
}
try {
JSONArray json = new JSONArray(result);
for (int i = 0; i < json.length(); i++) {
JSONObject e = json.getJSONObject(i);
String point = e.getString("Point");
String[] point2 = point.split(",");
String devStatus = e.getString("Status"); //now, let's process the Status...
String strOwner = e.getString("Owner"); //now, let's process the owner...
//==============================================================================
if (devStatus.equals("fire")) {
IsThereFire=true;
}
} //---End of FOR LOOP---//
}//---end of TRY---//
catch (JSONException e)
{
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is)
{
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try
{
while ((rLine = br.readLine()) != null)
{
answer.append(rLine);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
EDIT:
Sir, this is the timer I used..
///---CODE for the TIMER that ticks every second and synch to database to update status---///
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// HERE IS THE ACTUAL CODE WHERE I CALL THE ASYNCDATACLASS2
AsyncDataClass2 performBackgroundTask = new AsyncDataClass2();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
//---------------------------------------------------------------//
if you need to execute a task at fixed interval of time you can use a Timer with a TimerTask. It runs on different thread than the UI thread, meaning that you can run your http call directly in it. You can find the documentation here
I think you should try to use TimerTask or a job scheduler.
Lots of information about job schedulers can be found here and here.
Check this:
Timer timer;
private void startTimer() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
new AsyncDataClass2 adc = new AsyncDataClass2("u","p");
adc.execute();
}
}, 0, 1000);
}
Then in onCreate() you write:
startTimer();
Although, you should consider others comments, they're meaningful, requesting updates from web server every second in AsyncTask, it's not so good thing to do.
I do not think that's a really good idea to proceed like this but you can do it, of course with an simple TimerTask (tutorial there)
Basically, it would look like this:
public class MyTimerTask extends TimerTask {
#Override
public void run() {
// Just start your AsyncTask and proceed, I didn't adapt the code to your task
new AsyncDataClass2().execute()
}
}
Your Logic calls it:
TimerTask timerTask = new MyTimerTask();
// They're ms: 1000ms = 1s
timer.scheduleAtFixedRate(timerTask, 0, 1000);
timer.start();
You cancel it when you destroy your Fragment/Activity
timer.cancel();
Related
TimerTask is scheduled for every 15 minutes to refresh the data of the app. How can i execute the TimerTask for once outside the class without affecting the scheduled timer task as i have to keep updating the data of the app every 15 minutes. There is a scenario where i need to immediately update the data outside the class.
public class SplashActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
}
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
if (timer == null) {
cancel();
}
Boolean isInternetPresent = internetCheck.isConnectingToInternet();
if(isInternetPresent)
new MyAsyncTask().execute();
else
System.out.println("Internet connection not presents ");
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 900000);
}
public class MyAsyncTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
long s_time = System.currentTimeMillis();
android.util.Log.i("Start ", " Time value in millisecinds " + s_time);
String xmlDataOverHttp = PostData();
long e_time = System.currentTimeMillis();
android.util.Log.i("End ", " Time value in millisecinds " + e_time);
Myregistry registry= AppRegistry.getInstance();
Serializer serializer = new Persister();
MyObject example = null;
try {
example = serializer.read(MyObject.class, student_xml);
} catch (Exception e) {
e.printStackTrace();
}
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(MyObjectXMl, xmlDataOverHttp);
editor.apply();
registry.setObject(example);
return xmlDataOverHttp;
}
public String PostData() {
Boolean s = false;
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
String url = "http://localhost:8080" +"/get_xml_data?id=" + 1;
System.out.println("url----------" + url);
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
String token = readResponse(httpResponse);
return token;
}
Here MyAsyncTask is scheduled in TimerTask which gets called after every 15 minutes. How can i call this MyAsyncTask outside the class without affecting the scheduled TimerTask. I cnnot make MyAsyncTask class as static.
Currently, my app needs to do a task every 5 seconds, which involves updating the locations of markers in a Google Maps API-using map. However, it only really needs to do it every 5 seconds when the app is open and people are using it.
It seems that AsyncTask, according to people on the Internet, runs even when the app is closed, causing it to use up a lot of battery life.
How do I make it so that the task runs if and only if the app is open or just starting?
private class MyAsyncTask extends AsyncTask<String, String, Void> {
InputStream inputStream = null;
String result = "";
#Override
protected Void doInBackground(String... params) {
String url_select = "https://www.example.com/"; // generic
try {
URL url = new URL(url_select);
HttpURLConnection connectTo = (HttpURLConnection) url.openConnection();
connectTo.setRequestProperty("User-Agent", "");
connectTo.setRequestMethod("POST");
connectTo.setDoInput(true);
connectTo.connect();
// Read content & Log
inputStream = connectTo.getInputStream();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("St.Build,BuffRead", "Error converting result " + e.toString());
}
return null;
} // protected Void doInBackground(String... params)
#Override
protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONObject busData = new JSONObject(result);
if (busData.getString("title").equals("Bus Positions")) {
for (Marker mark: allBuses) {
mark.remove(); // Remove marker
}
allBuses.clear();
JSONObject resultSet = busData.getJSONObject("ResultSet");
JSONArray results = resultSet.getJSONArray("Result");
for (int i = 0; i < results.length(); i++) {
JSONObject bus = results.getJSONObject(i);
double lat = bus.getDouble("lat");
double lng = bus.getDouble("lng");
int call_name = bus.getInt("call_name");
String bus_type = "bus";
LatLng busLocation = new LatLng(lat,lng);
Marker busMark = map.addMarker(new MarkerOptions()
.position(busLocation)
.title(bus_type)
.icon(BitmapDescriptorFactory.fromResource(R.id.action_search)));
allBuses.add(busMark);
}
}
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
} // protected void onPostExecute(Void v)
}
You can use some workarounds to create a long running asynctask and manage its life cycle accordingly to the life cycle of the activity.
You can cancel the AsyncTask in the onStop method of you Activity.
In my searches across the web I saw a few different approaches and wanted to know what is the best way of doing this.
Best way to schedule a server call?
the options I saw were:
1. Timer
2. ScheduledThreadPoolExecutor
***Timer***
int delay = 5000; // delay for 5 sec
int period = 1000; // repeat every sec
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
// // call your MyAsyncTask class
}
}, delay, period);
}
*Timer has some drawbacks that are solved by ScheduledThreadPoolExecutor.
*
***ScheduledThreadPoolExecutor.***
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("EXESER", "CH EXES");
// Your code
}
});
}
}, 1
0, 40, TimeUnit.SECONDS);
what's your opinion?
I want execute http post after getting response from server.
If server response is false the http post will execute else not execute.
How can i do for this.
My android main activity code:
if (Utility.isValidMobile(mobileNumber)) {
String isAvailable = userDelegate.checkUser(mobileNumber, context);
if (isAvailable.equals("false")) {
userDelegate.addUser(userMO, context);
Toast.makeText(getApplicationContext(), "Your mobile number is" + mobileNumber + "name is" + userName, Toast.LENGTH_LONG).show();
} else if (isAvailable.equals("true")) {
Toast.makeText(getApplicationContext(), "Your mobile number is already registerd", Toast.LENGTH_LONG).show();
}
}
when i click signup button this above code will executed
My Userdelegate class code :
public void addUser(final UserMO userMo, final Context context) {
final String jsonStringObject = gson.toJson(userMo);
Thread t = new Thread() {
public void run() {
Looper.prepare(); // for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
// Limit
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userBO", jsonStringObject));
HttpPost post = new HttpPost("http://192.168.1.101:8080/warname/user/addUser");
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
Toast.makeText(context, "Your user id " + rd.readLine(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
Looper.loop(); // Loop in the message queue
}
};
t.start();
}
public void getMatchingExistingUserList(final String mobile_number, final Context context) {
final String jsonStringObject = gson.toJson(mobile_number);
Thread t = new Thread() {
public void run() {
Looper.prepare(); // for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
// Limit
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userBO", jsonStringObject));
HttpPost post = new HttpPost("http://192.168.1.101:8080/warname/user/addUser");
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
final String responseString = rd.readLine();
} catch (Exception e) {
e.printStackTrace();
}
Looper.loop(); // Loop in the message queue
}
};
t.start();
}
public String checkUser(final String mobile_number, final Context context) {
final StringBuilder isAvailable = new StringBuilder();
Thread t = new Thread() {
#Override
public void run() {
Looper.prepare(); // for the child Thread
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("MobileNumber", gson.toJson(mobile_number)));
HttpPost post = new HttpPost("http://192.168.1.101:8080/warname/user/checkUserMobileNumber");
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
isAvailable.append(rd.readLine());
} catch (Exception e) {
e.printStackTrace();
}
Looper.loop(); // Loop in the message queue
}
};
t.start();
return isAvailable.toString();
}
Problem is i got response false but the if condition not working.
how to solve this problem.
After changing:
if (Utility.isValidMobile(mobileNumber)) {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return userDelegate.checkUser(mobileNumber, context);
}
#Override
protected void onPostExecute(String isAvailable) {
Toast.makeText(getApplicationContext(), isAvailable, Toast.LENGTH_LONG).show();
if (isAvailable.equals("false")) {
Toast.makeText(getApplicationContext(), "Your mobile number is" + mobileNumber + "name is" + userName, Toast.LENGTH_LONG).show();
userDelegate.addUser(userMO, context);
} else if (isAvailable.equals("true")) {
Toast.makeText(getApplicationContext(), "Your mobile number is already registerd", Toast.LENGTH_LONG).show();
}
}
}.execute(null, null, null);
}
The if condition is not working ?
If server response is false the http post will execute else not
execute. How can i do for this
Issue occurring because you are using Threads in checkUser and addUser. Thread's execute with-out stopping execution of current Thread.
For example, when checkUser method is called from main thread then final StringBuilder isAvailable = new StringBuilder(); executing on main thread and Thread t is executing in separately. so system return control to next line which is return isAvailable.toString(); without waiting Thread execution complete means checkUser method always return null or empty string.
Same is for addUser method.
To do task accoding to result of checkUser method response use AsyncTask class.
You are using new threads to do http request here. Therefore your delegate methods are not synchronized. addUser and checkUser will return before your http requests finish.
To write multi thread codes like yours, you may want to use a some kind of a listener to do the threads communication work.
For example, you can pass a listener to your delegate which looks like this
class Listener{
private Handler handler = new Handler();
public void onUserAdded(){
handler.post(new Runnable(){
public void run(){
// Toast your thing
}
});
}
public void onUserChecked(final boolean available){
handler.post(new Runnable(){
public void run(){
if(available){
// Toast your thing
}else{
userDelegate.addUser(userMO, context);
}
}
});
}
}
And all your new Thread(){ run(){ codes should end with all call to the listener.
As you can see I use a Handler to post works back to the UI thread. This is very important for you to notify your UI elements of what is going on in your none-UI threads.
Also, I can't see what you are doing with your Looper.prepare() and Looper.loop(). No child thread is there.
I am using AsyncTask to fetch data from server, what if to check whether any new data available or to update changes in existing data in every 10 seconds
public class MainActivity extends Activity {
CenterLockHorizontalScrollview centerLockHorizontalScrollview;
ArrayList<Actors> actorsList;
ActorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
centerLockHorizontalScrollview = (CenterLockHorizontalScrollview) findViewById(R.id.scrollView);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
Log.d("Name:", object.getString("name"));
actor.setImage(object.getString("image"));
Log.d("Image:", object.getString("image"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
if(actorsList != null) {
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
centerLockHorizontalScrollview.setAdapter(MainActivity.this, adapter);
}
}
}
There is several ways on going about this. The most suitable one will depends mostly on the specs, design & architecture decision for you're app.
1) Java's TimerTask.
import java.util.Timer;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// work
}
}, 0, 10*1000); // 0 - time before first execution, 10*1000 - repeating of all subsequent executions
timer.cancel(); //cancels the timer and all schedules executions
2) Android's Handler. Powerful feature and commonly used for things like what you are asking. But, you must make sure you are not nesting handlers. More info here ; it describes more or less the solution for what you are looking for using Handlers.
3) Android's scheduled alarms. Even though this would work, if you really want to run something every 10 seconds, then, i will say this is probably not the best solution. But anyway, this allows you register for Android's alarms, which gives you a bit of time to run something in a BroadcastReceiver, which is triggered when the alarm is fired. There's a lot into this, but you can learn how to schedule an alarm here : https://developer.android.com/training/scheduling/alarms.html
you can check by using refresh method.
void refresh(boolean b){
if(b){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
refresh(true);
}
}, 10*1000);
}
}
call this method in your oncreate
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
refresh(true);
Friends ,i need help to android httppost data to server using Asynctask or Threads
I need to send data to my server when i click post button.But when i click it app need to go to next page and data need to send through as background process.I'm new to Android.I don't know what is exactly use for this kind of task (Threads or Asyanctask).
I tried this code but it will give me exception error
public void startProgress(final String name) {
// Do something long
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
send(name);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(runnable).start();
}
public void send(String name)
{
// get the message from the message text box
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:8080/Test");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String co2 =input_field.getText().toString();
nameValuePairs.add(new BasicNameValuePair("Name", name));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Toast toast = Toast.makeText(getApplicationContext(), "Got it ", Toast.LENGTH_SHORT);
toast.show();
httpclient.execute(httppost);
input_field.setText("");
} catch(Exception e){
Toast toast2 = Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT);
toast2.show();
}
}
but if i use it this way it works.(text is TextView item in that page)
public void startProgress(final String name) {
// Do something long
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text.post(new Runnable() {
#Override
public void run() {
send(name);
}
});
}
};
new Thread(runnable).start();
}
What happen in bellow piece of code can you please explain about this also
text.post(new Runnable() {
#Override
public void run() {
send(name);
}
});
please help me to solve this problem.If there is better way to do my need please mentioned it .Because it have very less experience about Android development
You can do this by using AsyncTask like this:
public class HttpPostExanple extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
BufferedReader inBuffer = null;
String url = "http://10.0.2.2:8080/Test";
String result = "fail";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("name", params[0]));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
postParameters);
request.setEntity(formEntity);
httpClient.execute(request);
result="got it";
} catch(Exception e) {
// Do something about exceptions
result = e.getMessage();
} finally {
if (inBuffer != null) {
try {
inBuffer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
protected void onPostExecute(String page)
{
//textView.setText(page);
Toast toast = Toast.makeText(getApplicationContext(), page, Toast.LENGTH_SHORT);
toast.show();
}
}
And you need to have this in your main method
new HttpPostExample().execute(new String[] {name});
Check this out.
Hope this will help you.
You should implement something like this:
new Thread(new Runnable() {
public void run() {
send(name); // if this method need to access the UI interface you have to use .post method
}
}).start();
About your question: the .post method causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread. [reference]
And this is required because without this method you violate the single thread model: the Android UI toolkit is not thread-safe and must always be manipulated on the UI thread. In your piece of code, the TextView is manipulated on a worker thread, which can cause really weird problems.
As you can see, If the method inside your thread need to access the UI you should use .post method, and this make more laborious the code. So the right solution may be use the AsyncTask that will manage for you the complexity of the threads. You have to put the piace of code that need to access on the UI, in the onPostExecute() method
I suggest you to use robospice or other frameworks as alternative:
Volley
DataDroid
REST Provider
REST Droid
PostMan (rings twice) Lib
Ion
droidQuery
Android Job Queue
Goro
because activity can be recreated before onPostExecute reached. AsyncTask is not good example for networking in Activity.