Displaying the same image files in adapter - Android - android

Situation:
I have an activity that contains an image picker function to select images. Once selected, these images are loaded/displayed in a GridView. I load the images using ImageLoader library with the following method:
ImageLoader.getInstance().displayImage("file://"+image.path, Utility.displayImageOptions);
In the same activity i have a Preview button which clicked lead to an another new activity. This new activity also contains a GridView using the same adapter code as in the previous activity. However, this GridView contains the compressed version of the images that were selected previously.
In my compression i save these bitmaps and create new files that are loaded in the second activity.
saveBitmapToFile(bitmap, index);
private void saveBitmapToFile(Bitmap bitmap, int imageIndex){
try {
bitmapFile = getPermanentFile(imageIndex);
FileOutputStream fos = new FileOutputStream(bitmapFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
Images image = new Images(bitmapFile.getAbsolutePath(), true, false);
compressedImageList.add(image);
}
catch (IOException e){
e.printStackTrace();
}
}
private static File getPermanentFile(int imageIndex) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(), TEMP_PHOTO_FILE + String.valueOf(imageIndex) + ".jpg");
try {
if (file.exists()){
Log.v("File exists", file.getName());
file.delete();
file = new File(Environment.getExternalStorageDirectory(), TEMP_PHOTO_FILE + String.valueOf(imageIndex) + ".jpg");
}
file.createNewFile();
} catch (IOException e) {
}
return file;
} else {
return null;
}
}
The problem i have is that say I start with a fresh app (nothing stored in cache), select 4 images and click Preview, i get the compressed version of these four images. But then i close the app and start it again and i again select 4 different images and hit Preview BUT i get the same 4 compressed images that I got at the first time. Clearing the cache/data by going in settings resolves the problem but how can i do this in code.
I delete these files onBackPressed() but still the problem remains when i click back and then select images again.
#Override
public void onBackPressed(){
super.onBackPressed();
for (Images file : compressedImageList){
File f = new File(file.cardPath);
boolean deleted = f.delete();
if (deleted){
Log.v("File deleted : ", file.cardPath);
}
}
compressedImageList.clear();
}

Have You tried
imageLoader.clearMemoryCache();
and
imageLoader.clearDiscCache();

Related

Storage in android studio

I am trying to pull multiple images from gallery and place in grid view , Unfortunately I am not able to do so, Can you help me with that. And also I made a folder in sd card and I m trying to store audio as well as photographs in the same folder. Can you help me with that as well?
I am using android 2.3.
So I have included this code inside the button click but on click of button it has created the folder but its not storing the file inside the folder. On click of the button every other thing is working, its opening the gallery and its calculating numpic. I am not sure why its not storing the file in CN Video folder.
public void onClick(View v) {
Intent pass_data = new Intent(MainRecord.this, OpenGallery.class);
pass_data.putExtra("numpic",numpic);
startActivity(pass_data);
// Saving Audio recorded file to directory
File f = new File(Environment.getExternalStorageDirectory() + "/CNvideo");
if(f.isDirectory()) {
//Write code for the folder exist condition
}else {
// create a File object for the parent directory
File CNvideoDirectory = new File("/sdcard/CNVideo/");
// have the object build the directory structure, if needed.
CNvideoDirectory.mkdirs();
// create a File object for the output file
String filename = getfilename();
File outputFile = new File(CNvideoDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
try {
FileOutputStream fos = new FileOutputStream(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}};

File saved in "Downloads" directory but when we open this folder by starting activity files does not appear

I want to implement functionality for saving image in Downloads directory and after that offer to user to open this one in a directory (open directory in which user can find and open this image). But I've got one issue. Saving ends successfully, but when user clicks "OPEN" in snackbar and chooses app to perform this action another directory appears. It contains also "Downloads" directory as well, this Downloads directory does not contain saved images! It seems like in android we have two different "Downloads" directories.
Below is how i get path for save image:
private File getFileForImageSaving() {
String filename = getImageNameFromUrl(mImageUrl) + ".png";
File dest = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
filename);
int index = 1;
while (dest.exists()) {
filename = getImageNameFromUrl(mImageUrl) + "_" + index + ".png";
dest = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
filename);
index++;
}
return dest;
}
This is how i run activity for view "Download" directory and open files.
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath());
intent.setDataAndType(uri, "image/png");
startActivity(Intent.createChooser(intent, "Open folder"));
This is how I save image. It is realy works, I've checked.
pri
vate void saveImageToFile() {
File dest = getFileForImageSaving();
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
FileOutputStream out = null;
try {
dest.createNewFile();
out = new FileOutputStream(dest);
Bitmap bitmap = Glide.with(ArticleImageViewActivity.this)
.load(mImageUrl)
.asBitmap()
.into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
Utils.showInSnackBar(
ArticleImageViewActivity.this, getString(R.string.image_has_been_successfully_saved),
Snackbar.LENGTH_LONG,
onOpenImageInDirectoryListener,
getString(R.string.open_image_in_directory));
} catch (Exception e) {
Utils.showInSnackBar(ArticleImageViewActivity.this,
getString(R.string.error_occurred_during_saving_image),
Snackbar.LENGTH_SHORT, null, null);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}.execute();
}
I partially resolve my problem by using Intent.ACTION_VIEW instead of Intent.ACTION_GET_CONTENT and " / " mime type instead of "image/png". But only partially because in this case user will be offered to choose a wide range of applications, but not only applications like filemanagers.
use MediaScannerConnection.scanFile to scan the file after saving. if you don't many/most galleries wont show your file.
https://developer.android.com/reference/android/media/MediaScannerConnection.html

