【问题标题】:unable to save data to txt in loop asynctask无法在循环异步任务中将数据保存到 txt
【发布时间】:2013-12-24 17:55:57
【问题描述】:

我正在尝试将每个 http 调用的每个输出数据保存在 asynctask 中。但我无法在文件中看到任何数据。非常感谢任何帮助。提前致谢。

     final String[] ar={"1","2","3",.............,"25"}

        filename="test_file";       
            myFile = new File("/sdcard/"+filename);
                 try {
                        myFile.createNewFile();
                    fOut = new FileOutputStream(myFile);
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                 myOutWriter = new OutputStreamWriter(fOut); 


                         for (  j = 0; j < ar.length; j++) {


                                 u="http://www.example.com/"+ar[j];

                                JSONParser jParser=new JSONParser();        


             new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,u);

                        }


                               try {
                            myOutWriter.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

    }


            class MyAsyncTask extends AsyncTask<String, String, Void> {

                private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
                InputStream inputStream = null;
                String result = ""; 

                protected void onPreExecute() {
                    progressDialog.setMessage("Downloading your data...");
                    progressDialog.show();
                    progressDialog.setOnCancelListener(new OnCancelListener() {
                        public void onCancel(DialogInterface arg0) {
                            MyAsyncTask.this.cancel(true);
                        }
                    });
                }

                @Override
                protected Void doInBackground(String... params) {
         String url_select = params[0];
                    try {

                        HttpClient httpclient = new DefaultHttpClient();
                        HttpResponse httpResponse = httpclient.execute(new HttpGet(url_select));

                        // receive response as inputStream
                        inputStream = httpResponse.getEntity().getContent();
        //
        //              // Read content & Log
        //              inputStream = httpEntity.getContent();
                    } catch (UnsupportedEncodingException e1) {
                        Log.e("UnsupportedEncodingException", e1.toString());
                        e1.printStackTrace();
                    } catch (ClientProtocolException e2) {
                        Log.e("ClientProtocolException", e2.toString());
                        e2.printStackTrace();
                    } catch (IllegalStateException e3) {
                        Log.e("IllegalStateException", e3.toString());
                        e3.printStackTrace();
                    } 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, "iso-8859-1"), 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("StringBuilding & BufferedReader", "Error converting result " + e.toString());
                    }
                    return null;
                } // protected Void doInBackground(String... params)


                protected void onPostExecute(Void v) {

                    //parse JSON data
                    try{
                        JSONObject jArray = new JSONObject(result);



                        String name = jArray.getString("name");


                              if (name!=null) {


                        Log.w("idname", name);


//
                    myOutWriter.append(name).append("\r\n");
//                  
                        Toast.makeText(getBaseContext(), name, 5).show();
                    }

                        // End Loop

                        this.progressDialog.dismiss();

                    } catch (JSONException e) {

                        Log.e("JSONException", "Error: " + e.toString());

                    } // catch (JSONException e)
               catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }


                } // protected void onPostExecute(Void v)

            } //class MyAsyncTask extends AsyncTask<String, String, Void>

【问题讨论】:

  • 在do inBackground方法中将u改为params[0]
  • onPostExecute 中记录name 并检查logcat
  • @raj 我已经编辑了代码。
  • @jason 为什么在 for 循环 new MyAsyncTask().execute(u); 和这个 new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,u); 中?您可以将 url 数组传递给 doInbackground 并在那里下载数据。无需在 for 循环中调用 execute。您是否还记录了姓名并签入了 logcat?
  • @Raghunandan 对不起先生,我的错误。我没有发布您的代码。它现在已编辑。日志名称正在工作。

标签: android android-asynctask


【解决方案1】:
 for (  j = 0; j < ar.length; j++) {
     u="http://www.example.com/"+ar[j];
     JSONParser jParser=new JSONParser();        
     new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,u);
  }
  try {
       myOutWriter.close();
  } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
  }

在启动 MyAsyncTask 后关闭 myOutWriter。所以当 MyAsyncTask 尝试将数据写入文件时,它会抛出 OutputStreamWriter is closed 异常。

您需要从此处删除关闭 myOutWriter 的代码。在 onPostExecute 末尾添加关闭代码,如下所示:

void onPostExecute(Void v) {
                .....

                } catch (JSONException e) {

                    Log.e("JSONException", "Error: " + e.toString());

                } // catch (JSONException e)
                catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                int count = taskCount.decrementAndGet()
                if(count == 0 ) {
                    try {
                      myOutWriter.close();
                    } catch (IOException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                    }
                }

            } // protected void onPostExecute(Void v)

taskCount的定义是这样的:

AtomicInteger taskCount = new AtomicInteger(ar.length - 1);

最后,我认为 Thread 和 CountDownLatch 是更好的选择

【讨论】:

    【解决方案2】:

    检查实体是否不为空,然后写入数据库

    HttpEntity entity = response.getEntity();
    
    if(entity!=null ){
     inputStream = entity.getContent();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 1970-01-01
      • 2014-04-19
      • 1970-01-01
      • 2014-07-24
      • 1970-01-01
      • 2020-04-03
      相关资源
      最近更新 更多