Why does AssetManager list() not show my assets folder? - android

In my Android app I have packaged a file in the /assets folder that needs to be copied to the SDCARD. When I list the contents of the assets folder to a String[] I get "images", "sounds", "webkit" and "kioskmode" but not my file manually added to the assets folder.
My code is here:
private void copyAsset () {
AssetManager am = getApplicationContext().getAssets();
String[] files = null;
try {
files = am.list("");
} catch (IOException e) {
}
for (String filename : files) {
if (filename.equals("images") || filename.equals("kioskmode") ||
filename.equals("sounds") || filename.equals("webkit")) {
Log.i(TAG, "Skipping folder " + filename);
continue;
}
InputStream in = null;
OutputStream out = null;
try {
in = am.open(filename);
File outFile = new File(Environment.getExternalStorageDirectory().getPath(), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Error copying asset ", e);
}
}
}
Does it make a difference that this is a second class in my app and is called in my MainActivity using Intent showHelper = new Intent(this, HelperManager.class);
startActivity(showHelper); ?
I have tried the 2nd line (AssetManager am = ...) with and without the getApplicationContext() bit, tried moving the file into a subfolder of /assets and tried files = am.list("") with leading and trailing slashes. If I use a subfolder the files array is empty when the code runs (set a breakpoint on the files = am.list(""); line and inspected it at run time.
The strange thing is that it worked once - when I first wrote the code, but for further testing, I deleted the file from the /sdcard folder on the phone, and it never worked since even though the file is still in the assets folder.
I am using Android Studio if that matters.
Thanks

Managed to get a solution using Load a simple text file in Android Studio as a fix. It still puts the 4 folders in the files array but I Can skip them using code as given above, although I should rather check for the file I want rather than the 4 I don't!

Related

FileNotFoundException while reading an uploaded file

I'm trying to convert an IOS App to Android. I have no experience in Android so it may be a silly question. Sorry for that:)
I've uploaded some json files into the "files" folder of the emulator by device file explorer. (not into the external storage)
But when reading them, FileNotFoundException is thrown. (Permission denied) The code I used for reading is as below;
try {
File file = new File(getApplicationContext().getFilesDir() + "/Data/Users/profile.json");
FileReader fileReader = new FileReader(file);
String contents = "";
int i;
while((i = fileReader.read())!= -1) {
char ch = (char)i;
contents += ch;
}
return contents;
} catch (IOException e) {
e.printStackTrace();
}
I've tried to form those files programmatically in the same directory under "files" folder, as below.
String string = "{}";
File file = new File(getApplicationContext().getFilesDir() + "/Data/Users");
file.mkdirs();
File file2 = new File(getApplicationContext().getFilesDir() + "/Data/Users/profile.json");
file2.createNewFile();
FileOutputStream fos = new FileOutputStream(file2);
fos.write(string.getBytes());
fos.close();
This time, I managed to read them successfully by using the above code. It seems uploading files by device file explorer leads to some permission problems. I couldn't find how to modify them. How can I fix this?

How to access a file from asset/raw directory

with this below code i'm trying to access the file which is stored in asset/raw folder, but getting null and
E/ERR: file:/android_asset/raw/default_book.txt (No such file or directory)
error, my code is:
private void implementingDefaultBook() {
String filePath = Uri.parse("file:///android_asset/raw/default_book.txt").toString();
File file = new File(filePath);
try {
FileInputStream stream = new FileInputStream(file);
} catch (Exception e) {
e.printStackTrace();
Log.e("ERR ", e.getMessage());
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
}
Place your text file in the /assets directory under the Android project and use AssetManager class as follows to access it.
AssetManager am = context.getAssets();
InputStream is = am.open("default_book.txt");
Or you can also put the file in the /res/raw directory, from where the file can be accessed by an id as follows
InputStream is =
context.getResources().openRawResource(R.raw.default_book);
Assets and resources are files on your development machine. They are not files on the device.
For assets, use open() on AssetManager to get an InputStream on your asset.
Also, FWIW:
Uri.parse("file:///android_asset/raw/default_book.txt").toString() is pointless, as it gives you the same string that you started with
file:///android_asset/ only works for WebView
As the actual question wasn't sufficiently answered, here we go
InputStream is = context.getAssets().openFd("raw/"+"filename.txt")
context can be this or getActivity() or basically any other context
Important is to include the folder before the filename separated by an /
In Kotlin we can achieve as-
val string = requireContext().assets.open("default_book.txt").bufferedReader().use {
it.readText()
}
InputStream is = getAssets().open("default_book.txt");

Cannot add a eng.traineddata to my Tesseract project Android 5.0

I am currently trying to implement Tesseract OCR into my project but have came to a crossing road. I followed all of the directions from https://github.com/rmtheis/tess-two and got stuck at the actual implementation portion of this project. The current code I have running is:
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.init(TESS_DATA_FILE_PATH, "eng");
baseApi.setImage(icon);
String recognizedText = baseApi.getUTF8Text();
baseApi.end();
Now the TESS_DATA_FILE_PATH is the current issue. I have been trying to add the eng.traineddata file to my project, but I simply do not know where or how to do it.
Things I have tried:
In the assets folder I added the file eng.traineddata but that is read only and I cannot change it at run time. So this wont work
I tried to add in other ways of running the project, and running the adb push command to add it directly to the device, but that wont work since I will be pushing this application to the masses.
So what I am looking for is an answer of, How do I add the eng.traineddata to my project. And what do I place in the TESS_DATA_FILE_PATH part of the init call.
Side Notes:
I did receive the BUILD SUCCESSFUL call at the end of all the steps at the link provided above.
I have successfully added the language pack to my project, and ran tess two on my android project.
Here is the code for how I did it:
This is what sets up the files path, and adds the traineddata folder
public void setupOCR(){
File folder = new File(Environment.getExternalStorageDirectory() + "/classlinkp/tessdata");
if (!folder.exists()) {
folder.mkdirs();
}
File saving = new File(folder, "eng.traineddata");
try {
saving.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
InputStream stream = null;
try {
stream = mContext.getAssets().open("eng.traineddata", AssetManager.ACCESS_STREAMING);
} catch (IOException e) {
e.printStackTrace();
}
if (stream != null){
copyInputStreamToFile(stream, saving);
}
}
Here is how I saved out the eng.traineddata file:
private void copyInputStreamToFile( InputStream in, File file ) {
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The saving method was gathered from: https://stackoverflow.com/a/28131358/3781164

I need to be able to store sound files for my application on sdcard

I've read a lot of topics but none seem to cover what I need.
I basically have a load of sound files and I want to be able to play them in the application from the sdcard.
I also want to be able to install them there in the first place when the application is installed.
I am using Eclipse with the android SDK and currently my Target project is v1.6
Can anyone help?
Thanks
OK so I found the answer!
First we need to get the external Storage Directory to a variable called baseDir.
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
Then Create the directory mysounds on the SDcard
File folder = new File(Environment.getExternalStorageDirectory() + "/mysounds");
boolean success = false;
if(!folder.exists())
{
success = folder.mkdir();
}
if (!success)
{
// Do something on success
}
else
{
// Do something else on failure
}
Then This following bit of code will copy all the files with sound at the beginning of the name from the assets directory to the mysounds directory you have already created.
try {
AssetManager am = getAssets();
String[] list = am.list("");
for (String s:list) {
if (s.startsWith("sound")) {
Log.d("Notice", "Copying asset file " + s);
InputStream inStream = am.open(s);
int size = inStream.available();
byte[] buffer = new byte[size];
inStream.read(buffer);
inStream.close();
FileOutputStream fos = new FileOutputStream(baseDir + "/mysounds/" + s);
fos.write(buffer);
fos.close();
}
}
}
Hope this helps someone!

How to read file from phone's internal memory in android?

I have downloaded a file from HttpConnection using the FileOutputStream in android and now its being written in phone's internal memory on path as i found it in File Explorer
/data/data/com.example.packagename/files/123.ics
Now, I want to open & read the file content from phone's internal memory to UI. I tried to do it by using the FileInputStream, I have given just filename with extension to open it but I am not sure how to mention the file path for file in internal memory,as it forces the application to close.
Any suggestions?
This is what I am doing:
try
{
FileInputStream fileIn;
fileIn = openFileInput("123.ics");
InputStream in = null;
EditText Userid = (EditText) findViewById(R.id.user_id);
byte[] buffer = new byte[1024];
int len = 0;
while ( (len = in.read(buffer)) > 0 )
{
Userid.setText(fileIn.read(buffer, 0, len));
}
fileIn.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
String filePath = context.getFilesDir().getAbsolutePath();//returns current directory.
File file = new File(filePath, fileName);
Similar post here
read file from phone memory
If the file is where you say it is, and your application is com.example.packagename, then calling openFileInput("123.ics"); will return you a FileInputStream on the file in question.
Or, call getFilesDir() to get a File object pointing to /data/data/com.example.packagename/files, and work from there.
I am using this code to open file in internal storage. i think i could help.
File str = new File("/data/data/com.xlabz.FlagTest/files/","hello_file.xml");

Categories

Resources