I'm relatively new to android, and I'm trying to modify an android app such that it downloads a profile picture (preferably in PNG) from a URL, and saves it in the com.companyName.AppName.whatever/files. It should be noted that the app was initially created in Unity, and just built and exported.
Here's my initial code:
URL url = null;
try {
url = new URL(playerDO.getProfileURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
InputStream input = null;
try {
input = url.openStream();
} catch (IOException e) {
e.printStackTrace();
}
String fileName = playerDO.getId() + ".png";
FileOutputStream outputStream = null;
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
byte[] buffer = new byte[256];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT: Here's my other code, as suggested by #Ashutosh Sagar
InputStream input = null;
Bitmap image = null;
try {
input = url.openStream();
image = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String fileName = playerDO.getId() + ".png";
FileOutputStream outputStream = null;
File myDir = getFilesDir();
try {
Log.wtf("DIRECTORY", myDir.toString());
File imageFile = new File(myDir, fileName);
if (!imageFile.exists()){
imageFile.createNewFile();
Log.wtf("ANDROID NATIVE MSG: WARN!", "File does not exist. Writing to: " + imageFile.toString());
}
outputStream = new FileOutputStream(imageFile, false);
image.compress(Bitmap.CompressFormat.PNG, 90, outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
Log.wtf("AWWW CRAP", e.toString());
}
}
(It doesn't write either).
Unfortunately, I've had several problems with this. My primary issue is that when it (on the cases that it does) runs, it actually doesn't save anything. I'll go and check com.companyName.AppName.whatever/files directory only to find no such .png file. I will also need it to overwrite any existing files of the same name, which is hard to check when it doesn't work.
My secondary issue is that it fails to take into account delays in internet connection. Although I've put in enough try-catch clauses to stop it from crashing (as it used to), the end result is that it also doesn't save.
How can I improve upon this? Anything I'm missing?
EDIT:
Printing out the directory reveals it should be in:
/data/user/0/com.appName/files/5965e9e4a0f0463853016e2b.png
However, using ES File explorer, the only thing remotely close to that is
emulated/0/Android/data/com.appName/files/
Are they the same directory?
try this first get bitmap image from url
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
and to save bitmap image please check the ans of GoCrazy
Try this
void getImage(String string_url)
{
//Generate Bitmap from URL
URL url_value = new URL(string_url);
Bitmap image =
BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
//Export File to local Directory
OutputStream stream = new FileOutputStream("path/file_name.png");
/* Write bitmap to file using JPEG or PNG and 80% quality hint for JPEG. */
bitmap.compress(CompressFormat.PNG, 80, stream);
stream.close();
}
Related
I am attempting to save to long term file storage in android as well as create a new file in the process. This code keeps crashing with minimal helpful logcat.
Thanks.
public void save (String text) {
FileOutputStream fos = null;
try {
fos = openFileOutput("logfile.txt", MODE_PRIVATE);
fos.write(text.getBytes());
} catch (FileNotFoundException e)
{} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null)
{
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I expect it to create a file called logfile.txt and print text to it but instead it crashes.
Try something alike this, in order to get a FileOutputStream from a File in tmp / private storage:
// File file = File.createTempFile("logfile", ".txt");
File file = new File(getFilesDir(), "logfile.txt");
FileOutputStream fos = new FileOutputStream(file);
The resulting path should be /data/data/tld.domain.package/files/logfile.txt.
file.getAbsolutePath() has the value.
See Save a file on internal storage.
I have an app who has to download some generated images (PNG).
I tried the standard approach ImageDownloader extends AsyncTask, doInBackground() retrieves the image and the onPostExecute() will try to save it to internal image.
(Part of the) code is below:
public class HandleImages extends AppCompatActivity {
String filename = "";
public boolean saveImageToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public Bitmap retrieveImage(String url){
ImageDownloader task = new ImageDownloader();
Bitmap image = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
try {
image = task.execute(url).get();
} catch (InterruptedException e) {
MainActivity.debb("InterruptedException - " + e.getMessage() + " in " + new Object(){}.getClass().getEnclosingMethod().getName());
e.printStackTrace();
} catch (ExecutionException e) {
MainActivity.debb("ExecutionException - " + e.getMessage() + " in " + new Object(){}.getClass().getEnclosingMethod().getName());
e.printStackTrace();
}
return image;
}
public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
try {
String[] filenames = urls[0].split("/");
filename = filenames[filenames.length-1] + ".jpg";
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
return BitmapFactory.decodeStream(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap != null)
saveImageToInternalStorage(bitmap);
}
}
}
and the error that I get is: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileOutputStream android.content.Context.openFileOutput(java.lang.String, int)' on a null object reference.
It seems that the FileOutputStream fos = openFileOutput(..) fails, but have no idea why.
Also tried to prepend a path (sdCard.getPath() + "/" +) to the filename. As expected it did not make any difference.
Images are ok, I can see them in the browser. Also tried with uploaded images - instead of the generated ones, same result.
This is pretty odd, does anyone have any idea?
Thanks!
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
Hope this function helps you. If this doesn't help feel free to ask
How can I load an image ".jpg for example" as a File ?
To be precise this file was saved using :
public static void saveFile(Context context, Bitmap bitmap, String picName) {
FileOutputStream fileOutputStream;
try {
fileOutputStream = context.openFileOutput(picName, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.JPEG, 30, fileOutputStream);
fileOutputStream.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "file not found");
e.printStackTrace();
} catch (IOException e) {
Log.d(TAG, "io exception");
e.printStackTrace();
}
}
So I only have the name as reference
I tried that :
public static Bitmap loadBitmap(Context context, String picName) {
Bitmap bitmap = null;
FileInputStream fileInputStream;
try {
fileInputStream = context.openFileInput(picName);
bitmap = BitmapFactory.decodeStream(fileInputStream);
fileInputStream.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "file not found");
e.printStackTrace();
} catch (IOException e) {
Log.d(TAG, "io exception");
e.printStackTrace();
}
return bitmap;
}
It works but I need it to be a file
If you wish to work with File objects, I recommend that you do so consistently. Use getFilesDir() or getCacheDir() as the base for building a File of where you want the file to go (e.g., new File(getCacheDir(), picName)). Then, use FileOutputStream and FileInputStream for your I/O, replacing openFileOutput() and openFileInput().
I'm trying to save an audio file to send it to whatsapp, but i am unable to save it on external storage. I am not getting where am I making mistakes.
I am using this code:
FileOutputStream outputStream;
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES), "FUNG");
if (!file.mkdirs()) {}
try {
outputStream = new FileOutputStream(file);
outputStream.write(R.raw.badum2);
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Intent shareIntent = new Intent(Intent.ACTION_SEND);
Uri uri = Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES) + "/FUNG/badum2.m4a");
shareIntent.setType("audio/m4a");
shareIntent.setPackage("com.whatsapp");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(shareIntent);
When the file is sent to WhatsApp, it shows error like:
"fail to share, please try again"
I don't see the audio file in directory, so I guess the error is that I am making some mistakes in saving audio files on external storage.
Please help me in solving this.
I see multiple problems:
(1) if (!file.mkdirs()) {} creates a directory at the path of file, later you use that directory to open an output stream, which of course does not work.
Solution:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES), "FUNG/badum2.m4a"); // assumed target file
if (!file.getParentFile().mkdirs() && !file.getParentFile().isDirectory()) {
// Abort! Directory could not be created!
}
(2) outputStream.write(R.raw.badum2); will write the int value referring
to your resource, not the resource itself.
Solution:
Use InputStream in = ctx.getResources().openRawResource(R.raw.badum2); where ctx is a Context instance (e.g. your Activity) and write its content to the file.
try {
outputStream = new FileOutputStream(file);
try {
InputStream in = ctx.getResources().openRawResource(R.raw.badum2);
byte[] buffer = new byte[4096];
int read;
while ((read = in.read(buffer, 0, buffer.length) >= 0) {
outputStream.write(buffer, 0, read);
}
in.close();
} catch (IOException ex) {
ex.printStackTrace();
}
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I'm trying to load a gif from a url to be displayed in an Imageview, store it in the internal storage and then later read it again. But it refuses to either store the image or reading it, not sure which one because I get no exceptions. Loading the image to the imageview works. The first method below (loadImage())
public Bitmap loadImage(String url){
Bitmap bm = null;
URL request;
try {
if(url!=null){
request = new URL(url);
InputStream is = request.openStream();
bm = BitmapFactory.decodeStream(is);
is.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bm;
}
public String writeGifToInternalStorage (Bitmap outputImage) {
try {
String fileName = String.valueOf(Calendar.getInstance().getTimeInMillis());
ByteBuffer byteBuffer = ByteBuffer.allocate(outputImage.getByteCount());
outputImage.copyPixelsToBuffer(byteBuffer);
byteBuffer.flip();
byte[] data = new byte[byteBuffer.limit()];
byteBuffer.get(data);
FileOutputStream fos = ctx.openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(data);
fos.close();
return fileName;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public Bitmap readFileFromInternalStorage(String filename) {
if (filename == null) return null;
FileInputStream fis;
try {
fis = ctx.openFileInput(filename);
return BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
Any ideas of whats wrong?
Your method readFileFromInternalStorage read an encoded image from the file system. This image file should be what you receive from the server.
For that, you need to save the image when you receive it from the server, for example like so:
InputStream is = new BufferedInputStream(request.openStream());
String fileName = String.valueOf(Calendar.getInstance().getTimeInMillis());
FileOutputStream fos = ctx.openFileOutput(fileName, Context.MODE_PRIVATE);
byte[] buffer = new byte[1024];
int red = 0;
while ((red = is.read(buffer)) != -1) {
fos.write(buffer,0, red);
}
fos.close();
is.close();
Then, your image is saved to the disk, and you can open it using your readFileFromInternalStorage method.
Also, if you use HttpClient instead of URL, I wrote a one-liner for downloading a file: Android download binary file problems