无法保存循环的AsyncTask数据为txt [英] unable to save data to txt in loop asynctask

查看:109
本文介绍了无法保存循环的AsyncTask数据为txt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每一个输出数据的AsyncTask保存每个HTTP call.But我无法看到提前在file.I真的AP preciate任何数据的help.Thanks。

 最终的String [] = AR {1,2,3,.............,25}        文件名=test_file里面;
            MYFILE =新的文件(/ SD卡/+文件名);
                 尝试{
                        myFile.createNewFile();
                    FOUT =新的FileOutputStream(MYFILE);
                }赶上(FileNotFoundException异常E1){
                    e1.printStackTrace();
                }赶上(IOException异常五){
                    e.printStackTrace();
                }
                 myOutWriter =新OutputStreamWriter(FOUT);
                         为(J = 0; J< ar.length; J ++){
                                 U =htt​​p://www.example.com/+ AR [J]。                                JSONParser jParser =新JSONParser();
             新MyAsyncTask()executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,U)。                        }
                               尝试{
                            myOutWriter.close();
                        }赶上(IOException异常五){
                            // TODO自动生成catch块
                            e.printStackTrace();
                        }    }
            类MyAsyncTask扩展的AsyncTask<字符串,字符串,太虚> {                私人ProgressDialog progressDialog =新ProgressDialog(MainActivity.this);
                为InputStream的InputStream = NULL;
                字符串结果=;                在preExecute保护无效(){
                    progressDialog.setMessage(下载您的数据......);
                    progressDialog.show();
                    progressDialog.setOnCancelListener(新OnCancelListener(){
                        公共无效onCancel(DialogInterface为arg0){
                            MyAsyncTask.this.cancel(真);
                        }
                    });
                }                @覆盖
                保护无效doInBackground(字符串... PARAMS){
         串url_select =参数[0];
                    尝试{                        HttpClient的HttpClient的=新DefaultHttpClient();
                        HTT presponse HTT presponse = httpclient.execute(新HTTPGET(url_select));                        //接收响应为InputStream的
                        的InputStream = HTT presponse.getEntity()的getContent()。
        //
        // //读取内容和放大器;日志
        //为InputStream = httpEntity.getContent();
                    }赶上(UnsupportedEncodingException E1){
                        Log.e(UnsupportedEncodingException,e1.toString());
                        e1.printStackTrace();
                    }赶上(ClientProtocolException E2){
                        Log.e(ClientProtocolException,e2.toString());
                        e2.printStackTrace();
                    }赶上(E3 IllegalStateException异常){
                        Log.e(IllegalStateException异常,e3.toString());
                        e3.printStackTrace();
                    }赶上(IOException异常E4){
                        Log.e(IOException异常,e4.toString());
                        e4.printStackTrace();
                    }
                    //转换使用字符串构建器响应字符串
                    尝试{
                        面包屑的BufferedReader =新的BufferedReader(新的InputStreamReader(InputStream中,ISO-8859-1),8);
                        StringBuilder的sBuilder =新的StringBuilder();                        串线= NULL;
                        而((行= bReader.readLine())!= NULL){
                            sBuilder.append(行+\\ n);
                        }                        inputStream.close();
                        结果= sBuilder.toString();                    }赶上(例外五){
                        Log.e(StringBuilding&安培; BufferedReader中,错误转换结果+ e.toString());
                    }
                    返回null;
                } //保护无效doInBackground(字符串... PARAMS)
                保护无效onPostExecute(虚空V){                    //解析JSON数据
                    尝试{
                        JSONObject的jArray =新的JSONObject(结果);                        字符串名称= jArray.getString(名称);
                              如果(名字!= NULL){
                        Log.w(idname,名);
//
                    myOutWriter.append(名称).append(\\ r \\ n);
//
                        Toast.makeText(getBaseContext(),名称,5).show();
                    }                        //结束循环                        this.progressDialog.dismiss();                    }赶上(JSONException E){                        Log.e(JSONException,错误:+ e.toString());                    } //赶上(JSONException E)
               赶上(IOException异常五){
                        // TODO自动生成catch块
                        e.printStackTrace();
                    }
                } //保护无效onPostExecute(虚空V)            } //类MyAsyncTask扩展的AsyncTask<字符串,字符串,太虚>


解决方案

 为(J = 0; J< ar.length; J ++){
     U =htt​​p://www.example.com/+ AR [J]。
     JSONParser jParser =新JSONParser();
     新MyAsyncTask()executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,U)。
  }
  尝试{
       myOutWriter.close();
  }赶上(IOException异常五){
       // TODO自动生成catch块
       e.printStackTrace();
  }

您关闭开始MyAsyncTask后myOutWriter。所以,当MyAsyncTask尝试将数据写入文件时,它抛出OutputStreamWriter是封闭的例外。

您需要从这里取出接近myOutWriter的code。添加在onPostExecute像下面的末尾添加接近code:

 无效onPostExecute(虚空V){
                .....                }赶上(JSONException E){                    Log.e(JSONException,错误:+ e.toString());                } //赶上(JSONException E)
                赶上(IOException异常五){
                    // TODO自动生成catch块
                    e.printStackTrace();
                }                诠释计数= taskCount.decrementAndGet()
                如果(计数== 0){
                    尝试{
                      myOutWriter.close();
                    }赶上(IOException异常五){
                      // TODO自动生成catch块
                      e.printStackTrace();
                    }
                }            } //保护无效onPostExecute(虚空V)

taskCount的定义是这样的:

 的AtomicInteger taskCount =新的AtomicInteger(ar.length  -  1);

最后,我想线程和CountDownLatch是更好的选择。

I am trying to save every output data in asynctask for each http call.But I am unable to see any data in a file.I really appreciate any help.Thanks in Advance.

     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>

解决方案

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

You close the myOutWriter after start MyAsyncTask. So when MyAsyncTask try to write data to file, it throw OutputStreamWriter is closed exception.

You need remove the code of close myOutWriter from here. Add add close code at the end of onPostExecute like below:

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)

the definition of taskCount is like this:

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

At last, I think Thread and CountDownLatch is better option

这篇关于无法保存循环的AsyncTask数据为txt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