5

Im my app when the splash screen gets started I am just hitting an URL and getting back an XML file. From that XML file i am parsing out data such as an user name, id and an URL to download an image. From that url i want to download an image and i want to store the image in a particular name in my app itself.I want to use the same image as a background in another activity. How can i download and store the image in my app. Where can it be stored in my app, either in raw folder or in drawable.

Before storing the name how come the image can be set as a background image in the particular activity, Please help me friends

Andro Selva
  • 53,910
  • 52
  • 193
  • 240
Siva K
  • 4,968
  • 14
  • 82
  • 161

2 Answers2

4

This is the code to download your image from an url :

InputStream in = new URL(image_url).openConnection().getInputStream();
Bitmap bm = BitmapFactory.decodeStream(in);

Note that it should be done asynchronously (like in an asynctask)

Than you can store the Bitmap on the system using:

File fullCacheDir = new File(Environment.getExternalStorageDirectory(),cacheDir);
String fileLocalName = name+".JPEG";
File fileUri = new File(fullCacheDir, fileLocalName);
FileOutputStream outStream = null;
outStream = new FileOutputStream(fileUri);
image.compress(Bitmap.CompressFormat.JPEG, 75, outStream);
outStream.flush();

Note that this is just an example on how to store your image and there is other ways. You should look at documentation anyway.

plus-
  • 45,453
  • 15
  • 60
  • 73
  • 1
    Just a minor. There's really no need to invoke `toString` on `File`. The `File` class has a constructor that looks like `File(File parent, String child)` – Kaj Jul 08 '11 at 06:49
1

If you want it for your application. Better download the image save it as Drawable instance and use it in your application where you want

public static Drawable drawable = null;

//get image from URL and store it in Drawable instance

public void getImageFromURL(final String urlString) {

    Thread thread = new Thread() {
        @Override
        public void run() {
            //TODO : set imageView to a "pending" image
            InputStream is = null;
            try{
            URLConnection urlConn = new URL(urlString).openConnection();

            is= urlConn.getInputStream();
            }catch(Exception ex){}
            drawable = Drawable.createFromStream(is, "src");


        }
    };
    thread.start();
}

set Background image to any view

void setImage(View myView){
    myView.setBackgroundDrawable(drawable);
}
Rajat
  • 1,449
  • 5
  • 20
  • 33