conditionally hiding & unhiding image folders in android - 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.

Related

How do I open a the folder where an image is located from my Xamarin Android Application?

I have tried looking almost everywhere on how to open the parent folder of a child image displayed in my app with no success. Am debugging my Android Application to a device running Android API level 29. The inbuilt samsung File Manager has a menu item for navigating to the source folder of any file and that is why I believe there is a way to tell the App to open the location of the image displayed on my ImageSwitcher object. The app has a context menu with a Open Source Folder menu item for opening the source folder of the image, the code to do that is the problem...
Code
public override bool OnContextItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
case Resource.Id.image_folder:
try
{
//I tried this inbuild dotnet method but it does not work
string file_path = new Java.IO.File(files[index]).AbsolutePath;
DirectoryInfo info= new DirectoryInfo(file_path);
info.MoveTo(new Java.IO.File(file_path).Parent);
}catch(Exception ex)
{
Android.App.AlertDialog.Builder mybuilder= new Android.App.AlertDialog.Builder(this);
mybuilder.SetTitle("Exception");
mybuilder.SetMessage(ex.Message);
mybuilder.Show();
}
break;
}
}
Code below shows how I obtained the path to the ImageSwicther currentl image.
void read_images()
{
//access the application's directory
Java.IO.File original_file = (Application.GetExternalFilesDir(null));
//check if the file is read only
if (original_file.CanRead())
{
//Toast.MakeText(this, "This folder can be read", ToastLength.Long).Show();
}
if (original_file.Exists() && original_file.IsDirectory)
{
try
{
//make sure the file is an image file
//apply the code for image mime type extensions
files = Directory.GetFiles(original_file.AbsolutePath);
for (int i = 0; i < files.Length; i++)
{
//delete any file that does not end with an image format
if (files[i].EndsWith("jpg") == false || files[i].EndsWith("png") == false)
{
Directory.Delete(files[i]);
}
}
}
catch (Exception e)
{
Android.App.AlertDialog.Builder alert = new Android.App.AlertDialog.Builder(this);
alert.SetTitle("File Read Exception");
alert.SetMessage(e.Message + "\n" + e.Data);
alert.Show();
}
// Toast.MakeText(this, "File exists",ToastLength.Short).Show();
}
}
Now that the I have the paths to the images in a string array, all I do is use an integer variable called index to switch the path and display it to the ImageSwitcher object when user swipes right or left like
//increment index for right swipe and decrement for left
myswitcher.ClearAnimation();
myswitcher.SetInAnimation(this,Resource.Animation.slide_in_left);
myswitcher.SetOutAnimation(this,Resource.Animation.slide_out_left);
myswitcher.SetImageURI(Android.Net.Uri.FromFile(new Java.IO.File(files[index])));
NB:
The files[index] is a string array containing paths of all the images displayed in the imageswitcher object.

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();
}
}};

writing and saving a file in android application

m trying to write a file when a button Save_btn is pressed however, when i run the application it runs smoothly with no errors but the file is nowhere to be found.
I am trying to write to the internal storage of the device. the text being written is in a edittext field. i would like this text from the EditText to be written to the file
I have included the code I'm using below;
Save_btn = (Button) findViewById(R.id.g);
Save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View views) {
TextView CodeView = (TextView) findViewById(R.id.Code_Viewer);
CodeView.setText(CodeView.getText());
try {
String etName = CodeView.getText().toString();
if (!etName.trim().equals("")) {
File file = new File("/Documents/test.txt");
//if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getName(), true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(etName);
bufferWritter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
);
Any advice on how to get the file to write properly would be greatly appreciated.
Thanks in advance.
replace this code with yours :
Save_btn = (Button) findViewById(R.id.g);
Save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View views) {
TextView CodeView = (TextView) findViewById(R.id.Code_Viewer);
CodeView.setText(CodeView.getText());
String etName = CodeView.getText().toString();
File dir = new File(getFilesDir(), "yourfolder");
if(!dir.exists())
{
dir.mkdirs();
}
String textFileName="textFile.txt";
File file = new File(dir.getPath(), textFileName );
if(file.exists())
{
file.delete();
}
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(etName);
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
);
you should note these points :
this code will create file on /data/data/[your app package name]/files/[your folder]/[your textFileName]
it always remove your file if the file name was the same , so you should get unique name for each one.(you can include date and time in file name)
I'm not sure this can work because the file path you're specifying is a) absolute and b) pointing to a directory you probably have no write permission for.
File file = new File("/Documents/test.txt");
This references the Documents folder in the file systems root directory instead of your apps files.
If you want to save it locally for use in your own application, you can try Context#getFilesDir, e.g.
File file = new File(context.getFilesDirectory(), "yourfile.txt");
In case you want to save it somewhere other applications can use it you might need a more sophisticated approach, e.g. a FileProvider.
You should use
File file = new File(context.getFilesDir(), "test.txt");
instead of
File file = new File("/Documents/test.txt");
to save to your internal storage. The rest of your code can stay the same.

