Skip to content

Instantly share code, notes, and snippets.

@viperwarp
Created August 17, 2011 23:57
Show Gist options
  • Save viperwarp/1152961 to your computer and use it in GitHub Desktop.
Save viperwarp/1152961 to your computer and use it in GitHub Desktop.
download and cache menu icons
//Download menu icons
if (menu != null && !menuImageURL.equals("")) {
File cacheDir = new File (ClassificationActivity.this.getCacheDir(), "/ic_menu/");
if (!cacheDir.exists()) cacheDir.mkdirs();
List<String> existingFiles = Arrays.asList(cacheDir.list());
for (int i = 0; i < menu.length(); i++) {
try {
String filename = menu.getJSONObject(i).getString("image");
if (!existingFiles.contains(filename)) {
try {
File file = new File(cacheDir, filename);
/* Open a connection to that URL. */
URL url = new URL(menuImageURL + filename);
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
existingFiles.remove(filename);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (String string : existingFiles) {
File image = new File(cacheDir, string);
image.delete();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment