How to retrieve file content using full path? - android

In Android webview, you could pass something like this file:///android_asset/myfile.txt or this http://www.mysite.com/t.html and it will get it without a problem. Now if I tried the first url with the file prefix in a reader "FileReader" it will throw an exception that File not found although in WebView it work with no problem (why?)
What I want is to create a function that could take a file or http url and get the content html using the full path "file:/// ..." how could I do this without facing the file not found exception ?

Now if i tried the first url with the file prefix in a reader "FileReader" it will throw an exception that file not found although in WebView it work with no problem (why?)
Because "File Reader" does not have an asset named /myfile.txt, presumably. "File Reader" is somebody else's program, not yours, so file:///android_asset/myfile.txt refers to an asset in that other program, not yours.
What i want is to create a function that could take a file or http url and get the content html using the full path "file:/// ..." how could i do this without facing the file not found exception ?
Have an asset named /myfile.txt in your app.
I have not tried using standard Java I/O (e.g., File objects) to read file:///android_asset paths. That might work. If not, use startsWith() to determine if the string begins with file:///android_asset -- if it does, trim that off and use the rest with AssetManager to read the asset.

Related

How to get actual path to video from onActivityResult

I have a video that I save to .../Movies/MyApp/abcde.mp4. So I know where it is. When I load it through my app using an implicit intent to ACTION_GET_CONTENT, the path is returned as content:/media/external/video/media/82 when I do
data.getData().toString()
The problem with that path is that it works when I try to access it with MediaRecorder as
mVideoView.setVideoURI(Uri.parse(mVideoStringPath))
However if I try to convert it to a path in another thread (for a job queue), the file is not found
new File(mVideoStringPath)
when I use the technique (copy and paste) described at How to get file path in onActivityResult in Android 4.4, still get the error
java.lang.RuntimeException: Invalid image file
Also per my logging, the new technique shows the path to the video as
video path: /storage/emulated/0/Movies/MyApp/abc de.mp4
notice the space in abc de.mp4. that indeed is the name of the file. And the phone's camera app has no trouble playing
However if I try to convert it to a path in another thread (for a job queue), the file is not found
That is because it is not a path to a file. It is a Uri, which is an opaque handle to some data.
How to get actual path to video from onActivityResult
You don't. You use the Uri. There is no requirement that the Uri point to a file. There is no requirement that the Uri, if it happens to represent a file, represent one that you have direct filesystem access to.
you need to escape the space the the file path in order to construct a File object from it.
filepath.replace(" ", "\\ ");

About Android webview file upload

I am using webview in android app, the webview will load a html page contains file upload control.I override the "openFileChooser" function, so I can select file in webview,but after I choose file and return to webview, the file name while change to url-encoded format(If the file name isn't ascii character) ?
There's nothing you can (or should) do here.
The operating system handles these things, i.e. placing the selected file in the value attribute of the <input type="file">.
But there's nothing wrong with these URL-encoded names. You shouldn't rely on the filenames from the client side, anyway.
What you should use is only the file's content and maybe its size and extension as reported.

C++ OpenCV imread not working in Android

I am trying to read an image in my C++ code
LOGD("Loading image '%s' ...\n", (*inFile).c_str());;
Mat img = imread(*inFile, CV_LOAD_IMAGE_GRAYSCALE);
CV_Assert(img.data != 0);
and get the following output:
09-25 17:08:24.798: D/IRISREC(12120): Loading image '/data/data/com.example.irisrec/files/input/osoba1.jpg' ...
09-25 17:08:24.798: E/cv::error()(12120): OpenCV Error: Assertion failed (img.data != 0) in int wahet_main(int, char**), file jni/wahet.cpp, line 4208
The file exists. But strange is, that if I try to preview the image using Root File Browser it is just black. I copied the files there manually.
EDIT:
The code works fine under Windows with .png and .jpg format. I am just trying to port an existing C++ project for Iris Recognition to Android.
imread() determines the type of file based on its content not by the file extension. If the header of the file is corrupted, it makes sense that the method fails.
Here are a few things you could try:
Copy those images back to the computer and see if they can be opened by other apps. There's a chance that they are corrupted in the device;
Make sure there is a file at that location and that your user has permission to read it;
Test with types of images (jpg, png, tiff, bmp, ...);
For testing purposes it's always better to be more direct. Get rid of inFile:
Example:
Mat img = imread("/data/data/com.example.irisrec/files/input/osoba1.jpg", CV_LOAD_IMAGE_GRAYSCALE);
if (!img.data) {
// Print error message and quit
}
When debugging, first try to get more data on the problem.
It's an unfortunate design that imread() doesn't provide any error info. The docs just say that it'll fail "because of missing file, improper permissions, unsupported or invalid format".
Use the debugger to step into the code if you can. Can you tell where it fails?
Search for known problems, stackoverflow.com/search?q=imread, e.g. imread not working in OpenCV.
Then generate as many hypotheses as you can. For each one, think of a way to test it. E.g.
The image file is malformed (as #karlphillip offered). -- See if other software can open the file.
The image file is not a supported format. -- Verify the file format on your desktop. Test that desktop OpenCV can read it. Check the docs to verify the image formats that AndroidCV can read.
The image file is not at the expected path. -- Write code to test if there's a file at that path, and verify its length.
The image file does not have read permission. -- Write code to open the file for reading.
A problem with the imread() arguments. -- Try defaulting the second argument.
I was able to solve this issue only by copying the image files in code.I stored them in my asset folder first and copied them to internal storage following this example.
If someone can explain this to me please do this.
It could be a permission issue.You would have to request the permission from Java code in your Activity class like this in Android 6.0 or above. Also make sure that in your AndroidManifest.xml, you have the the following line :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
In your activity file add this:
if (PermissionUtils.requestPermission(
this,
HOME_SCREEN_ACTIVITY,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
Mat image = Imgcodecs.imread(filePath,Imgcodecs.IMREAD_COLOR);
}
I struggled a long time to find this and I was getting Mat object null for all the time before.

Loading html file from local folder into webview

I'm new to Android development.
I want to load a html file into a webview.
Note that there are so many relevant questions on SO like this, but they all deal with getting **.html* from assets folder.
But I want to load html file from local folder, say "D://abc.html" because if my html is around 10Mb then corresponding apk size also goes upto 10mb.
Any help appreciated.
EDIT
I tried webView.loadUrl("file:///D:/Projects/myWebsite/index.html");
but it gives Web page not available and File not found error.
You can use:
WebView webView = // ...
webView.loadUrl("file:///myPath/myFile.html");
In an Android application, files can be read from 3 types of locations:
Internal storage: Each app has its own, file names are relative to this location. URL takes form file:///myFolder/myFile.html
External storage: Needs permission and may not always be available. Get the root folder by calling Environment.getExternalStorageDirectory(). So, construct the URL using: String url = "file:///" + Environment.getExternalStorageDirectory().toString() + File.separator + "myFolder/myFile.html"
Assets: Stored in the apk. Read-only access. URL takes form file:///android_asset/myFolder/myFile.html (See also Loading an Android Resource into a WebView)
In Android 4.4 KitKat, a "Not allowed to load local resource: file:///.." is thrown.
arise when loadURL and the only alternative I've found is "loadDataWithBaseURL".
webView.loadDataWithBaseURL("file:///android_asset/demo/",
tmpDocumentText,"text/html", "UTF-8", null);
WebView has loadData method http://developer.android.com/reference/android/webkit/WebView.html
All you need to do is reading the file into String then feed it to WebView using loadData.
either one can use this way to load file specifically if the file is present within android studio project
(pls note android_res is res folder actually and should not be replaced)
webView.loadUrl("file:///android_res/drawable/FILENAME.EXTENSION");
but if that is not working please try another way of loading file like
webView.loadDataWithBaseURL("file:///android_asset/demo/",tmpDocumentText,
"text/html", "UTF-8", null);

android: Check the existence of a file in the application

I have few html files in assets folder of my application. My application loads these files depending on the device language. When I check for the existance of the file it say does not exist, but when I load that file using browser.loadUrl(filename), it loads it fine.
Following code will help you to understand my problem:
String filename="file:///android_asset/actualfilemname.html";
File f = new File(filename);
if(!f.exist){
filename = "file:///android_asset/newfile.html";[Everytime it loads this file even though I have actualfilename.html in the folder]
}
browser.loadUrl(filename);
[it loads the newfile.html but not actualfilename.html]
You can't use File for resources. You'll need to use the AssetManager for that.
(In the off-chance that File does handle resources, which I don't think it does, you'll have to convert the path to a URI first, for example using URI.create(). File(String) expects a path, not a URI.)
Is this the exact code you are using? you probably want to be calling f.exists() not filename.exist().
Edit: try working with the AssetManager instead of hard coding your file path. My best guess is that the file path you are using is not exactly how it supposed to be.

Categories

Resources