Android . Where to save downloaded images? - java

In my application I have several images in drawable folder. That makes apk big. Now I have uploaded them in my Google drive and when the user will connect to the internet it will download that images from drive. Where to save that downloaded images? in external storage , in database or in other place? I want that the user couldn't delete that images.

You can store them in Internal phone memory.
To save the images
private String saveToInternalSorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("youDirName", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"img.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);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return directory.getAbsolutePath();
}
To access the stored file
private void loadImageFromStorage(String path)
{
try {
File f = new File(path, "img.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
// here is the retrieved image in b
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
EDIT
You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed.
For more information Internal Storage

I want that the user couldn't delete that images
You can't really do that. Images weren't here unless user selected them so why you do not want to let user delete them? in such case you will download it again or ask user to select. normal "cache" scenario. Not to mention you are in fact unable to protect these images as user can always clear app data (including databases and internal storage).

Related

Why Isn't My FileOutputstream Writing to a File?

I'm a beginner working on an Android app that uses the gcacace SignaturePad library to capture the signature of my user. My goal is to take the signature, compress it down into a JPEG, and then write that information to a file on the users phone so the picture can be accessed later.
I am currently getting no errors or crashes when I run the code, yet no directory or file is being created when I test the app out on my device(Google Pixel 2). Can anyone give me a hand figuring out where the problem is? I've thrown my head against a wall this entire morning and still don't know.
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("images", Context.MODE_PRIVATE);
if (!directory.exists()) {
directory.mkdirs();
}
File myPath = new File(directory, "1.jpg");
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(myPath);
} catch (Exception e) {
e.printStackTrace();
}
signaturePad.getSignatureBitmap().compress(Bitmap.CompressFormat.JPEG, 90, fOut);
Bitmap signature = signaturePad.getSignatureBitmap();
int bytes = signature.getByteCount();
try {
fOut.write(bytes);
fOut.flush();
fOut.close();
} catch (IOException ex) {
ex.printStackTrace();
}
Toast.makeText(activity_signature_pad.this, "Signature Saved", Toast.LENGTH_SHORT).show();
The code in your question writes to what the Android SDK refers to internal storage. That is private to your app; ordinary users do not have access to it (including you, except when using developer tools).
You appear to want to write to external storage. For that, use:
File directory = new File(getExternalFilesDir(null), "images")

Problem saving image in external storage on android

I am writing a camera application for the android platform. I am using the CameraKitView Library for producing my camera view. Everything else including accessing the camera is working as expected except for actually capturing and saving the image. minimum sdk is 15 and target sdk and compile sdk is 28. The code for saving the image is as shown below
cameraKitView.captureImage(new CameraKitView.ImageCallback() {
#Override
public void onImage(CameraKitView cameraKitView, byte[] photo) {
File savedPhoto = new File(Environment.getExternalStorageDirectory(), "pchk.jpg");
try{
FileOutputStream outputStream = new FileOutputStream(savedPhoto.getPath());
outputStream.write(photo);
outputStream.close();
}catch (java.io.IOException e){
e.printStackTrace();
}
}
});
Thank you in advance for your assistance
First of all verify that your file or folder where you want to save a file is exists or not, if not create them
capturedFolderPath is a path of the folder where you want to create the file
File folderFile = new File(capturedFolderPath)
if (!folderFile.exists()) {
folderFile.mkdirs();
}
String imageNameToSave = "xyz.jpg";
String imagePath = capturedFolderPath
+ File.separator + imageNameToSave + ".jpg";
File photoFile = new File(imagePath);
if (!photoFile.exists()) {
photoFile.createNewFile();
}
after creating write the bytes on the file like this
FileOutputStream outputStream = new FileOutputStream(photoFile);
outputStream.write(bytes);
outputStream.close();

How to create a file in external storage and set permission programmatically

I am trying to have a local backup of a database of my app in the device storage. I created a backup file/directory, but I want user to restrict from being able to copy/delete the file/directory from the device.
Is it possible to achieve this through code, using a service which I am running?
Method to check if user has permissions to write on external storage or not.
public static boolean canWriteOnExternalStorage() {
// get the state of your external storage
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// if storage is mounted return true
Log.v(“sTag”, “Yes, can write to external storage.”);
return true;
}
return false;
}
and then let’s use this code to actually write to the external storage:
// get the path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + “/your-dir-name/”);
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
File file = new File(dir, “My-File-Name.txt”);
FileOutputStream os = outStream = new FileOutputStream(file);
String data = “This is the content of my file”;
os.write(data.getBytes());
os.close();
You need the following permission
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />
Happy coding!!

What folder should I store text files?

I have my classes in /src/com.example.myapp/ and I have a text mytext.txt there too.
However, when I reference static File f = new File("mytext.txt")); it does not find it, even though the file is in the same directory as the class.
What do I need to do? What directory is it actually looking in?
Assets is read-only. I need somewhere where I can read and update the text file.
Use an assets folder.
Here is an example...
Loading array from a text file in assets folder (Android)
You create the assets folder in your root project folder then place your file in it. Once it's there, you access this way:
getAssets().open("file.txt");
the getAssets method is part of your Activity / Context. Context carriers a lot of the information about your app.
If you are not in an Activity, you can pass the Context to your class and use this:
context.getAssets().open("file.txt");
If you want the file with EDIT mode, you can use Internal/External Storage
Then you can read it as:
String filePath = context.getFilesDir().getAbsolutePath(); //returns current directory.
File file = new File(filePath, fileName);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
}
return text.toString(); //the output text from file.
You can even write to this file :
String filename = "myfile";
String string = "ur data";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Hope it will help you ツ
Use the assets directory:
assets/
This is empty. You can use it to store raw asset files. Files that you save here are compiled into an .apk file as-is, and the original filename is preserved. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager. For example, this is a good location for textures and game data.

