I am using json to get the image from url and successfully stored into sdcard.
I want to get image from sdcard and display into gridview. when I am using below code I can easily get the all image and easily display into grid view.
public void getFromSdcard() {
ArrayList<String> f = new ArrayList<String>();
File file = new File("/mnt/sdcard/IMG");
if (file.isDirectory()) {
listFile = file.listFiles();
Log.v("Length", "IMG ::" + listFile.length);
for (int i = 0; i < listFile.length; i++) {
f.add(listFile[i].getAbsolutePath());
}
}
}
The problem is I don't want to display all the images into grid view, i want to display specific images (using image prefix).
for example i have list of jpg below
LR-001.jpg
LR-002.jpg
GR-001.jpg
GR-002.jpg
CF-001.jpg
CF-002.jpg
ER-001.jpg
ER-002.jpg
GBR-001.jpg
GBR-002.jpg
GPT-001.jpg
GPT-002.jpg
NCK-001.jpg
NCK-002.jpg
how to get image of GR prefix?
You could check if the filename starts with "GR" for instance:
for (int i = 0; i < listFile.length; i++) {
String fileName = listFile[i].getName();
if (fileName.startsWith("GR"))
f.add(listFile[i].getAbsolutePath());
}
the same with the for-each
for (File file : listFile) {
String fileName = file.getName();
if (fileName.startsWith("GR"))
f.add(file);
}
to get a random entry from your ArrayList you can use the class Random
private Random randomGenerator;
randomGenerator = new Random();
int index = randomGenerator.nextInt(f.size());
File file = f.get(index);
nexInt returns a number between 0 and f.size() - 1
You could check your filenames for the starting letters "GR"
Following Code should work
List<File> f = new ArrayList<File>();
File file = new File("/mnt/sdcard/IMG");
if (file.isDirectory()) {
listFile = file.listFiles();
Log.v("Length", "IMG ::" + listFile.length);
for (File file : listFile) {
if(file.getName().startsWith("GR"){
f.add(file.getAbsolutePath());
}
}
}
Hope it will help you
You could use a FilenameFilter:
f = file.list(new FilenameFilter(){
#Override
public boolean accept(File dir, String filename){
if (filename.startsWith("GR")) return true;
return false;
}
});
Related
I have a problem with an ArrayList (File in the above code). This arraylist is composed by files that are located into the sd. The problem is that I can have duplicates (the same image, but in different paths into the sd, so the same filename but different path) and I want to remove them. So I use this code:
ArrayList<File> removedDuplicates = new ArrayList<File>();
for (int i = 0; i < File.size(); i++) {
if (!removedDuplicates.contains(File.get(i))) {
removedDuplicates.add(File.get(i));
}
}
But it doesn't work, I guess because contains() for a List of File looks at the filepath instead of at the filename. Is it true? How can I solve my problem? I also tried with:
ArrayList<File> removedDuplicates = new ArrayList<File>();
for (int i = 0; i < File.size(); i++) {
if (!removedDuplicates.contains(File.get(i).getName())) {
removedDuplicates.add(File.get(i));
}
}
but still it doesn't work. Thanks
The type of getName is String and the type of object in your ArrayList is File, so you're never going to get the same thing.
You want to compare the names inside the ArrayList.
for(File f : files){
String fName = f.getName();
boolean found = false;
for(File f2 : removedDuplicates){
if(f2.getName().equals(fName)){
found = true;
break;
}
}
if(!found){
removedDuplicates.add(f);
}
}
Its very simple.
PS: Tested Code
Map<String, File> removedDuplicatesMap = new HashMap<String, File>();
for (int i = 0; i < files.size(); i++) {
String filePath = files.get(i).getAbsolutePath();
String filename = filePath.substring(filePath.lastIndexOf(System
.getProperty("file.separator")));
removedDuplicatesMap.put(filename, files.get(i));
}
ArrayList<File> removedDuplicates = new ArrayList<File>(
removedDuplicatesMap.values());
Try this:
ArrayList<File> removedDuplicates = new ArrayList<File>();
File temp;
for (int i = 0; i < File.size(); i++) {
temp=new File(File.get(i).getAbsolutePath());
if (!removedDuplicates.contains(temp)) {
removedDuplicates.add(File.get(i));
}
}
In my app i am getting the images from a folder in gallery and saving it into an array list.Now i want to extract only the files with .jpg extension.How can i do it
The code for saving to array list is
private List<String> ReadSDCard()
{
//It have to be matched with the directory in SDCard
File f = new File("sdcard/data/crak");
File[] files=f.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
/*It's assumed that all file in the path are in supported type*/
tFileList.add(file.getPath());
}
return tFileList;
}
You can use FilenameFilter interface to Filter the Files.
Change your codeline
File[] files=f.listFiles();
as below:
File[] jpgfiles = f.listFiles(new FileFilter() {
#Override
public boolean accept(File file)
{
return (file.getPath().endsWith(".jpg")||file.getPath().endsWith(".jpeg"));
}
});
Use .endsWith() method from Java String Class to check File Extension from file path.
Method:
public boolean endsWith(String suffix)
Your Code something like,
private List<String> ReadSDCard()
{
//It have to be matched with the directory in SDCard
File f = new File("sdcard/data/crak");
File[] files=f.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
/*It's assumed that all file in the path are in supported type*/
String filePath = file.getPath();
if(filePath.endsWith(".jpg")) // Condition to check .jpg file extension
tFileList.add(filePath);
}
return tFileList;
}
private List<String> ReadSDCard()
{
String extension = "";
File f = new File("sdcard/data/crak");
File[] files=f.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
int ind = files[i].getPath().lastIndexOf('.');
if (ind > 0) {
extension = files[i].getPath().substring(i+1);// this is the extension
if(extension.equals("jpg"))
{
tFileList.add(file.getPath());
}
}
}
return tFileList;
}
In your code add the following:
String filePath = file.getPath();
if(filePath.endsWith(".jpg"))
tFileList.add(filePath);
Let me get this out of the way; I am a beginner to java, I research the code I need and try to learn it while using it in my app.
I am currently stuck, not really sure how I can continue, ANY help is greatly appreciated.
I am trying to look in the /mnt/ folder for any folder with 'ext' or 'sd' in the file name. This is what I have so far, it gets me a null pointer exception but I don't know what variable is null.
public class MainActivity extends Activity
{
static File[] dirs;
#Override
public void onCreate(Bundle savedInstanceState)
{
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findMnt("/mnt/");
AlertDialog builder = new AlertDialog.Builder(this).setTitle("AppName").setMessage(dirs[0].getPath()).setNeutralButton("Close", null).show();
AlertDialog builder2 = new AlertDialog.Builder(this).setTitle("AppName").setMessage(dirs[1].getPath()).setNeutralButton("Close", null).show();
}
public static void findMnt(String path) {
File file = new File(path);
if(file.exists()){
File[] list = file.listFiles();
for(int i=0; i<list.length; i++) {
if(list[i].isDirectory()) {
if(list[i].getPath().contains("sd") || list[i].getPath().contains("ext")){
for(int b=0; b<list.length; b++){
dirs[b] = new File(list[i].getPath());
}
}
}
}
}
}
Memory Cases: if you take any new device or for ex. micromax funbook, then its having three memory
/data/data/ (phone internal memory) getFilesDirectory()
/mnt/sdcard/ (phone's internal sdcard)
Environment.getExternalStorageDirectory()
/mnt/extsd/ (External sdcard) /mnt/extsd
You first need to be sure whether your External card is of /mnt/sdcard/ or /mnt/extSd for that I have created a function
/**
* #return Number of bytes available on external storage extSD
*/
public long getExternalAvailableSpaceInBytes() {
long availableSpace = -1L;
try {
StatFs stat = new StatFs("mnt/extsd");
System.out.println("ExternalAvailableSpace Path : "+mStringExernalSD);
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
} catch (Exception e) {
e.printStackTrace();
}
return availableSpace;
}
if getExternalAvailableSpaceInBytes() returns 0 it means you need to consider /mnt/sd
To get all folders
ArrayList<File> mFiles= new ArrayList<File>();
if(getExternalAvailableSpaceInBytes()>0)
findMnt(mFiles, "/mnt/extsd");
else
findMnt(mFiles, "/mnt/sdcard");
public ArrayList<File> findMnt(ArrayList<File> files, File dir)
{
if (!dir.isDirectory())
{
files.add(dir);
return files;
}
for (File file : dir.listFiles())
findMnt(files, file);
return files;
}
This method is crude but will work for what I need it to. Searches for the sdcard folder, then searches for a folder with ext in the name, and if it fails it searches the sdcard folder for an ext folder.
String sd = findSd("/mnt/") + "/";
String ext = findExt("/mnt/") + "/";
if(ext == "ext not found"){
ext = findExt(sd + "/");
}
public static String findSd(String path){
File file = new File(path);
if(file.exists()){
File[] list = file.listFiles();
for(int i=0; i<list.length; i++) {
if(list[i].isDirectory()) {
if(list[i].getPath().contains("sd")){
return list[i].getPath();
}
}
}
}
return "sd not found";
}
public static String findExt(String path){
File file = new File(path);
if(file.exists()){
File[] list = file.listFiles();
for(int i=0; i<list.length; i++) {
if(list[i].isDirectory()) {
if(list[i].getPath().contains("ext") && list[i].getPath() != findSd("/mnt/")){
return list[i].getPath();
}
}
}
}
return "ext not found";
}
How can get total count of available media file in sdcard/some/ folder that should include audio, images, video.
I think something like this
File file=new File("/sdcard/domedir");
File[] list = file.listFiles();
int count = 0;
for (File f: list){
String name = f.getName();
if (name.endsWith(".jpg") || name.endsWith(".mp3") || name.endsWith(".some media extention"))
count++;
}
Maybe you should write a simple recursive method like this one :
public int countFile(String path) {
int count = 0;
File f = new File(path);
if (f.exists() && f.isDirectory()) {
for (File fi : f.listFiles()) {
if (fi.isDirectory())
count += countFile(fi.getAbsolutePath());
else
count++;
}
}
return count;
}
Well you can simply check whether the type of files correspond to common media types
static class MyDocFileFilter implements FileFilter{
private final String[] myDocumentExtensions
= new String[] {".java", ".png", ".avi", ".mkv"};
public boolean accept(File file) {
if (!file.isFile()) return false;
for (String extension : myDocumentExtensions) {
if (file.getName().toLowerCase().endsWith(extension))
return true;
}
return false;
}
}
Then use File to list all the required files using the filter. And change extensions accordingly
File file = new File("DIRECTORY_NAME");
File[] fileslist = file.listFiles(new MyMediaFileFilter());
How does one obtain images from the /DCIM/100ANDRO folder?
I have tried
File rootsd = Environment.getExternalStorageDirectory();
File dcim = new File(rootsd.getAbsolutePath() + "/DCIM/100ANDRO");
File[] imagelist = dcim.listFiles(new FilenameFilter(){
public boolean accept(File dir, String name)
{
return ((name.endsWith(".jpg"))||(name.endsWith(".png")));
}
});
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]);
}
but I got a Null Pointer Exception.
Have you remembered to give the app permission to write the external memory?
It is done in the AndroidManifest.xml file, by adding
"android.permission.WRITE_EXTERNAL_STORAGE"
Since you are making a new file object, this is needed, I would guess.