conditionally hiding & unhiding image folders in android

The following is my requirement:
I have a checkbox in my activity. If the checkbox is checked, I will add a '.nomedia' file to hide all the photos in my folder. If the checkbox is unchecked, I will delete the '.nomedia' file, to display all the photos in the folder. My problem is, though the creation/deletion of '.nomedia' file is successful, the hiding/unhiding of the images are not happening in the android gallery app. How can I force the gallery app to show/hide the folder contents according to my checkbox state?
The following is my code:
CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox1);
if (checkBox.isChecked()) {
hideFolder();
} else {
unHideFolder();
}
private void hideFolder() {
File targetDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + CONSTANTS.MYFOLDERPATH);
File noMediaFile = new File(targetDir, ".nomedia");
try {
if (!noMediaFile.exists()) {
noMediaFile.createNewFile();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void unHideFolder() {
File targetDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + CONSTANTS.MYFOLDERPATH);
File noMediaFile = new File(targetDir, ".nomedia");
if (noMediaFile.exists()) {
noMediaFile.delete();
}
}
You need to force start media scan. Thus to index of media on the sdcard, .nomedia will no reflect immediately. On way to do that is to clear the data of Gallery app.

internal storage for app and uri

So I'm using the twitter api and I want to tweet with an image I use:
TweetUri = Uri.fromFile(saveIT);
TweetComposer.Builder builder = new TweetComposer.Builder(this)
.text("")
.image(TweetUri);
builder.show();
The original image is a bitmap, so what I did (not sure if this is the optimal way) was save in the internal storage:
private File 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
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
String mImageName="MI_"+ timeStamp +".jpg";
File mypath=new File(directory,mImageName);
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(Exception e)
{
e.printStackTrace();
}
}
return mypath;
}
The file it returns will be the "saveIT" in the TweetUri when it does the fromfile method. Of course this will overload the storage so what I plan to do is wipe the internal storage for the app when it is stopped (no other data is saved in the internal storage other than the temp images I save for the tweet):
#Override
protected void onStop() {
super.onStop();
File MSD = this.getApplicationContext().getFilesDir();
File [] lisFiles = MSD.listFiles();
for(int i=0;i<lisFiles.length;i++)
{
boolean deleted = lisFiles[i].delete();
}
}
None of this works... I can't seem to find any of the images when I save them to verify if the deleting is happening. Also, when the user clicks tweet no image is added to the tweet as well. No idea what I'm doing wrong here... In reality I don't want to save the image in the internal storage but I do because the tweet api uses a URI to tweet and not a bitmap.
I switched it to write to external storage and it worked fine. Also I switched it to delete at onDestroy. This is better because, when I invoke the Twitter API it switches activities so the onstop is invoked which would delete the temp picture too early. It's too early becuase if the user clicks cancel at the twitter api, comes back to my api and then invokes the twitter api again the uri will point to nothing since the picture was already deleted. THATS ALL FOLKS :)

Sent Image to another ImageView (in other activity)

I'm currently developing an Android Application. My current progress is that I successful develop custom android camera. I followed this step (http://courses.oreillyschool.com/android2/CameraAdvanced.html) The tutorial given saved the picture taken into the gallery, but I want to insert the name, description, and other information of the Image because I'm going to save the image along with the details that the user enter into my database.
Here for example on my interface:
a) Success taken Image:
b) The image that need to be pass to another Imageview (red circle):
I want the save button able to pass the image that had been taken to the ImageView(red circle) and not to store the image into the gallery. And here's are the code on the save button:
private View.OnClickListener mSaveImageButtonClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
File saveFile = openFileForImage();
if (saveFile != null) {
saveImageToFile(saveFile);
} else {
Toast.makeText(Capturingimage.this, "Unable to open file to save the image.", Toast.LENGTH_LONG).show();
}
}
};
This is save image to file method:
private void saveImageToFile(File file) {
if (mCameraBitmap != null) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(file);
if (!mCameraBitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream)) {
Toast.makeText(Capturingimage.this, "Unable to save image to file.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Capturingimage.this, "Saved image to: " + file.getPath(),
Toast.LENGTH_LONG).show();
}
outStream.close();
} catch (Exception e) {
Toast.makeText(Capturingimage.this, "Unable to save image to file.",
Toast.LENGTH_LONG).show();
}
}
}
My ImageView(redCircle) id is :
#+id/image_view_after_capture
If you guys aren't very clear with the codes, here's the link on the full source code (http://courses.oreillyschool.com/android2/CameraAdvanced.html) on MainActivity.java. I'm sorry if my question is a lil bit messy and less explanation on the codes. I'm new to android programming, I hope you guys can teach me. I really appreciate your time and help to consider to help me.
Thank you in Advance!
when you save image than hold your captured image path and pass to another activity where you want to show
String mCaptureImagePath="";
private void saveImageToFile(File file) {
if (mCameraBitmap != null) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(file);
if (!mCameraBitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream)) {
Toast.makeText(Capturingimage.this, "Unable to save image to file.",
Toast.LENGTH_LONG).show();
} else {
mCaptureImagePath=file.getPath(); //**** this is your save image path
Toast.makeText(Capturingimage.this, "Saved image to: " + file.getPath(),
Toast.LENGTH_LONG).show();
}
outStream.close();
} catch (Exception e) {
Toast.makeText(Capturingimage.this, "Unable to save image to file.",
Toast.LENGTH_LONG).show();
}
}
}
After show image where you want like this
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(mCaptureImagePath,bmOptions);
yourImageView.setImageBitmap(bitmap);

Categories

Resources