how to check a html file exist in assets folder - android

Assets
|-man
| |-myhtml.html
|
|-women
| |-myhtml.html
this is my folder structure some times i need to check the file exist in men some times i need to check the file exist in women what can i do.
try {
fileExist = Arrays.asList(getResources().getAssets().list("")).contains(pathInAssets);
} catch (FileNotFoundException e) {
fileExist = false;
} catch (IOException e) {
e.printStackTrace();
}
this give only the list man and women i cant go inside it and check the existance.
Is their any other way to check this

use below method to get file from assets folder.
i provide code get all .mp4 file and store file into string list.
private List<String> videoList=new ArrayList<>();
private boolean listAssetFiles(String path) {
String [] list;
try {
list = getAssets().list(path);
if (list.length > 0) {
// This is a folder
for (String file : list) {
if (!listAssetFiles(path + "/" + file))
return false;
else {
// This is a file
// TODO: add file name to an array list
if (file.contains(".mp4") || file.contains(".mp3") ) {
videoList.add(file);
}
}
}
}
} catch (IOException e) {
return false;
}
return true;
}
when you call this method pass only ..
listAssetFiles(""); // you can pass your path if is empty then it scan root.

Just open an input stream for the file. As if you were going to read the file.
If you manage to open it the file does exist. Otherwise you get an exception.

Related

Dropbox api v2 for Android: how to get media files details?

How to get media files and their details with Dropbox API v2 for Android(Java)? I have gone through the documentation for the FileMetadata , but I couldn't find the methods to get file details like file type(e.g. music, video, photo, text, ...) , file's URL and thumbnail.
this is my folders and files list Asyntask:
//login
DbxClientV2 client = DropboxClient.getClient(accessToken);
// Get files and folder metadata from root directory
String path = "";
TreeMap<String, Metadata> children = new TreeMap<>();
try {
try {
result = client.files().listFolder(path);
arrayList = new ArrayList<>();
//arrayList.add("/");
while (true) {
int i = 0;
for (Metadata md : result.getEntries()) {
if (md instanceof DeletedMetadata) {
children.remove(md.getPathLower());
} else {
String fileOrFolder = md.getPathLower();
children.put(fileOrFolder, md);
//if (!fileOrFolder.contains("."))//is a file
arrayList.add(fileOrFolder);
if (md instanceof FileMetadata) {
FileMetadata file = (FileMetadata) md;
//I need something like file.mineType, file.url, file.thumbnail
file.getParentSharedFolderId();
file.getName();
file.getPathLower();
file.getPathDisplay();
file.getClientModified();
file.getServerModified();
file.getSize();//in bytes
MediaInfo mInfo = file.getMediaInfo();//Additional information if the file is a photo or video, null if not present
MediaInfo.Tag tag;
if (mInfo != null) {
tag = mInfo.tag();}
}
}
i++;
}
if (!result.getHasMore()) break;
try {
result = client.files().listFolderContinue(result.getCursor());//what is this for ?
} catch (ListFolderContinueErrorException ex) {
ex.printStackTrace();
}
}
} catch (ListFolderErrorException ex) {
ex.printStackTrace();
}
} catch (DbxException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
If you want media information, you should use listFolderBuilder to get a ListFolderBuilder object. You can use call .withIncludeMediaInfo(true) to set the parameter for media information, and then .start() to make the API call. The results will then have the media information set, where available.
Dropbox API v2 doesn't offer mime types, but you can keep your own file extension to mime type mapping as desired.
To get an existing link for a file, use listSharedLinks. To create a new one, use createSharedLinkWithSettings.
To get a thumbnail for a file, use getThumbnail.

List all files, recursively, in Android Dropbox API

How can I list all files, recursively in DropBox folder?
I tried code below but returns no result:
result = dbxClient.files().search("", "*");
And this returns files in path, not subfolders:
result = dbxClient.files().listFolder(path);
You can get a ListFolderBuilder from listFolderBuilder and use the withRecursive option to list out sub-items as well.
Be sure to check ListFolderResult.hasMore to see if you should call back to listFolderContinue to get more results though.
You can check this link, navigate to inner class 'FolderScanTask'. It contains working code for Android:
https://github.com/ControlX/Android-Dropbox-UploadImage-To-SpecificFolder-By-FolderSelection/blob/master/app/src/main/java/io/github/controlx/dbxdemo/MainActivity.java
This is work in progress, here I'm just making an ArrayList for parent folders, has more logic as suggested by Greg is already there you just need to fill in that.
Code Snippet for the same:
String path = "";
DbxClientV2 dbxClient = DropboxClient.getClient(ACCESS_TOKEN);
TreeMap<String, Metadata> children = new TreeMap<String, Metadata>();
try {
try {
result = dbxClient.files()
.listFolder(path);
} catch (ListFolderErrorException ex) {
ex.printStackTrace();
}
List<Metadata> list = result.getEntries();
cs = new CharSequence[list.size()];
arrayList = new ArrayList<>();
arrayList.add("/");
while (true) {
int i = 0;
for (Metadata md : result.getEntries()) {
if (md instanceof DeletedMetadata) {
children.remove(md.getPathLower());
} else {
String fileOrFolder = md.getPathLower();
children.put(fileOrFolder, md);
if(!fileOrFolder.contains("."))
arrayList.add(fileOrFolder);
}
i++;
}
if (!result.getHasMore()) break;
try {
result = dbxClient.files()
.listFolderContinue(result.getCursor());
} catch (ListFolderContinueErrorException ex) {
ex.printStackTrace();
}
}
} catch (DbxException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Here ArrayList is just for my use wherein I'm just making a list of only folders.
So, modify accordingly.

Android - isDirectory always returns false for new File(pathToDirectoryString)

Our aim is to set readable and writable permissions on folders. using [setReadable(bool)][1] and [setWritable(bool)][1]. That is it.
We're already writing files to them and reading files from them, but as a precaution, we want to explicitly set these permissions.
The code is below. Does something get lost from mkdirs() to getAbsolutePath() to new File to isDirectory()? Because for some reason, when we check if the folderPath is a directory, it ALWAYS returns false, even though the log clearly identifies it as a path to a directory...
//This is in the onCreate function of the service.
File mainFolder = new File(thisService.this.getExternalFilesDir(null), "mainFolder");
if (!mainFolder.exists()) {
//The folder doesn't exist yet, so create it.
mainFolder.mkdirs();
//And then make the other folders we'll need.
File confsFolder = new File(File mainFolder.getAbsoluteFile()+"/confs");
confsFolder.mkdirs();
File logsFolder =new File(File mainFolder.getAbsoluteFile()+"/logs");
logsFolder.mkdirs();
File packagesFolder = new File(File mainFolder.getAbsoluteFile()+"/packages");
packagesFolder.mkdirs();
}
//String variables holding the folder paths.
confsFolderPathString = mainFolder.getAbsolutePath() + "/confs/ ";
logsFolderPathString = mainFolder.getAbsolutePath() + "/logs/ ";
packagesFolderPathString = mainFolder.getAbsolutePath() + "/packages/ ";
setPermissions(new File(confsFolderPathString));
setPermissions(new File(logsFolderPathString));
setPermissions(new File(packagesFolderPathString));
...elswhere in the service...
private void setPermissions(File folderPath) {
Log.d(TAG, "setPermissions: ");
//Credit to: http://stackoverflow.com/a/11482350/956975
Log.d(TAG, "setPermissions: folderPath -> "+folderPath.getAbsoluteFile());
//That log produces this strings:
//setPermissions: folderPath -> /storage/emulated/0/Android/data/our.package.domain.and.project/files/mainFolder/confs/
//setPermissions: folderPath -> /storage/emulated/0/Android/data/our.package.domain.and.project/files/mainFolder/logs/
//setPermissions: folderPath -> /storage/emulated/0/Android/data/our.package.domain.and.project/files/mainFolder/packages/
//Those are DIRECTORIES, right?
//Get the list of files (which could include folders) in the folderPath.
if(folderPath.isDirectory()){ //<-------------THIS IS ALWAYS FALSE
File[] list = folderPath.listFiles();
if(list != null && list.length > 0){
for (File f : list) {
if (f.isDirectory()) {
Log.d("setPermissions: ", "Dir: " + f.getAbsoluteFile());
//Set readable permissions
f.setReadable(true);
//Set writable permissions
f.setWritable(true);
//Go deeper into the directory
setPermissions(f, true, true);
} else {
Log.d("setPermissions: ", "File: " + f.getAbsoluteFile());
//Set readable permissions
f.setReadable(true)
//Set writable permissions
f.setWritable(true);
}
}
}else{
try {
throw new Exception("setPermissions: Directory list is empty.");
} catch (Exception e) {
Log.e(TAG, "setPermissions: Directory list is empty.", e);
}
}
}else{
try {
throw new FileNotFoundException("setPermissions: "+folderPath.getAbsolutePath() + " is not a directory.");
} catch (FileNotFoundException e) {
Log.e(TAG, "setPermissions: "+folderPath.getAbsolutePath()+" is not a directory.", e);
}
}
}
I think it is returning false because the directory does not exist yet when you call isDirectory().
So, before check if it's a directoty, chec if exists:
private void setPermissions(File folderPath) {
...
if(folderPath.exists() && folderPath.isDirectory()) {
// ALL FUNCTIONALITY
}
}
EDIT:
You have a mistake in the if comprobation for create directories. You are checking !File instead of !mainFolder.exists()
if (!File mainFolder.exists()) {
replace it by
if (!mainFolder.exists()) {

Reading text from Google Drive files

Is there any possible way to read the text from a file on Google Drive and store it in a String? This file may contain images as well. I was looking into the Google Drive SDK but they only allow us to download the entire file. How should I go about doing this?
From Files.get() documentation.
private static InputStream downloadFile(Drive service, File file) {
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
try {
HttpResponse resp =
service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl()))
.execute();
return resp.getContent();
} catch (IOException e) {
// An error occurred.
e.printStackTrace();
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
You can convert InputStream to String or File as you want.

In android how to programmatically clear web cache without clearing database

I m developing an android app in which i'm integrating facebook functionality as suggested in this blog http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/
as i'm able to login first time but after logout i cannot able to login again as webcache get created in my application data....
is there any way which i can use to solve my problem ......is i have use below code as suggested here but it cannot delete delete my webcache...
static int clearCacheFolder(final File dir, final int numDays) {
int deletedFiles = 0;
if (dir != null && dir.isDirectory()) {
try {
for (File child : dir.listFiles()) {
// first delete subdirectories recursively
if (child.isDirectory()) {
deletedFiles += clearCacheFolder(child, numDays);
}
// then delete the files and subdirectories in this dir
// only empty directories can be deleted, so subdirs have
// been done first
if (child.lastModified() < new Date().getTime() - numDays
* DateUtils.DAY_IN_MILLIS) {
if (child.delete()) {
deletedFiles++;
}
}
}
} catch (Exception e) {
Log.e("error Tag",
String.format("Failed to clean the cache, error %s",
e.getMessage()));
}
}
return deletedFiles;
}
please do suggest some another way to delete my webcache without deleting my database.....

Categories

Resources