Save picture while Camera is in stopPreview mode

BACKGROUND
Hey so I have a camera that I have implemented myself in code. This means I access and control the camera hardware and use it to save pictures. I can save the picture using the Camera.takePicture() function when the camera is running: running means Camera.startPreview();
PROBLEM
My problem is that I want to be able to save the image also when the camera image is frozen: frozen is when Camera.stopPreview(); is called.When frozen I can see the image in my layout but how do I access it? Where is the image saved so that I might be able to modify it later?
Thanks in advance!
------------------Update 1
jpeg bla;
public class jpeg implements PictureCallback{
public void onPictureTaken(byte[] data, Camera camera) {
g_data = data;
}
}
This is part of my code. Here I am trying to write the data that would originally be saved to a global variable. However the value of g_data remains null and I am unable to set a breakpoint inside the onPictureTaken() call back function.
------------------Update 2
FileOutputStream outStream = null;
try {
// generate the folder
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MirrorMirror");
if( !imagesFolder.exists() ) {
imagesFolder.mkdirs();
}
// generate new image name
SimpleDateFormat formatter = new SimpleDateFormat("HH_mm_ss");
Date now = new Date();
String fileName = "image_" + formatter.format(now) + ".jpg";
// create outstream and write data
File image = new File(imagesFolder, fileName);
outStream = new FileOutputStream(image);
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) { // <10>
//Toast.makeText(ctx, "Exception #2", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {}
I used this code previously to save the file from the camera onPictureTaken() function. The key here is the byte[] data which I need to save and save later. However like I said I just get a null when I check it in the debugger.
Camera.takePicture never looks at the view you specified as previewDisplay. Actually, it isn't an ImageView, but a SurfaceView, and there are no API to read pixels from it.
You can call takePicture() preemptively just before you stopPreview(). Later, if you find out that you don't need the picture, just discard it.
Ok so the exact way to do this is to take the picture just before stopPreview() and save it to a temporary file. Actually with this implementation you never call stopPreview()(otherwise it will crash) since the takePicture() function stops the preview automatically.
try {
File temp = File.createTempFile("temp", ".jpg");
} catch (IOException e) {
e.printStackTrace();
}
Now that we have the temporary file saved we will access it later and move it to our new desired file location.
How to copy file.
temp.deleteOnExit();
be sure to call deleteonExit() so that Android deletes the file after the app is closed(if so desired).

Categories

Resources