简体   繁体   English

下载图像并将其保存到SD卡中

[英]downloading and saving image into sd card

I am trying to download and save the image into a sd card and sometimes it work, sometimes it doesn't. 我正在尝试将图像下载并保存到SD卡中,有时它可以工作,有时却不能。 I need help trying to understand why and i tried to google but i couldn't find an answer. 我需要帮助以了解原因,并且尝试使用Google,但找不到答案。

so this is my code to retrieve the magazine issues and then loop through each item in json array then download and store them into the sd card. 所以这是我的代码,用于检索杂志问题,然后循环遍历json数组中的每个项目,然后将其下载并存储到sd卡中。 however some images doesn't get downloaded, it skips instead (view logcat) 但是某些图像没有下载,而是跳过(查看logcat)

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class downloadMagazine extends AsyncTask<String, String, String> {

         @Override
            protected void onPreExecute() {
                super.onPreExecute();
                progressDialog = new ProgressDialog(Store.this);
                progressDialog.setMessage("Loading.." + "\n" + "加载中..");
                progressDialog.setIndeterminate(false);
                progressDialog.setCancelable(false);
                progressDialog.show();
            } 
        /**
         * getting preview url and then load them
         * */
        protected String doInBackground(String... args) {
            URL myFileUrl = null;

            // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                // getting JSON string from URL
                JSONObject json = jParser.makeHttpRequest(url_magazine, "GET", params);

                // Check your log cat for JSON reponse
                //Log.d("All Products: ", json.toString());

                try {
                    // Checking for SUCCESS TAG
                    int success = json.getInt(TAG_SUCCESS);

                    if (success == 1) {
                        // products found
                        // Getting Array of Products
                        mag = json.getJSONArray(TAG_MAGAZINE);

                        for (int i = 0; i < mag.length(); i++) {
                            JSONObject c = mag.getJSONObject(i);

                            // Storing each json item in variable
                            String magazineUrl = c.getString(TAG_MAGAZINE_URL);
                            String issueName = c.getString(TAG_MAGAZINE_NAME);

                            urlList.add(magazineUrl);
                            issueNameList.add(issueName);
                            //System.out.println(urlList);
                        }                   
                    } 
                } catch (JSONException e) {
                    e.printStackTrace();
                }           

                // Building Parameters
                List<NameValuePair> param = new ArrayList<NameValuePair>();
                // getting JSON string from URL
                JSONObject json1 = jParser.makeHttpRequest(urlList.get(pos), "GET", param);

                // CHECKING OF JSON RESPONSE
                Log.d("All guide: ", json.toString());

                try {
                    issues = json1.getJSONArray(TAG_ISSUE);

                    for (int i = 0; i < issues.length(); i++) {
                        JSONObject c = issues.getJSONObject(i);

                        String image = c.getString(TAG_IMAGE);

                        imageList.add(image);
                        //System.out.println(imageList);
                    }   


                    // STOP THE LOOP
                    //break;

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                for (int i = 0; i < imageList.size(); i ++)
                {
                imageUrl = imageList.get(i).toString();
                Log.d("thumbnail", imageUrl);
                number = i;
                try {
                    myFileUrl = new URL(imageUrl);    // RETRIEVE IMAGE URL
                    }
                 catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream in = conn.getInputStream();
                    Log.i("I'm connected", "Download");
                    bmImg = BitmapFactory.decodeStream(in);

                    File filename;
                    // GET EXTERNAL STORAGE, SAVE FILE THERE
                    File storagePath = new File(Environment.getExternalStorageDirectory(),folderName+"issue"+issueNumber+"/");
                    storagePath.mkdirs();

                    filename = new File(storagePath + "/page"+number+".jpg");
                    FileOutputStream out = new FileOutputStream(filename);
                    bmImg.compress(Bitmap.CompressFormat.JPEG, 90, out);

                        out.flush();
                        out.close();

                        MediaStore.Images.Media.insertImage(getContentResolver(),filename.getAbsolutePath(), filename.getName(),
                                filename.getName());          
                        in.close();

                         // displayImage();
                } catch (IOException e) {
                    e.printStackTrace();
                }   
                }

                return null;

}

this is my logcat output whenever it skips download a page (i know it is similar to one of the question i posted but i really do need help in trouble shooting). 每当它跳过下载页面时,这就是我的logcat输出(我知道它与我发布的问题之一相似,但我确实需要在排除故障方面提供帮助)。 I have no idea what happened, i googled and saw that many using android 4.0 onwards have faced this issue 我不知道发生了什么,我在Google上搜索了一下,发现许多使用android 4.0以后的版本都遇到了这个问题

01-23 17:09:29.120: W/System.err(24339): java.io.EOFException
01-23 17:09:29.120: W/System.err(24339):    at libcore.io.Streams.readAsciiLine(Streams.java:203)
01-23 17:09:29.120: W/System.err(24339):    at libcore.net.http.HttpEngine.readResponseHeaders(HttpEngine.java:544)
01-23 17:09:29.120: W/System.err(24339):    at libcore.net.http.HttpEngine.readResponse(HttpEngine.java:784)
01-23 17:09:29.120: W/System.err(24339):    at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:274)
01-23 17:09:29.120: W/System.err(24339):    at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
01-23 17:09:29.130: W/System.err(24339):    at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:270)
01-23 17:09:29.130: W/System.err(24339):    at com.sfcca.coverflow.Store$downloadMagazine.doInBackground(Store.java:881)
01-23 17:09:29.130: W/System.err(24339):    at com.sfcca.coverflow.Store$downloadMagazine.doInBackground(Store.java:1)
01-23 17:09:29.130: W/System.err(24339):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
01-23 17:09:29.130: W/System.err(24339):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-23 17:09:29.130: W/System.err(24339):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-23 17:09:29.130: W/System.err(24339):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
01-23 17:09:29.130: W/System.err(24339):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-23 17:09:29.130: W/System.err(24339):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-23 17:09:29.130: W/System.err(24339):    at java.lang.Thread.run(Thread.java:856)

