保存异步任务结果

时间:2017-03-10 03:25:12

标签: android android-asynctask

我对异步任务知之甚少,所以如果我的问题非常基本,我很抱歉 我有一个AsyncTask类,它从我的数据库中下载一些数据并在列表视图中显示它们 现在我的Fragment包含我执行的任务,每次我的Fragment重新启动时都会显示加载进度,这有点烦人                                                                                                所以我决定这样做:

下载任务从我的片段开始(在setUserVisibleHint方法中),保存结果,并从那里在我的列表视图中显示它们。 每次app重启时重复此操作.. 但我不知道怎么做,如果你能给我一点提示,我将非常感激......

这是我的 AsyncTask 类:

    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;
   }
 }

我称之为:

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

2 个答案:

答案 0 :(得分:1)

你应该检查应用程序是否第一次打开,不是。

         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();

              }

答案 1 :(得分:0)

当您的应用启动时,只需使用false设置一些标记SharedPreferences即可。并再次呼叫第一次AsyncTask使SharedPreferences flag成为真,并在每次应用开始时检查flagfalse还是true。 还有一件事可以让您对片段进行更多控制,在片段的setRetainInstance(true)中使用onActivityCreated,这将有助于您在更改fragment配置时保留片段实例。