I'm developing an Android 3.1 and above application.
I have this code to download some json data:
public class FormsListActivity extends ListActivity
{
private List<Form> mForms;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.formlist);
FormListAsyncTask formAsyncTask = new FormListAsyncTask(this);
formAsyncTask.execute("http://192.168.1.128/RestServiceImpl.svc/forms/");
}
private class FormListAsyncTask extends AsyncTask<String, Integer, List<Form>> {
private Context mContext;
private ProgressDialog loadingDialog;
FormListAsyncTask(Context context)
{
mContext = context;
loadingDialog = new ProgressDialog(mContext);
loadingDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
loadingDialog.setMessage("Downloading. Please wait...");
loadingDialog.setCancelable(false);
loadingDialog.setMax(100);
loadingDialog.show();
}
#Override
protected List<Form> doInBackground(String... url)
{
Log.v("doInBackground", "retreiving forms");
return FormSpringController.LoadAll(url[0]);
}
// Just some example code to update your progress dialog
protected void onProgressUpdate(Integer... values)
{
Log.v("onProgressUpdate", "updating: " + ((int) ((values[0] / (float) values[1]) * 100)));
loadingDialog.setProgress((int) ((values[0] / (float) values[1]) * 100));
}
protected void onPostExecute(List<Form> forms)
{
if (forms != null)
{
ListActivity act = (ListActivity) mContext;
act.setListAdapter(new FormAdapter(act, R.layout.form_list_item, forms));
mForms = forms;
}
else
{
TextView errorMsg = (TextView)
((FormsListActivity) mContext).findViewById(R.id.formErrorMsg);
errorMsg.setText("Problem downloading forms. Please try again later.");
}
loadingDialog.dismiss();
}
}
}
Why loadingDialog's progress is not updated on onProgressUpdate?
I am not finding any publishProgress(); in your code.
call publishProgress() from your doInBackground() which call override onProgressUpdate() implicitly.
Related
I want to bring up a progress dialog when the user loads up the twitter feed and when the twitter feed has loaded the progress dialog disappears.
This is the TwitterAsyncTask class:
public class TwitterAsyncTask extends AsyncTask<Object, Void, ArrayList<TwitterTweet>> {
ListActivity callerActivity;
private ProgressDialog pd;
final static String TWITTER_API_KEY = "ddd";
final static String TWITTER_API_SECRET ="fffff";
Context cnt;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(cnt.getApplicationContext());
pd.setMessage("loading");
pd.show();
}
#Override
protected ArrayList<TwitterTweet> doInBackground(Object... params) {
ArrayList<TwitterTweet> twitterTweets = null;
callerActivity = (ListActivity) params[1];
if (params.length > 0) {
TwitterAPI twitterAPI = new TwitterAPI(TWITTER_API_KEY,TWITTER_API_SECRET);
twitterTweets = twitterAPI.getTwitterTweets(params[0].toString());
}
return twitterTweets;
}
#Override
protected void onPostExecute(ArrayList<TwitterTweet> twitterTweets) {
ArrayAdapter<TwitterTweet> adapter =
new ArrayAdapter<TwitterTweet>(callerActivity, R.layout.twitter_tweets_list,
R.id.listTextView, twitterTweets);
callerActivity.setListAdapter(adapter);
ListView lv = callerActivity.getListView();
lv.setDividerHeight(0);
lv.setBackgroundColor(callerActivity.getResources().getColor(R.color.white));
if (pd != null)
{
pd.dismiss();
}
}
}
And here is the class that calls the TwitterAsyncTask class:
public class MainActivity extends ListActivity {
final static String twitterScreenName = "CFABUK";
final static String TAG = "MainActivity";
private AsyncTask<Object, Void, ArrayList<TwitterTweet>> tat;
boolean done;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
done = false;
AndroidNetworkUtility androidNetworkUtility = new AndroidNetworkUtility();
if (androidNetworkUtility.isConnected(this)) {
new TwitterAsyncTask().execute(twitterScreenName, this);
} else {
Log.v(TAG, "Network not Available!");
}
}
public void timerDelayRemoveDialog(long time, final ProgressDialog d) {
new Handler().postDelayed(new Runnable() {
public void run() {
d.dismiss();
}
}, time);
}
}
the error seems to appear for the line pd = new ProgressDialog(cnt.getApplicationContext());...What should I put for this? thanks
Just add Constructor in your AsyncTask like
Context mContext;
public TwitterAsyncTask(Context mContext){
this.mContext=mContext;
}
And from your activity
Context mContext=this;
new TwitterAsyncTask(mContext).execute(twitterScreenName, this);
Instead of cnt.getApplicationContext() replace it with YourClassName.this
Embed your Async task in your activity, and replace your Context cnt by YourActivity.class... And please include some log.
i have listview and the content of listview change depend on user interface
and i need to know how to create new instance of async task if i implement callback receiver
public interface CallbackReciever {
public void receiveData(String result);
}
and the async task class
public abstract class ConnectDB extends AsyncTask<String, String, String> implements CallbackReciever {
ProgressDialog pDialog;
Context context;
public String resString;
public ConnectDB(Context context)
{
// TODO Auto-generated constructor stub
this.context=context;
}
#Override
public abstract void receiveData(String object);
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args)
{
// getting JSON string from URL
resString =Connection.Get(path);
return resString;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url)
{
// dismiss the dialog after getting all products
pDialog.dismiss();
if(resString!=null)
{
receiveData(resString);
}
}
}
and the MainActivity class
public class MainActivity extends Activity {
ListView list;
MovieAdapter adapter;
public ArrayList<Movie> data=new ArrayList<Movie>();
public ConnectDB conDB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Context t=this.getApplicationContext();
setContentView(R.layout.activity_main);
conDB= new ConnectDB(MainActivity.this) {
#Override
public void receiveData(String result) {
// TODO Auto-generated method stub
try {
Log.d("ds", result);
JSONObject json = null;
JSONArray jArray = new JSONArray(result);
int i=0;
while ( i< jArray.length())
{
final Movie tmp=new Movie();
json = jArray.getJSONObject(i);
tmp.setName(json.getString("name"));
tmp.setUrl(json.getString("image"));
tmp.setDescription(json.getString("desc"));
tmp.setTime(json.getString("time"));
tmp.setTime(Utils.ChangeTolocaclTime(tmp.getTime()));
tmp.setWatch(Utils.CanWatch(tmp.getTime()));
data.add(tmp);
i++;
}
}
catch (JSONException e) {
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
if(data.size()==0)
{
Toast.makeText(t, "Server Error", Toast.LENGTH_SHORT).show();
list.setVisibility(View.INVISIBLE);
}
// Create custom adapter for listview
adapter=new MovieAdapter(MainActivity.this, data,t);
//Set adapter to listview
list.setAdapter(adapter);
}
};
conDB.execute("MBC2");
}
The activity should implement the receiver and the async task should call it, something like this:
public class MyActivity extends Activity implements CallbackReceiver{
#Override
public void onCreate(Bundle savedInstanceState) {
//Set everything up
MyAsyncTask task = new MyAsyncTask();
task.setOnDataReceivedListener(this);
task.execute();
}
#Override
public void onReceiveData(String data){
//Do something with the data
}
}
Then, in the async task, you can call the receiver method in onPostExecute
public abstract class MyAsyncTask extends AsyncTask<String, String, String>{
private CallbackReciever receiver = null;
public void setOnDataReceivedListener(CallbackReciever receiver){
this.receiver = receiver
}
protected void onPostExecute(String file_url)
{
if(receiver != null){
receiver.onReceiveData(file_url);
}
}
}
The second way to do this is to simply make an anonymous inner class of your async task and override onPostExecute:
public class MyActivity extends Activity implements CallbackReceiver{
#Override
public void onCreate(Bundle savedInstanceState) {
//Set everything up
MyAsyncTask task = new MyAsyncTask(){
#Override
protected void onPostExecute(String file_url){
//Do what you want with your data here
}
};
task.execute();
}
}
So I am completely new to Andorid programming and can't seem to get a ProgressDialog to show on a ListActivity (ScheduleActiviy in my example) when running an AsyncTask from a separate class (GetGames in my example). I am attempting to use separate class for code re-usability. When I previously had the AsyncTask as an embedded class it seemed to work. I have posted what I believe to be all the relevant code. Any help would be great. Thanks!
ScheduleActivity.java
public class ScheduleActivity extends ListActivity
{
private final String PDIALOG_MSG = "Loading schedule...";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.schedule);
ArrayList<HashMap<String, String>> gamesList = null;
try
{
// Loading information in Background Threads
gamesList = new GetGames(ScheduleActivity.this, PDIALOG_MSG).execute().get();
GetGames.java
public class GetGames extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>>
{
private Context context;
private ProgressDialog pDialog;
private String pDialogMsg;
public GetGames(Context ctx, String dialogMsg)
{
context = ctx;
pDialogMsg = dialogMsg;
}
#Override
public void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage(pDialogMsg);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public void onPostExecute(ArrayList<HashMap<String, String>> rtnList)
{
pDialog.dismiss();
}
Your ProgressDialog should probably be controlled on the Activity level instead of the AsyncTask level. Theoretically I don't see why how you're doing it wouldn't work, but I can show you a method which definitely works (it's what I do) and it organizes things a bit differently:
//In AsyncTask
#Override
protected void onPreExecute() {
showProgressDialog(R.string.importing_pages);
}
#Override
public void onPostExecute(Boolean b) {
hideProgressDialog();
}
//In Activity
public void showProgressDialog(int msgResId) {
showProgressDialog(getString(msgResId));
}
public void showProgressDialog(String msg) {
mProgressDialog = ProgressDialogHelper.buildDialog(this, msg);
mProgressDialog.show();
}
public void hideProgressDialog() {
if(mProgressDialog != null)
mProgressDialog.dismiss();
}
//My progress dialog helper class:
public class ProgressDialogHelper {
/**
* Creates a generic progress dialog with the specified message
*
* #param activity the activity which hosts the dialog. This must be an activity, not a context.
* #param msgResId the resId for the message to display
* #return a progress dialog
*/
public static ProgressDialog buildDialog(Activity activity, int msgResId) {
return buildDialog(activity, activity.getApplicationContext().getString(msgResId));
}
/**
* Creates a generic progress dialog with the specified message
*
* #param activity the activity which hosts the dialog. This must be an activity, not a context.
* #param msg the message to display
* #return a progress dialog
*/
public static ProgressDialog buildDialog(Activity activity, String msg) {
ProgressDialog dialog;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
dialog = new ProgressDialog(new ContextThemeWrapper(activity, android.R.style.Theme_Holo_Dialog));
else
dialog = new ProgressDialog(activity);
dialog.setMessage(msg);
dialog.setCancelable(false);
return dialog;
}
}
You don't have to make a helper class if you don't want to, it's just how I organized it. The main idea here is that the progress dialog should be owned by the Activity instead of the AsyncTask.
Also, the context used must be the activity's, not getApplicationContext(). It looks like you have that part right though.
You can display Progress Dialogs using AsyncTasks. That's not a problem. I do it all the time. What may be the problem is the doInBackground() method. What do you have there?
I also generally nest the AsyncTasks within the Activity class, so that it can call other Activity class methods in the onPostExecute() method. Otherwise, in order for it to communicate back with your Activity you'll have to use something like a handler or static references.
public class TestActivity extends Activity {
private AsyncTask<Void, Void, ArrayList<String>> bgLoader;
private ArrayList<String> listOfStuff;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
listOfStuff = new ArrayList<String>();
textView = (TextView) findViewById(R.id.textView);
textView.setText("Your list has " + listOfStuff.size() + " items in it!");
bgLoader = new MyAsyncTask(this, "Waiting...").execute();
}
private void resumeDoingStuff() {
try {
listOfStuff = bgLoader.get();
textView.setText("Your list has " + listOfStuff.size() + " items in it!");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public class MyAsyncTask extends AsyncTask<Void, Void, ArrayList<String>> {
private ProgressDialog progressDialog;
private String message;
private Context ctx;
public MyAsyncTask(Context context, String message) {
this.ctx = context;
this.message = message;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(ctx);
progressDialog.setMessage(message);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected ArrayList<String> doInBackground(Void... params) {
ArrayList<String> retList = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
try {
retList.add("TEST STRING " + i);
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return retList;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
progressDialog.dismiss();
resumeDoingStuff();
}
}
}
The progress dialog in AsyncTask does not dismiss, even though progressDialog.dismiss is run in onPostExecute().
I have tried implementing many answers to related questions on SO, with no success so far.
I am sure that I must be overlooking something very basic, but I am stuck.
Any pointers to an explanation and code snippet would be great, Thanks.
Main
public class Main extends Activity {
String result;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
asyncTask task = new asyncTask("Loading ...", this);
try {
result = task.execute("Question").get();
}
catch (Exception e) {
Log.e("Error: ", e.toString());
}
}
}
asyncTask
public class asyncTask extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private String message;
private Context context;
public asyncTask(String msg, Context ctx) {
this.context = ctx;
message = msg;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.show(context, "", message, true, false);
}
#Override
protected String doInBackground(String... params) {
int count = 100000;
for (int i = 0; i < count; i++) {
// waste time
}
return "Answer";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}
Actually your are doing :
progressDialog.show(context, "", message, true, false);
instead it should be like :
progressDialog = ProgressDialog.show(context, "", message, true, false);
You have to statically call show method and assign it to your progressDialog
Make this changes in your onPostExecute
#Override
protected void onPostExecute(String result) {
try{
if(progrssDialog.isShowing()){
progressDialog.dismiss();
}
}
catch(Exception e){
e.printStackTrace();
}
finally
{
progressDialog.dismiss();
}
}
A common issue i have found is the Variable Scope.
Most times , the ProgressDialog will be defined inside a Method , which wont be accessable outside that method.
You need to Declare it like so ,
Public Class MainActivity extends Activity {
ProgressDialog progressDialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private class asyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}
replace
task.execute("Question").get();
with
task.execute("Question");
by calling .get() you forcing main thread to wait. It will/can hang your UI.
progressDialog.dismiss();
put this in doInBackground() method before Return Statement.
I'm trying to display a custom progressdialog while loading RSS feed from an HTTP server, I made a hard search, but nothing helped me to do this, the only thing I know is that the solution should use AsyncTask, but I'm confusing about the params to pass to this AsyncTask.
Here's my activity :
public class Soirees extends ListActivity {
private List<Message> messages;
private TextView tvSorties;
private MyProgressDialog dialog;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.sorties);
tvSorties=(TextView)findViewById(R.id.TVTitle);
tvSorties.setText("Programme des soirées");
loadFeed();
}
private void loadFeed(){
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
List<Message> titles = new ArrayList<Message>(messages.size());
for (Message msg : messages){
titles.add(msg);
}
MessageListAdapter adapter = new MessageListAdapter(this,titles);
this.setListAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (Throwable t){
Log.e("ImageLoader",t.getMessage(),t);
}
}
}
Can you please help me add AsyncTask to this?
/**
* this class performs all the work, shows dialog before the work and dismiss it after
*/
public class ProgressTask extends AsyncTask<String, Void, Boolean> {
public ProgressTask(ListActivity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
}
/** progress dialog to show user that the backup is processing. */
private ProgressDialog dialog;
/** application context. */
private ListActivity activity;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
MessageListAdapter adapter = new MessageListAdapter(activity, titles);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
if (success) {
Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
}
}
protected Boolean doInBackground(final String... args) {
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
List<Message> titles = new ArrayList<Message>(messages.size());
for (Message msg : messages){
titles.add(msg);
}
activity.setMessages(titles);
return true;
} catch (Exception e)
Log.e("tag", "error", e);
return false;
}
}
}
public class Soirees extends ListActivity {
private List<Message> messages;
private TextView tvSorties;
private MyProgressDialog dialog;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.sorties);
tvSorties=(TextView)findViewById(R.id.TVTitle);
tvSorties.setText("Programme des soirées");
// just call here the task
AsyncTask task = new ProgressTask(this).execute();
}
public void setMessages(List<Message> msgs) {
messages = msgs;
}
}
Fixed by moving the view modifiers to onPostExecute so the fixed code is :
public class Soirees extends ListActivity {
private List<Message> messages;
private TextView tvSorties;
//private MyProgressDialog dialog;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.sorties);
tvSorties=(TextView)findViewById(R.id.TVTitle);
tvSorties.setText("Programme des soirées");
new ProgressTask(Soirees.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
List<Message> titles;
private ListActivity activity;
//private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
List<Message> titles = new ArrayList<Message>(messages.size());
for (Message msg : messages){
titles.add(msg);
}
MessageListAdapter adapter = new MessageListAdapter(activity, titles);
activity.setListAdapter(adapter);
adapter.notifyDataSetChanged();
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
}
}
protected Boolean doInBackground(final String... args) {
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
return true;
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
}
}
}
#Vladimir, thx your code was very helpful.
AsyncTask is very helpful!
class QueryBibleDetail extends AsyncTask<Integer, Integer, String>{
private Activity activity;
private ProgressDialog dialog;
private Context context;
public QueryBibleDetail(Activity activity){
this.activity = activity;
this.context = activity;
this.dialog = new ProgressDialog(activity);
this.dialog.setTitle("查询经文");
this.dialog.setMessage("正在查询:"+tome+chapterID+":"+sectionFromID+"-"+sectionToID);
if(!this.dialog.isShowing()){
this.dialog.show();
}
}
#Override
protected String doInBackground(Integer... params) {
Log.d(TAG,"经文doInBackground");
publishProgress(params[0]);
if(sectionFromID > sectionToID){
return "";
}
String queryBible = "action=query_bible&article="+chapterID+"&id="+tomeID+"&verse_start="+sectionFromID+"&verse_stop="+sectionToID+"";
try{
String bible = (Json.getRequest(HOST+queryBible)).trim();
bible = android.text.Html.fromHtml(bible).toString();
return bible;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String bible){
Log.d(TAG,"经文onPostExecute");
TextView bibleBox = (TextView) findViewById(R.id.bibleBox);
bibleBox.setText(bible);
this.dialog.dismiss();
}
}
A couple of days ago I found a very nice solution of this problem. Read about it here. In two words Mike created a AsyncTaskManager that mediates ProgressDialog and AsyncTask. It's very easy to use this solution. You just need to include in your project several interfaces and several classes and in your activity write some simple code and nest your new AsyncTask from BaseTask. I also advice you to read comments because there are some useful tips.
Don't know what parameter should I use?
A lot of Developers including have hard time at the beginning writing an AsyncTask because of the ambiguity of the parameters. The big reason is we try to memorize the parameters used in the AsyncTask. The key is Don't memorize. If you can visualize what your task really needs to do then writing the AsyncTask with the correct signature would be a piece of cake.
What is an AsyncTask?
AsyncTask are background task which run in the background thread. It takes an Input, performs Progress and gives Output.
ie AsyncTask<Input,Progress,Output>
Just figure out what your Input, Progress and Output are and you will be good to go.
For example
How does doInbackground() changes with AsyncTask parameters?
How doInBackground() and onPostExecute(),onProgressUpdate() are
related?
How can You write this in a code?
DownloadTask extends AsyncTask<String,Integer,String>{
#Override
public void onPreExecute(){
}
#Override
public String doInbackGround(String... params)
{
// Download code
int downloadPerc = // calculate that
publish(downloadPerc);
return "Download Success";
}
#Override
public void onPostExecute(String result)
{
super.onPostExecute(result);
}
#Override
public void onProgressUpdate(Integer... params)
{
// show in spinner, access UI elements
}
}
How will you run this Task in Your Activity?
new DownLoadTask().execute("Paradise.mp3");
It's been a few years since this question was asked (and since someone has posted a response). Since then, ProgressDialog was deprecated in API level O, according to Android's official documentation. As such, you might consider using an inline progress bar instead of a ProgressDialog as the documentation authors suggest.
This question is already answered and most of the answers here are correct but they don't solve one major issue with config changes. Have a look at this article https://androidresearch.wordpress.com/2013/05/10/dealing-with-asynctask-and-screen-orientation/ if you would like to write a async task in a better way.