i have a Problem with String[] array.I refer about this from Here
& Here
But still, i have not found any solution from the link.
What I want:
I am developing a Custom Camera App.I have a Folder in which I am saving a Captured images.also, i have 1 ImageView. when my App Launched the Image [or Bitmap] of Folder is set into that ImageView (Always set the First image of the folder into ImageView).
Following is my Code.
private void loadImageInImageView() {
Uri[] mUrls;
String[] mFiles = new String[0];
File file = new File(android.os.Environment.getExternalStorageDirectory(), "CameraApp/Images");
File[] imageList = file.listFiles(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return ((name.endsWith(".jpg")) || (name.endsWith(".png")) || (name.endsWith(".mp4")));
}
});
if (mFiles.length >= 0) {
Toast.makeText(this, "No Captured Images", Toast.LENGTH_SHORT).show();
} else {
mFiles = new String[imageList.length];
for (int i = 0; i < imageList.length; i++) {
mFiles[i] = imageList[i].getAbsolutePath();
}
mUrls = new Uri[mFiles.length];
for (int i = 0; i < mFiles.length; i++) {
mUrls[i] = Uri.parse(mFiles[i]);
imgBtnThumbnail.setImageURI(mUrls[i]);
}
}
}
in Above code [when Folder is Empty] :
When i set if (mFiles.length > 0)
it shows me an Error
Error: Attempt to get length of null array
When i set if (mFiles.length >= 0)
Then it shows me same as Above Error.
When i set if (mFiles == null)
it is also not Working because I have initialized String[] in above code.
String[] mFiles = new String[0];
Hence it also not work.
When I have some Images then it working Fine.because it executed the else part.
what should I do?Whenever my Folder is Empty then it Shows me a Toast.otherwise my else code will be executed.
Any help will be Highly appreciated.
File[] imageList = file.listFiles(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return ((name.endsWith(".jpg")) || (name.endsWith(".png")) || (name.endsWith(".mp4")));
}
});
if (imageList.length = 0) {
Toast.makeText(this, "No Captured Images", Toast.LENGTH_SHORT).show();
} else {
String[] mFiles = new String[imageList.length];
for (int i = 0; i < imageList.length; i++) {
mFiles[i] = imageList[i].getAbsolutePath();
}
mUrls = new Uri[mFiles.length];
for (int i = 0; i < mFiles.length; i++) {
mUrls[i] = Uri.parse(mFiles[i]);
imgBtnThumbnail.setImageURI(mUrls[i]);
}
}
If the function you want works when the size of the imageList is greater than zero, try below code.
private void loadImageInImageView() {
File file = new File(android.os.Environment.getExternalStorageDirectory(), "CameraApp/Images");
File[] imageList = file.listFiles(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return ((name.endsWith(".jpg")) || (name.endsWith(".png")) || (name.endsWith(".mp4")));
}
});
// conditional operator [ ? : ]
// value = (experssion) ? value if true : value if false
// ref : https://www.tutorialspoint.com/java/java_basic_operators.htm
int imgLength = imageList == null ? 0 : imageList.length;
if(imgLength > 0)
{
String[] mFiles = new String[imgLength];
Uri[] mUrls = new Uri[imgLength];
//merge for condition
for (int i = 0; i < imgLength; i++) {
mFiles[i] = imageList[i].getAbsolutePath();
mUrls[i] = Uri.parse(mFiles[i]);
imgBtnThumbnail.setImageURI(mUrls[i]);
}
}
else
{
Toast.makeText(this, "No Captured Images", Toast.LENGTH_SHORT).show();
}
}
Do not initialize mFiles. Initialize it in the moment when you add some data.
And for checking if it isn't empty use this:
if (mFiles != null && mFiles.length > 0) {
...
}
private void loadImageInImageView() {
Uri[] mUrls;
File[] imageList
File file = new File(android.os.Environment.getExternalStorageDirectory(), "CameraApp/Images");
imageList = file.listFiles(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return ((name.endsWith(".jpg")) || (name.endsWith(".png")) || (name.endsWith(".mp4")));
}
});
if (imagelist==null && imageList.length == 0) {
Toast.makeText(this, "No Captured Images", Toast.LENGTH_SHORT).show();
} else {
for (int i = 0; i < imageList.length; i++) {
imgBtnThumbnail.setImageURI(Uri.parse(imageList[i].getAbsolutePath()););
}
}
}
try this;
but your image changes continuously because of for loop;
Related
I am able to fetch all the images from any specified non hidden folder from device but how can I get all the images from a hidden specified folder.
As soon as I mention my hidden folder name in the query, cursor return null
public static List<MediaData> getAppScannedImages(Context context) {
Cursor imagecursor = null;
List<MediaData> gallerydata = new ArrayList<MediaData>();
try {
final String orderBy = Images.ImageColumns.DATE_TAKEN + " DESC";
imagecursor = context.getContentResolver()
.query(Images.Media.EXTERNAL_CONTENT_URI,
projectionImage,
Images.Media.BUCKET_DISPLAY_NAME + "='"
+ ".myHiddenFolder" + "'", null,
orderBy);
if (imagecursor != null) {
imagecursor.moveToFirst();
int count = imagecursor.getCount();
for (int i = 0; i < count; i++) {
MediaData galData = new MediaData();
galData.setKey_id(i);
galData.setId(imagecursor.getString(0));
galData.setName(imagecursor.getString(1));
galData.setPath(imagecursor.getString(2));
galData.setDate(imagecursor.getString(3));
gallerydata.add(galData);
imagecursor.moveToNext();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (imagecursor != null) {
imagecursor.close();
}
}
return gallerydata;
}
You can try a different approach.
You have to find out the list of hidden folder from sd card and search all those folders for images.
the follwoing code is displays hidden files:
public void goTODir(File dir) {
//dir is initail dir like="/mnt/sdcard"
String imageType = ".jpg";
File[] listFile = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
goTODir(listFile[i]);
} else {
if (listFile[i].isHidden()){
if(listFile[i].getName().endsWith(imageType))
{
//add to your array list
}
}
}
}
}
}
String path = Environment.getExternalStorageDirectory().toString();
File dir = new File(path);
File listFile[] = dir.listFiles();
for (int i = 0; i < listFile.length; i++) {
if(listFile[i].getAbsolutePath().contains("your hidden folder name")){
File dirtest = new File(listFile[i].getAbsolutePath());
File listFiletest[] = dirtest.listFiles();
for (int j = 0; j < listFiletest.length; j++) {
get all images from hidden folder
}
}
}
For Kotlin Lover
companion object {
const val FOLDER_PATH = "/YourFolder/.hideen/"
}
/**
* Method to get all Image Path
* #return [ArrayList]
* */
fun getImagePath(): ArrayList<String> {
// image path list
val list: ArrayList<String> = ArrayList()
// fetching file path from storage
val file = File(Environment.getExternalStorageDirectory().toString() + FOLDER_PATH)
val listFile = file.listFiles()
if (listFile != null && listFile.isNullOrEmpty()) {
Arrays.sort(listFile, LastModifiedFileComparator.LASTMODIFIED_REVERSE)
}
if (listFile != null) {
for (imgFile in listFile) {
if (
imgFile.name.endsWith(".jpg")
|| imgFile.name.endsWith(".jpeg")
|| imgFile.name.endsWith(".png")
) {
val model : String = imgFile.absolutePath
list.add(model)
}
}
}
// return imgPath List
return list
}
I have a problem getting the size of a file.
I have the following code:
File file = new File(path);
FilenameFilter mediafilefilter = new FilenameFilter(){
private String[] filter = {".txt"};
#Override
public boolean accept(File dir, String filename) {
for(int i= 0;i< filter.length ; i++){
if(filename.indexOf(filter[i]) != -1)return true;
}
return false;
}
};
File[] flies = file.listFiles(mediafilefilter);
if (files != null) {
{
if (files.length > 0)
{
System.out.println("Totol is :" + files.length);
for (int j = 0; j < files.length; j++) //not work
}
}
}
some text file is 0 byte
Like that
list[0].length()/1024
list[0] is the first file in your array
public long getFileSizes(File f) throws Exception{
long s=0;
if (f.exists()) {
FileInputStream fis = null;
fis = new FileInputStream(f);
s= fis.available();
}
return s;
}
What I want here is to display only the folders and subfolders that contains images or videos or mp3.
for (int i = 0; i < fileList.size(); i++) {
TextView textView = new TextView(this);
textView.setText(fileList.get(i).getName());
textView.setPadding(5, 5, 5, 5);
System.out.println(fileList.get(i).getName());
if (fileList.get(i).isDirectory()) {
textView.setTextColor(Color.parseColor("#000000"));
}
view.addView(textView);
}
}
public ArrayList<File> getfile(File dir) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
// Filters based on whether the file is hidden or not
return (((sel.isFile() || sel.isDirectory()) && !sel.isHidden()));
//...
}
};
File listFile[] = dir.listFiles(new ImageFileFilter());
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
fileList.add(listFile[i]);
getfile(listFile[i]);
} else {
if (listFile[i].getName().endsWith(".png") || listFile[i].getName().endsWith(".JPG") || listFile[i].getName().endsWith(".jpeg") || listFile[i].getName().endsWith(".gif") || listFile[i].getName().endsWith(".mp3")) {
//fileList.add(listFile[i].getParentFile());
fileList.add(listFile[i]);
}
}
}
}
return fileList;
}
I tried the functions below but it still display the folders that doesn't include images or videos or mp3
private boolean isImageFile(String filePath) {
if (filePath.endsWith("JPG") || filePath.endsWith("PNG") || filePath.endsWith(".mp3"))
// Add other formats as desired
{
return true;
}
return false;
}
private class ImageFileFilter implements FileFilter {
#Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else if (isImageFile(file.getAbsolutePath())) {
return true;
}
return false;
}
}
}
In your accept function, you have the code return (((sel.isFile() || sel.isDirectory()) && !sel.isHidden()));
Instead of returning true if sel.isDirectory, you'd need to search all files in that directory and look for media files in it, and return true only if one is found. This would turn your algorithm into a recursive one which may have issues if you use symbolic links in your filesystem- you'll have to beware of loops. It may also cause performance issues.
This may seem like an old question but I have tried all solutions and this doesn't seem to work for me. I use the following code for listing all files with extension .docx in my ListView. However, this doesn't work properly for some reason and lists only all files under root.
In onCreate:
view = (LinearLayout) findViewById(R.id.view);
//getting SDcard root path
root = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath());
getfile(root);
for (int i = 0; i < fileList.size(); i++) {
TextView textView = new TextView(this);
if(!fileList.get(i).isDirectory() & fileList.get(i).getName().endsWith(".docx") || fileList.get(i).getName().endsWith(".doc")) {
textView.setText((i+1)+". "+fileList.get(i).getName());
Toast.makeText(this, fileList.get(j).getAbsolutePath(),Toast.LENGTH_LONG).show();
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
.....
}
});
view.addView(textView);
}
else {
getfile( new File(fileList.get(i).getAbsolutePath())); // its directory so similar code but new filelist instance
for (int k = 0; k < fileList.size(); k++) {
//TextView textView = new TextView(this);
if(!fileList.get(k).isDirectory() & fileList.get(k).getName().endsWith(".docx") || fileList.get(k).getName().endsWith(".doc")) {
textView.setText((k+1)+". "+fileList.get(i).getName());
Toast.makeText(this, fileList.get(j).getAbsolutePath(),Toast.LENGTH_LONG).show();
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
...
}
});
view.addView(textView);
}
else {
}
}
}
getFile ArrayList function:
public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
} else {
if (listFile[i].getName().endsWith(".docx")
|| listFile[i].getName().endsWith(".doc"))
{
fileList.add(listFile[i]);
}
}
}
}
return fileList;
}
Though i got so many post but problem is that
it return true if phone has inbuild storage.
Anyone for help me
Below code will helps...
/**
* Returns all available external SD-Card roots in the system.
*
* #return paths to all available external SD-Card roots in the system.
*/
public static String[] getStorageDirectories() {
String[] storageDirectories;
String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
List<String> results = new ArrayList<String>();
File[] externalDirs = myContext.getExternalFilesDirs(null);
for (File file : externalDirs) {
String path = null;
try {
path = file.getPath().split("/Android")[0];
} catch (Exception e) {
e.printStackTrace();
path = null;
}
if (path != null) {
if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Environment.isExternalStorageRemovable(file))
|| rawSecondaryStoragesStr != null && rawSecondaryStoragesStr.contains(path)) {
results.add(path);
}
}
}
storageDirectories = results.toArray(new String[0]);
} else {
final Set<String> rv = new HashSet<String>();
if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
Collections.addAll(rv, rawSecondaryStorages);
}
storageDirectories = rv.toArray(new String[rv.size()]);
}
return storageDirectories;
}
//To check external SD is available or not
String retArray[] = getStorageDirectories();
if (retArray.length == 0) {
Toast.makeText(ListenActivity.this, "Sdcard not Exists", Toast.LENGTH_SHORT).show();
} else {
for (int i = 0; i < retArray.length; i++) {
Log.e("path ", retArray[i]);
}
}