Best way to download images from XML content

2019-08-27 16:02发布

问题:

I am designing an Android application which will be displaying some news that will be retrieved from a remote URL in xml format, say http://adomain/latest.xml

The XML file has the following format:

<articles>
<article>
    <id>6</id>
    <title>A sample title</title>
    <image>http://adomain/images/anImage.jpg</image>
    <lastupdate>1326938231</lastupdate>
    <content><![CDATA[Sample content]]></content>
</article>
...
</articles>

I have created an Updater Service which listens to Connectivity Changes and when the system has a connection over the internet, it tries to download the xml file. Then parse it and save data. The Updater runs on a separate thread, every 10 minutes.

My question is: What is the best way to handle the images?

a) Should I perform lazy loading on images when a news item is displayed

OR

b) Should I download the image when I parse the xml file?

回答1:

I recommend lazy loading as the news item is displayed, so you don't use excessive bandwidth (and potentially cost for the user). No point in downloading images if the user never wants to look at them.



回答2:

for images, I think you always follow lazy loading because, image loading may take some time, and also an efficient lazy loader can help you to avoid any future memory issue.



回答3:

Just fetch <Image> tag data from your XMl.

String imgURL  = your <Image> value;  

 ImageView  imageView = new ImageView(this);

                Bitmap  bmp = BitmapFactory.decodeStream(new java.net.URL(imgURL).openStream());

                    imageView.setId(i);
                    imageView.setImageBitmap(bmp);

This will work to set image and you also get image in "bmp".

Android provide directly show image from URL:

For Store Image to Sd Card:

File file = new File (pathOfSdCard, iamgeName);

try {                      
    file.createNewFile();
    FileOutputStream out = new FileOutputStream(file);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 10, out);
                out.flush();
                out.close();

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

Put Line to your AndroidMenifest:

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

This all i using in my app. it works fine.

I hope this will helps you a lot.