无法在循环asynctask中将数据保存到txt

时间:2013-12-24 08:54:29

标签: android android-asynctask

我试图在每个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>

2 个答案:

答案 0 :(得分: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就会关闭异常。

您需要从此处删除关闭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是更好的选择

答案 1 :(得分:0)

检查实体是否为null然后写入db

HttpEntity entity = response.getEntity();

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