I have a problem trying to get a .png image to my android phone.
I am now this far:
URL url = new URL ("http://oranjelan.nl/oranjelan-bg.png");
InputStream input = url.openStream();
try {
String storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (storagePath + "/oranjelangbg.png");
try {
byte[] buffer = new byte[1000000];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
But I get the following error @ String storagePath = Environment.getExternalStorageDirectory(); The compiller says cannot convert file to string.
Then if i fool around a bit and try this piece of code:
URL url;
void setup() {
try {
URL url = new URL ("http://oranjelan.nl/oranjelan-bg.png");
InputStream input = url.openStream();{
try {
String storagePath = Environment.getExternalStorageDirectory().getName();
OutputStream output = new FileOutputStream (storagePath + "/oranjelangbg.png");
try {
byte[] buffer = new byte[1000000];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
} finally {
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
}
} catch (MalformedURLException ex) {
throw new RuntimeException(ex);
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
}
then my android freezes when I launch the app.
Does anyone have any ideas?
In addition to what Tanis.7x pointed out, you will need to move the network operations out of the UI thread and into something such as an AyncTask. Otherwise you will not be able to interact with the application until it finishes downloading – that may result in an application unresponsive message and a force close. In more recent android versions, doing networking on the main thread is an automatic exception, even if it does not result in delay.