Check whether you have given appropriate permissions to the manifest 检查您是否已对清单指定了适当的权限

 <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Have a look at this: http://code.google.com/p/google-http-java-client/issues/detail?id=116 看看这个: http : //code.google.com/p/google-http-java-client/issues/detail?id=116

I'd try the LAST comment there and see if the issue goes away: 我会在那儿尝试最后的评论,看看问题是否消失了:

System.setProperty("http.keepAlive", "false"); System.setProperty(“ http.keepAlive”,“ false”);

Now, you may not necessarily want that setting in the long term, but at least see if that's related. 现在,您可能不一定要长期使用该设置,但至少要看看是否相关。

And note that even though this question refers to Spring and a bunch of other stuff, it seems like the same root problem: Spring Rest Template usage causes EOFException 并且请注意,即使这个问题涉及Spring和其他许多东西,也似乎是相同的根本问题: Spring Rest Template的使用会导致EOFException

Lastly, I'm not exactly sure what you are trying to do there, but with one AsyncTask doing a lot of work (and not really dealing with contingencies like the network going away, and more) but you could get into trouble several others ways there (unrelated to your question). 最后,我不确定您要在其中做什么,但是使用一个AsyncTask要做很多工作(并不能真正处理诸如网络中断之类的突发事件,等等),但是您可能会遇到其他几种麻烦在那里(与您的问题无关)。 You might also want to consider a general purpose image download/cache library, if that might help, such as https://github.com/koush/UrlImageViewHelper . 如果可能有用,您可能还想考虑使用通用图像下载/缓存库,例如https://github.com/koush/UrlImageViewHelper Even if you don't use one of those, digging through the source a bit you may see how they're making things a bit more robust. 即使您不使用其中之一,也可以仔细研究一下源代码,您可能会发现它们如何使事情变得更强大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM