Caching exisiting files - android

I have the following code:
file = new File(getRealPathFromURI(uri));
How am I able to store this in the cache with a name so I can then access it later on?
I know there are methods such as File outputDir = context.getCacheDir();
File outputFile = File.createTempFile("prefix", "extension", outputDir);
But I don't understand how I can store this file in the cache with a specific name so then at a further date I can do file = new File(getActivity().getCacheDir(), "storedFileName"); in other activitys.
Any guidance would be great, thanks.
EDIT:
Here is my main activity where I get a pic from the gallery and it is returned as a uri in the onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
Intent i = new Intent(getApplicationContext(),
sliding_menu.class);
File file = new File(selectedImage.getPath());
ObjectOutput out;
try {
String filenameOffer="Image";
out = new ObjectOutputStream(new FileOutputStream(new File
(getCacheDir(),"")+filenameOffer));
out.writeObject(file);
out.close();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
startActivity(i);
}
}
}
As you can see, I am trying to make the Uri of the selected image, then make it into a file.
Then I am trying to store the file in the cache so I can then further retrieve it throughout my application.
Here is the next activity where I am trying to access the file:
try {
String filename="Image";
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(new File(
getActivity().getCacheDir(),"")+filename)));
String res = (String) in.readObject();
Picasso.with(getActivity().getApplication()).load((res))
.into(mImageView);
} catch (Exception e) {
}
But the image isn't loading. What can I change to make this work?

Example with a .png file
Save File:( InputStream = from internet )
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "MyApp/" + fileName );
if (!f.exists())
{
f.getParentFile().mkdirs();
f.createNewFile();
}
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
Read File:
File path = new File(Environment.getExternalStorageDirectory(),"MyApp/" + fileName);
if(path.exists())
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(path.getAbsolutePath(), options);
}

To store your data on cache file you can use,
Suppose response is string which you want to store in cache.
ObjectOutput out;
try {
String filenameOffer="cacheFileSearch.srl";
out = new ObjectOutputStream(new FileOutputStream(new File
(getActivity().getCacheDir(),"")+filenameOffer));
out.writeObject( response );
out.close();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
And for getting data back from cache file,
try {
String filename="cacheFileSearch.srl";
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(new File(
getActivity().getCacheDir(),"")+filename)));
String res = (String) in.readObject();
} catch (Exception e) {
AppConstant.isLoadFirstTime=true;
}
And for deleting file, you can use
String filename="cacheFileSearch.srl";
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(new File(
getActivity().getCacheDir(),"")+filename)));
File dir = getActivity().getCacheDir();
if (dir.isDirectory()) {
if (new File(new File(dir, "")+filename).delete()) {
}
}
in.close();
} catch (Exception e) {
}

Related

How to create folder in internal storage and save captured image

I want to capture image and save it to specific folder in internal storage. Currently i am able to open intent and get thumbnail of captured image. I dont want to user extrnal stotage as now mostly users use their internal storage and not sd card.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null){
startActivityForResult(intent,1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK){
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
LayoutInflater inflater = LayoutInflater.from(LeaveApplicationCreate.this);
final View view = inflater.inflate(R.layout.item_image,attachView, false);
ImageView img = view.findViewById(R.id.img);
AppCompatImageView btnRemove = view.findViewById(R.id.btnRemove);
img.setImageBitmap(imageBitmap);
btnRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
attachView.removeView(view);
}
});
attachView.addView(view);
File directory = new File(Environment.getExternalStorageDirectory(),"/Digimkey/Camera/");
if (!directory.exists()) {
directory.mkdir();
}
File file = new File(directory, System.currentTimeMillis()+".jpg");
try (FileOutputStream out =new FileOutputStream(file)) {
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (IOException e) {
e.printStackTrace();
}
}
}
First gain Write Permissions.
File directory = new File(Environment.getExternalStorageDirectory(), dirName);
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(directory, fileName);
if (!file.exists()) {
file.createNewFile();
}
try (FileOutputStream out =new FileOutputStream(file)) {
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (IOException e) {
e.printStackTrace();
}
There are two types of storage.
1) Internal ex. "/root/.."
Unless you have rooted device, we can't access. this path.
2) External ex. "/storage/emuated/0"
Environment.getExternalStorageDirectory()
By using this path, we are able to create a directory/file.
Use to method to save your bimap in local storage. Pass bimap image as parameter i.e saveToInternalStorage(imageBitmap)
private String saveToInternalStorage(Bitmap bitmapImage){
//set image saved path
File storageDir = new File(Environment.getExternalStorageDirectory()
+ "MyApp"+ "/Files");
if (!storageDir.exists()) {
storageDir.mkdirs();
}
File mypath=new File(storageDir,"bitmap_image.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
Required permissions in Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Sending GIF image in asset folder to another application using Intent

How do we send GIF image which is present in asset folder to another application using Intent?
I have tried this:
private File getEmojiFile(int position) {
AssetManager assetManager = getApplicationContext().getAssets();
File file = new File(getCacheDir(), mEmojiFileNames[position]);
try {
if (!file.createNewFile()) {
//Emoji File already exists.
return file;
}
} catch (IOException e) {
e.printStackTrace();
}
FileChannel in_chan = null, out_chan = null;
try {
AssetFileDescriptor in_afd = assetManager.openFd(mEmojiFileNames[position]);
FileInputStream in_stream = in_afd.createInputStream();
in_chan = in_stream.getChannel();
FileOutputStream out_stream = new FileOutputStream(file);
out_chan = out_stream.getChannel();
in_chan.transferTo(in_afd.getStartOffset(), in_afd.getLength(), out_chan);
} catch (IOException ioe) {
Log.w("copyFileFromAssets", "Failed to copy file '" + mEmojiFileNames[position] + "' to external storage:" + ioe.toString());
} finally {
try {
if (in_chan != null) {
in_chan.close();
}
if (out_chan != null) {
out_chan.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return file;
}
and then sending it to another app using Intent:
final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
EMOJI_IMAGE_TYPE emojiImageType = getImageType(position);
intent.setType("image/gif"));
intent.setPackage(getCurrentAppPackage(SoftKeyboard.this, getCurrentInputEditorInfo()));
PackageManager packageManager = getPackageManager();
if (intent.resolveActivity(packageManager) != null) {
//Save emoji file because current input field supports GIF/PNG.
File emojiFile = getEmojiFile(position);
Uri photoURI = FileProvider.getUriForFile(SoftKeyboard.this, SoftKeyboard.this.getApplicationContext().getPackageName() + ".provider", emojiFile);
intent.putExtra(Intent.EXTRA_STREAM, photoURI);
dialog.dismiss();
hideWindow();
try {
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(SoftKeyboard.this,"This text field does not support "+
"GIF"+" insertion from the keyboard.",Toast.LENGTH_LONG).show();
}
However, after this blank image is coming. Here is tried to send the image to messenger application. It accepted intent but showed blank transparent image:
Scenario: You have a gif file in the Drawable Folder.
Then the code will be:`
private void shareDrawable(Context context,int resourceId,String fileName) {
try {
//create an temp file in app cache folder
File outputFile = new File(context.getCacheDir(), fileName + ".gif");
FileOutputStream outPutStream = new FileOutputStream(outputFile);
//Saving the resource GIF into the outputFile:
InputStream is = getResources().openRawResource(resourceId);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int current = 0;
while ((current = bis.read()) != -1) {
baos.write(current);
}
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(baos.toByteArray());
//
outPutStream.flush();
outPutStream.close();
outputFile.setReadable(true, false);
//share file
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(outputFile));
shareIntent.setType("image/gif");
context.startActivity(shareIntent);
}
catch (Exception e) { Toast.makeText(context, "error", Toast.LENGTH_LONG);}
}

Image not saving in folder

I am trying to create a folder and save images in it.
But it's not working.
I don't know what's wrong in my code - can you tell me why?
// The method that invoke of uploading images
public void openGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
File folder = new File(this.getExternalFilesDir(
Environment.DIRECTORY_PICTURES), "albumName");
File file = new File(this.getExternalFilesDir(
Environment.DIRECTORY_PICTURES), "fileName"+3);
Bitmap imageToSave = (Bitmap) data.getExtras().get("data");
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Uri selectedImage = data.getData();
Intent i = new Intent(this,
AddImage.class);
i.putExtra("imagePath", selectedImage.toString());
startActivity(i);
}
edit
final File path =
Environment.getExternalStoragePublicDirectory
(
// Environment.DIRECTORY_PICTURES + "/ss/"
//Environment.DIRECTORY_DCIM
Environment.DIRECTORY_DCIM + "/MyFolderName/"
);
// Make sure the Pictures directory exists.
if(!path.exists())
{
path.mkdirs();
}
Bitmap imageToSave = (Bitmap) data.getExtras().get("data");
final File file = new File(path, "file" + ".jpg");
try {
FileOutputStream fos = new FileOutputStream(path);
final BufferedOutputStream bos = new BufferedOutputStream(fos, 8192);
FileOutputStream out = new FileOutputStream(path);
//fos = new FileOutputStream(path);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, fos);
// imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
How I do make the folder in DCIM and create a file there into:
/*
Create a path where we will place our picture in the user's public
pictures directory. Note that you should be careful about what you
place here, since the user often manages these files.
For pictures and other media owned by the application, consider
Context.getExternalMediaDir().
*/
final File path =
Environment.getExternalStoragePublicDirectory
(
//Environment.DIRECTORY_PICTURES
//Environment.DIRECTORY_DCIM
Environment.DIRECTORY_DCIM + "/MyFolderName/"
);
// Make sure the Pictures directory exists.
if(!path.exists())
{
path.mkdirs();
}
final File file = new File(path, fileJPG + ".jpg");
try
{
final FileOutputStream fos = new FileOutputStream(file);
final BufferedOutputStream bos = new BufferedOutputStream(fos, 8192);
//bmp.compress(CompressFormat.JPEG, 100, bos);
bmp.compress(CompressFormat.JPEG, 85, bos);
bos.flush();
bos.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
fileJPG is the file name I'm creating (dynamically, adding a date).
Replace MyFolderName with albumName.
bmp is my Bitmap data (a screenshot, in my case).
i take a long time for this faking error too and finally it's solve just with add this one line code in manifest
android:requestLegacyExternalStorage="true"

Phonegap Android: saved picture is shown as cache group

I used Phonegap and the image-resizer plugin to save images into the Android device with this code:
try {
// Obligatory Parameters, throw JSONException if not found
String filename = params.getString("filename");
filename = (filename.contains(".")) ? filename : filename + "."+ format;
String directory = params.getString("directory");
directory = directory.startsWith("/") ? directory : "/"+ directory;
int quality = params.getInt("quality");
OutputStream outStream;
//store the file locally using the external storage directory
File file = new File(Environment.getExternalStorageDirectory()
.toString() + directory, filename);
try {
outStream = new FileOutputStream(file);
if (format.equals(FORMAT_PNG)) {
bmp.compress(Bitmap.CompressFormat.PNG, quality, outStream);
} else {
bmp.compress(Bitmap.CompressFormat.JPEG, quality, outStream);
}
outStream.flush();
outStream.close();
JSONObject res = new JSONObject();
res.put("url", "file://" + file.getAbsolutePath());
result = new PluginResult(Status.OK, res);
scanPhoto(imageData.substring(8));
} catch (IOException e) {
result = new PluginResult(Status.ERROR, e.getMessage());
}
} catch (JSONException e) {
result = new PluginResult(Status.JSON_EXCEPTION, e.getMessage());
}
}
Then for it to be available in the gallery this function is called:
private void scanPhoto(String imageFileName) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(imageFileName);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.cordova.getActivity().sendBroadcast(mediaScanIntent);
}
Update :However when I go to the gallery the images are in a group called cache so I have 2 groups camera and cache. How do I change this into the application's name instead? - got a app name now after poiting directory in a folder with my app name

Captured image is not stored in the specific folder in android

I have created a program to capture the image and that is getting stored into sdcard/dcim/camera folder. Now I am trying to save the captured image in my own directory created in sdCard, say "/somedir".
I am able to make the directory programmatically but the image file is not getting stored in it.
Can anybody tell me where I am doing wrong here??
Here is the code....
File folder = new File(Environment.getExternalStorageDirectory() + "/abc");
Bitmap mybitmap1; //mybitmap1 contain image. So plz dont consider that I don't have image in mybitmap1;
if(!folder.exists())
{
success = folder.mkdir();
Log.i("Log", "folder created");
}
else
{
Log.i("Log", "Folder already present here!!");
}
String fname = date +".jpg";
file = new File( folder,fname);
if (file.exists ())
file.delete ();
capturedImageUri = Uri.fromFile(file);
FileOutputStream out;
byte[] byteArray = stream.toByteArray();
try {
out = new FileOutputStream(file);
mybitmap1.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(), mybitmap1, file.getName(), file.getName());
//MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
} catch (Exception e) {
e.printStackTrace();
}
Refer the below code
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == 1 ) {
final Uri selectedImage = data.getData();
try {
bitmap = Media.getBitmap(getContentResolver(),selectedImage);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator
+ filename);
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are settings the wrong file name for the file. Just use this method if you want to use time in the name of image file.
private Uri getImageUri() {
// Store image in dcim
String currentDateTimeString = getDateTime();
currentDateTimeString = removeChar(currentDateTimeString, '-');
currentDateTimeString = removeChar(currentDateTimeString, '_');
currentDateTimeString = removeChar(currentDateTimeString, ':');
currentDateTimeString = currentDateTimeString.trim();
File file = new File(Environment.getExternalStorageDirectory()
+ "/DCIM", currentDateTimeString + ".jpg");
Uri imgUri = Uri.fromFile(file);
return imgUri;
}
private final static String getDateTime() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd_hh:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("PST"));
return df.format(new Date());
}
public static String removeChar(String s, char c) {
StringBuffer r = new StringBuffer(s.length());
r.setLength(s.length());
int current = 0;
for (int i = 0; i < s.length(); i++) {
char cur = s.charAt(i);
if (cur != c)
r.setCharAt(current++, cur);
}
return r.toString();
}
Hers is what you need to do:
instead of
File folder = new File(Environment.getExternalStorageDirectory() + "/abc");
do this
File folder = new File(Environment.getExternalStorageDirectory().getPath() + "/abc");
if(folder.exists()){
//save your file then
}
else{
folder.mkdirs();
//save your file then
}
Make sure you use the neccessary permissions in your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Categories

Resources