Displaying the same image files in adapter - 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();

access android media directory?

ey up. ive built a simple music app that reads wav files from the sdcard and plays them.
how do i access the default media directory?
this is how i get the sdcard
public void LoadSounds() throws IOException
{
String extState = Environment.getExternalStorageState();
if(!extState.equals(Environment.MEDIA_MOUNTED)) {
//handle error here
}
else {
File sd = new File(Environment.getExternalStorageDirectory ()); //this needs to be a folder the user can access, like media
as usual the docs dont give an actual example of usage but it says this - If you're using API Level 8 or greater, use getExternalFilesDir() to open a File that represents the external storage directory where you should save your files. This method takes a type parameter that specifies the type of subdirectory you want, such as DIRECTORY_MUSIC...
how do i use it?
thank you
edit:
this makes it crash if i try to fill a spinner array with file path Strings.
File path = getExternalFilesDir(Environment.DIRECTORY_MUSIC);
File sd = new File(path, "/myFolder");
File[] sdDirList = sd.listFiles(new WavFilter());
if (sdDirList != null)
{
//sort the spinner
amountofiles = sdDirList.length;
array_spinner=new String[amountofiles];
......
final Spinner s = (Spinner) findViewById(R.id.spinner1); //crashes here
ArrayAdapter<?> adapter = new ArrayAdapter<Object>(this,
android.R.layout.select_dialog_item, array_spinner);
EDIT2:
ok so ive done this test that is supposed to write a txt file to the music directory.
i run the app, no txt file is written anywhere on the device i can find.
// Path to write files to
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath();
String fname = "mytest.txt";
// Current state of the external media
String extState = Environment.getExternalStorageState();
// External media can be written onto
if (extState.equals(Environment.MEDIA_MOUNTED))
{
try {
// Make sure the path exists
boolean exists = (new File(path)).exists();
if (!exists){ new File(path).mkdirs(); }
// Open output stream
FileOutputStream fOut = new FileOutputStream(path + fname);
fOut.write("Test".getBytes());
// Close output stream
fOut.flush();
fOut.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
another edit: i will get this working!!
so if i use this line it creates a folder on the sdcard called 'Musictest'. dont understand??
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC + "test").getAbsolutePath();
////////////////////////////////////////////////////////////////////
Final Edit:
right so this will look for a folder called test in the devices music directory.
if it doesnt exist, it will be created.
(some fixing to be done here, error if empty) it then lists the files in the directory and adds them to an array.
public void LoadSounds() throws IOException
{
String extState = Environment.getExternalStorageState();
// Path to write files to
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC + "/test").getAbsolutePath();
if(!extState.equals(Environment.MEDIA_MOUNTED)) {
//handle error here
}
else {
//do your file work here
// Make sure the path exists
boolean exists = (new File(path)).exists();
//if not create it
if (!exists){ new File(path).mkdirs(); }
File sd = new File(path);
//This will return an array with all the Files (directories and files)
//in the external storage folder
File[] sdDirList = sd.listFiles();
if (sdDirList != null)
{
//add the files to the spinner array
array_spinnerLoad=new String[sdDirList.length];
files = new String[sdDirList.length];
for(int i=0;i<sdDirList.length;i++){
array_spinnerLoad[i] = sdDirList[i].getName();
files[i] = sdDirList[i].getAbsolutePath();
}
}
}
}
as mentioned in the docs, getExternalFilesDir() return File. And File object can represent either file or directory.
Therefore:
File musicDirectory = new File( getExternalFilesDir(Environment.DIRECTORY_MUSIC));
Will give you the object to play with.

Categories

Resources