Display an image even after the user has closed the app - android

How do I load the same picture the user has selected even after the user closes the app?
I currently have the following code which I call in onCreate, but the Bitmap is null every time the user closes the app.
private void loadImageFromStorage() {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File myPath = new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
File f = new File(directory.getAbsolutePath(), "profile.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView coverView = findViewById(R.id.cover_view);
coverView.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Assuming the image was actually saved as profile.jpg and it exists in the imageDir folder, all you need to do to load the image (based on your current usage) is:
private void loadImageFromStorage() {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File myFile = new File(directory.getAbsolutePath(),"profile.jpg");
if(myFile.exists()){
try {
Bitmap b = BitmapFactory.decodeFile(myFile.getAbsolutePath());
ImageView coverView = findViewById(R.id.cover_view);
coverView.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.d("MyApp", "The image file does not exist.");
}
}
But if the image is not yet saved or non-existence, then you may need to ask another question that details how you are currently doing it. But this setup will allow you know if that image actually existts.

Related

Android Studio : How to save text files from EditText into a specific directory

I am currently making a journal app, so the users type their entry into an EditText and it saves in their phone and they can load it up later. At first I used just getFilesDir() but recently there is this weird rList file that shows up every time I open the app and I couldn't figure it out(I wrote a question about it). So now I want to save these files in this specific directory called TextEntries
Here is the code for my save funcction:
public void save(View v) {
textFile = inputTitle.getText().toString();
String text = inputFeelings.getText().toString();
FileOutputStream fos = null;
try {
String rootPath = getFilesDir().getAbsolutePath() + "/TextEntries/";
File root = new File(rootPath);
if (!root.exists()) {
root.mkdirs();
}
fos = openFileOutput(textFile, MODE_PRIVATE);
fos.write(text.getBytes());
inputFeelings.getText().clear();
Toast.makeText(this, "Saved to " + getFilesDir() + "/TextEntries/" + textFile,
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
All help is welcome and thank you in advance.
replace
openFileOutput(textFile, MODE_PRIVATE);
with
new FileOutputStream(rootPath + textFile)

(android) how to overwrite image on DCIM folder?

I already have a resized bitmap object.
with this bitmap, how can i overwrite this bitmap in DCIM folder??
I know that I should change the bitmap into File object...
please help me
(Assume that i also have the absolute path)
I tried this with the code below.
It creates a new file only if a file with same name doesn't exist.
Otherwise, it doesn't create a new file.
private void SaveBitmapToFileCache(Bitmap bitmap, String strFilePath) {
File fileCacheItem = new File(strFilePath);
OutputStream out = null;
try
{
fileCacheItem.createNewFile();
out = new FileOutputStream(fileCacheItem);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Try something like this:
//File file= new File("FilePath"+ "/myfolder/myimage.jpg");
if(fileCacheItem .exists())
{
file.delete();
}

android-how to save a view to sd card

i have a imageview , i am trying to save bitmap from imageview by this method
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
the rgb of saved image is not like that it looks in running app,so i am wondering if there is any way to save image view directly to a sd card rather getting the bitmap and then save it to sd card.
please help me i have tried everything.
You can read and write object using below code :
public static void witeObjectToFile(Context context, Object object, String filename)
{
ObjectOutputStream objectOut = null;
try
{
FileOutputStream fileOut = context.openFileOutput(filename, Activity.MODE_PRIVATE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(object);
fileOut.getFD().sync();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if (objectOut != null)
{
try
{
objectOut.close();
} catch (IOException e)
{
// do nowt
}
}
}
}
public static Object readObjectFromFile(Context context, String filename)
{
ObjectInputStream objectIn = null;
Object object = null;
try
{
FileInputStream fileIn = context.getApplicationContext().openFileInput(filename);
objectIn = new ObjectInputStream(fileIn);
object = objectIn.readObject();
} catch (FileNotFoundException e)
{
// Do nothing
} catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
} finally
{
if (objectIn != null)
{
try
{
objectIn.close();
} catch (IOException e)
{
// do nowt
}
}
}
return object;
}
For example ArrayList can be saved as :
ImageView abcImage = (ImageView) readObjectFromFile(context, AppConstants.FILE_PATH_TO_DATA);
and write as :
witeObjectToFile(context, abcImage, AppConstants.FILE_PATH_TO_DATA);
Try to use this
public void onClick(View v) {
if (v.getId() == R.id.btnSaveImage) {
imageView.setDrawingCacheEnabled(true);
Bitmap bm = imageView.getDrawingCache();
storeImage(bm);
}
}
private boolean storeImage(Bitmap imageData) {
// get path to external storage (SD card)
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/yourappname/";
File sdIconStorageDir = new File(iconsStoragePath);
// create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
File file = new File(sdIconStorageDir.toString() + File.separator + "fileName");
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
imageData.compress(CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
MediaScannerConnection.scanFile(this, new String[] { file.getPath() },
new String[] { "image/jpeg" }, null);
Toast.makeText(this, "Snapshot Saved to " + file, Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}

displaying downloaded images in my phone gallery

I'm trying to tell my app to make some images which are already downloaded appear in the gallery of my phone.
the images are well download and displayed in my app, they have no extension, their names are only a md5.
here is how i'm trying to do so:
public static void makePhotoAppearOnGallery(Activity activity, String md5) {
final String extStorageDirectory = Environment
.getExternalStorageDirectory().toString();
final String festivalDirectory_path = extStorageDirectory
+ Constants.IMAGES_STORAGE_PATH;
File imageOutputFile = new File(festivalDirectory_path, "/");
if (imageOutputFile.exists() == false) {
imageOutputFile.mkdirs();
}
File imageFile = new File(imageOutputFile, md5);
Bitmap bm = decodeFile(imageFile.getAbsoluteFile());
OutputStream outStream = null;
try {
outStream = new FileOutputStream(imageFile);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
MediaStore.Images.Media.insertImage(activity.getContentResolver(), festivalDirectory_path, festivalDirectory_path+"/"+md5, "myDownloadedPics");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
scanFile(imageFile,activity);
}
public static void scanFile(File downloadedFile, Context mContext){
Uri contentUri = Uri.fromFile(downloadedFile);
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
mediaScanIntent.setData(contentUri);
mContext.sendBroadcast(mediaScanIntent);
}
the app crashes on this line:
MediaStore.Images.Media.insertImage(activity.getContentResolver(), festivalDirectory_path, festivalDirectory_path+"/"+md5, "myDownloadedPics");
with this message:
java.io.FileNotFoundException: /mnt/sdcard/data/com.example.app/images: open failed: EISDIR (Is a directory)
Does anyone know from what it comes?
I had the same problem. It turns out this error happens when there is a folder with the same file name. For example I had a folder named "log.txt".

saving file on sd card, writes file size 0

I have trouble with saving images on sd card. I can see the file on the sd card but file is empty (size 0). I tried saving it on the phone memory and it works fine. Here is my code.
Imagewritter {
public static boolean writeAsJPG(Context context, Bitmap bitmap,
String filename) {
filename = filename + ".jpg";
File path = Environment.getExternalStorageDirectory();
File f = new File(path, filename);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
fos = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, "file not found");
return false;
}
bitmap.compress(CompressFormat.JPEG, quality, fos);
try {
fos.flush();
fos.close();
} catch (IOException e) {
Log.d(TAG, "error closing");
e.printStackTrace();
}
}
here is the code where the bitmap comes from.
DrawingView = (drawing) findViewById(R.id.drawing_view);
drawingBitmap = (Bitmap) DrawingView.getBitmap();
String idName = timeStampText;
//save Image as JPG
ImageWritter.writeAsJPG(getApplicationContext(), drawingBitmap, idName);
i think u have to add these permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Get the image in byte array & check the size of that byte array.. I think you getting 0 size byte array.....
The only problem here is that I have two lines for writing the file. Using FileOutputStream and OpenFileOutput. Just remove these lines and it'll be fine.
try {
fos = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, "file not found");
return false;
}

Categories

Resources