Mehran
Mehran

Reputation: 501

Save Async Task result

I know not much about Async Task so I'm sorry if my question is so basic.
I have a AsyncTask class which downloads some data from my database and show them in a listview..
Now my Fragment that contains my executing task will show Loading progress every time my Fragment restarts and this is a little annoying ..
So I decided to do this :

Download task begin in my Fragment(in setUserVisibleHint method), save result, and show them in my listview from there.. And repeat this every time app restarts.. But I have no idea how to do it , I would be so grateful if you could give me just a hint..

This is my AsyncTask class :

    public class RingBankAsyncTask extends AsyncTask<String, Void, String> {
    private ProgressDialog progressDialog;
    private AsyncResponse delegate;
    private Context context;
    private HashMap<String, String> postData = new HashMap<String, String>();
    private String loadingMessage = "Loading...";
    private boolean showLoadingMessage = true;

   public RingBankAsyncTask(Context context, AsyncResponse delegate) {
     this.delegate = delegate;
     this.context = context;
   }

   public RingBankAsyncTask(Context context, boolean showLoadingMessage, AsyncResponse delegate) {
     this.delegate = delegate;
     this.context = context;
     this.showLoadingMessage = showLoadingMessage;
   }

   public RingBankAsyncTask(Context context, HashMap<String, String> postData, AsyncResponse delegate) {
     this.context = context;
     this.postData = postData;
     this.delegate = delegate;
  }

   public RingBankAsyncTask(Context context, HashMap<String, String> postData, boolean showLoadingMessage, AsyncResponse delegate) {
     this.context = context;
     this.postData = postData;
     this.delegate = delegate;
     this.showLoadingMessage = showLoadingMessage;
   }

   public RingBankAsyncTask(Context context, String loadingMessage, AsyncResponse delegate) {
     this.context = context;
     this.loadingMessage = loadingMessage;
     this.delegate = delegate;
   }

   public RingBankAsyncTask(Context context, HashMap<String, String> postData, String loadingMessage, AsyncResponse delegate) {
     this.context = context;
     this.postData = postData;
     this.loadingMessage = loadingMessage;
     this.delegate = delegate;
   }

   protected void onPreExecute() {
     if (this.showLoadingMessage == true) {
       this.progressDialog = new ProgressDialog(this.context);
       this.progressDialog.setMessage(this.loadingMessage);
       this.progressDialog.show();
     }

     super.onPreExecute();
   }

   protected String doInBackground(String[] urls) {
     String result = "";

     for (int i = 0; i <= 0; i++) {
       result = invokePost(urls[i], this.postData);
     }

     return result;
   }

   private String invokePost(String requestURL, HashMap<String, String> postDataParams) {
     String response = "";
     try {
       URL url = new URL(requestURL);

       HttpURLConnection conn = (HttpURLConnection)url.openConnection();
       conn.setReadTimeout(15000);
       conn.setConnectTimeout(15000);
       conn.setRequestMethod("POST");
       conn.setDoInput(true);
       conn.setDoOutput(true);

       OutputStream os = conn.getOutputStream();
       BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

       writer.write(getPostDataString(postDataParams));

       writer.flush();
       writer.close();
       os.close();
       int responseCode = conn.getResponseCode();

       if (responseCode == 200) {
         BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         String line;
         while ((line = br.readLine()) != null)
           response = new StringBuilder().append(response).append(line).toString();
       }
       else {
         response = "";

         Log.i("RingBankAsyncTask", new StringBuilder().append(responseCode).append("").toString());
       }
     } catch (Exception e) {
       e.printStackTrace();
     }

     return response;
   }

   private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
     StringBuilder result = new StringBuilder();
     boolean first = true;

     for (Map.Entry entry : params.entrySet()) {
       if (first)
         first = false;
       else {
         result.append("&");
       }
       result.append(URLEncoder.encode((String)entry.getKey(), "UTF-8"));
       result.append("=");
       result.append(URLEncoder.encode((String)entry.getValue(), "UTF-8"));
     }

     return result.toString();
   }

   protected void onPostExecute(String result) {
     if ((this.showLoadingMessage == true) && 
       (this.progressDialog.isShowing())) {
       this.progressDialog.dismiss();
     }

     result = result.trim();

     this.delegate.processFinish(result);
   }

   public String getLoadingMessage() {
     return this.loadingMessage;
  }

   public void setLoadingMessage(String loadingMessage) {
    this.loadingMessage = loadingMessage;
   } 
   public HashMap<String, String> getPostData() {
     return this.postData;
   }
   public void setPostData(HashMap<String, String> postData) {
    this.postData = postData;
  }

   public Context getContext() {
     return this.context;
   }

   public AsyncResponse getDelegate() {
     return this.delegate;
   }
 }

And I call it like this :

    RingBankAsyncTask task = new RingBankAsyncTask(getActivity(), this);
    task.execute(myUrl);

Upvotes: 2

Views: 775

Answers (2)

android_jain
android_jain

Reputation: 788

You should check check whether app is opening for the first time ot not.

         SharedPreferences sharedpreferences =.getSharedPreferences("CHEKINGFIRST", Context.MODE_PRIVATE);

    first= sharedpreferences12.getString("FIRST", "");
    if(!first.equal("second")){ 
  RingBankAsyncTask task = new RingBankAsyncTask(getActivity(), this);
task.execute(myUrl);
SharedPreferences sharedPreferencess=getActivity().getSharedPreferences("CHEKINGFIRST", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor1=sharedPreferencess.edit();
                    editor1.putString("FIRST","second");
                    editor1.commit();

              }

Upvotes: 1

Muhammad Usman
Muhammad Usman

Reputation: 923

when your app starts, just set some flag false by using SharedPreferences. and again calling first time AsyncTask make SharedPreferences flag to true, and check each time app starts whether flag is false or true. and one more thing you can do for more control on fragment, use setRetainInstance(true) in onActivityCreated of your fragment, this will help you to retain fragment instance while changing fragment configuration.

Upvotes: 0

Related Questions