I have this file structure in my android project:
I want to read all the folder names and their file names contained in assets folder. I have tried so many things but I am not able to achieve my goal. Can somebody guide me to correct direction?
Thanks in advance.
You can read the filenames of a particular folder from assets as follows :
private List<String> getFileNames(Context context, String folderName) throws IOException {
AssetManager assetManager = context.getAssets();
String[] files = assetManager.list(folderName);
return Arrays.asList(files);
}
Simple read all the assets using the below function
public myClass(Context myContext) {
AssetManager mngr = myContext.getAssets();
InputStream is = mngr.open("assests.txt");
}
A simple getAssets().list("") will list all folders.
And files if there are. But you havenot.
Related
I have the following functionality to a desktop application with java and I want to do the same thing for a mobile application.
File f = new File(pathToFiles);
File[] files = f.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return (pathname.getName().endsWith(".img") ? true : false);
}
});
Now in my android class I access the same files stored in a folder inside assets using the AssetManager with the following way:
AssetManager assetManager = context.getAssets();
String[] files = assetManager.list("folderInsideAssets");
List<String> it = new LinkedList<String>(Arrays.asList(files));
The problem here is that I get them as string in a list instead of a File class like in plain java.
Is a way to convert it to a File[] class and proceed with the same way or I should handle this differently?
Thank you in advance!
Stackoverflow Question on loading pictures from asset
Yes, create another folder in assets directory. use getAssets().list(<folder_name>) for getting all file names from assets:
String[] images =getAssets().list("images");
ArrayList<String> listImages = new ArrayList<String>(Arrays.asList(images));
Now to set image in imageview you first need to get bitmap using image name from assets :
InputStream inputstream=mContext.getAssets().open("images/"
+listImages.get(position));
Drawable drawable = Drawable.createFromStream(inputstream, null);
imageView.setImageDrawable(drawable);
I have a project in Android Studio with a lot of libraries. The main project has an assets folder (which contains two folders) and the libraries don't have any assets folders.
I have this code:
public static final Pattern LENGUAJES = Pattern.compile("html-(.+)");
public static List<String> getLenguajesHelp(Context oContext) {
ArrayList<String> oLens = new ArrayList<String>();
AssetManager assetManager = oContext.getAssets();
try {
String[] oFiles = assetManager.list("");
for (int i = 0; i < oFiles.length; i++) {
Log.v("probandoElMatcher", oFiles[i]);
Matcher oMat = LENGUAJES.matcher(oFiles[i]);
if (oMat.find()) {
oLens.add(oMat.group(1));
}
}
} catch (IOException oEx) {
oEx.printStackTrace();
}
return oLens;
}
The Context is from the main project (in the assets folder I have a folder named html-es, the idea is that the method matches with that folder) but the method getAssets.list() returns a list of files that I don't have in the assets folder, the most of them are .pak files. What would be the problem?
The problem was that i has a lot of flavors, when there are flavors the assets folder must be inside of the main folder (or the specific flavor folder), but i don't know why the get assets returns the .pak files (know returns the .pak files and my files)
I have a question, why can't access a file in my assets folder?
Folder
My code
Uri path = Uri.parse("android.resource://com.hackro.tutorials.myapplication/raw/comprobante.pdf");
String newPath = path.toString();
Resources res = getResources();
try {
PdfReader reader = new PdfReader(newPath);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("/sdcard/evidencia.pdf"));
AcroFields fields = stamper.getAcroFields();
fields.setField("Referencia", referencia);
fields.setField("Fecha y Hora", fechahora);
fields.setField("Tipo", tipo);
fields.setField("Operacion", operacion);
fields.setField("no. tarjeta", tarjeta);
fields.setField("vencimiento", vencimiento);
fields.setField("monto", monto);
fields.setField("concepto", concepto);
fields.setField("Nombre", nombre);
fields.setField("Autorizacion", autorizacion);
stamper.setFormFlattening(true);
stamper.close();
reader.close();
} catch (Exception e) {
Log.e("error: ", e.getMessage());
}
Exception
java.io.IOException: android.resource://com.hackro.tutorials.myapplication/raw/comprobante.pdf not found as file or resource.
You have a few problems here.
First, resources are not assets. You are attempting to use the android.resource scheme to access an asset as if it were a raw resource, and this will not work.
Second, you are constructing a Uri, then are converting that to a string, then are trying to wrap that in a File object. That will never work, for any type of Uri.
Third, neither resources nor assets are files on the filesystem of the device. They are files on the filesystem of your development machine. They are entries in the APK file on the device. You cannot get a File object pointing to a resource or an asset.
Use getAssets() on a Context (e.g., your Activity or Service) to get an AssetManager. Then, call open("comprobante.pdf") on that AssetManager to get an InputStream on the asset. Pass that to the PdfReader constructor and hope that your PDF library supports an InputStream.
My application files are bellow, I want to get sharethis.png file in java code , What is syntax ?
I used this ...
Bitmap bMap = BitmapFactory.decodeFile("file:///android_asset/www/sharethis.png");
but not working
Try:
Bitmap shareThis = BitmapFactory.decodeResource(context.getResources(),
R.drawable.shareThis);
If you want to reference it from a JavaScript or html file in your assets folder, use file:///android_asset/www/sharethis.jpg.
Otherwise, according to this answer, this will list all the files in the assets folder:
AssetManager assetManager = getAssets();
String[] files = assetManager.list("");
This to open a certain file:
InputStream input = assetManager.open(assetName);
Try this:
try {
// get input stream
InputStream ims = getAssets().open("sharethis.png");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
mImage.setImageDrawable(d);
}
catch(IOException ex) {
Log.e("I/O ERROR","Failed")
}
Instead of using the assets dir, put the file into /res/raw , and you can then access it using the following URI: android.resource://com.your.packagename/" + R.raw.sharethis
In J2ME, I've do this like that:
getClass().getResourceAsStream("/raw_resources.dat");
But in android, I always get null on this, why?
For raw files, you should consider creating a raw folder inside res directory and then call getResources().openRawResource(resourceName) from your activity.
InputStream raw = context.getAssets().open("filename.ext");
Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));
In some situations we have to get image from drawable or raw folder using image name instead if generated id
// Image View Object
mIv = (ImageView) findViewById(R.id.xidIma);
// create context Object for to Fetch image from resourse
Context mContext=getApplicationContext();
// getResources().getIdentifier("image_name","res_folder_name", package_name);
// find out below example
int i = mContext.getResources().getIdentifier("ic_launcher","raw", mContext.getPackageName());
// now we will get contsant id for that image
mIv.setBackgroundResource(i);
Android access to raw resources
An advance approach is using Kotlin Extension function
fun Context.getRawInput(#RawRes resourceId: Int): InputStream {
return resources.openRawResource(resourceId)
}
One more interesting thing is extension function use that is defined in Closeable scope
For example you can work with input stream in elegant way without handling Exceptions and memory managing
fun Context.readRaw(#RawRes resourceId: Int): String {
return resources.openRawResource(resourceId).bufferedReader(Charsets.UTF_8).use { it.readText() }
}
TextView txtvw = (TextView)findViewById(R.id.TextView01);
txtvw.setText(readTxt());
private String readTxt()
{
InputStream raw = getResources().openRawResource(R.raw.hello);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try
{
i = raw.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = raw.read();
}
raw.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
TextView01:: txtview in linearlayout
hello:: .txt file in res/raw folder (u can access ny othr folder as wel)
Ist 2 lines are 2 written in onCreate() method
rest is to be written in class extending Activity!!
getClass().getResourcesAsStream() works fine on Android. Just make sure the file you are trying to open is correctly embedded in your APK (open the APK as ZIP).
Normally on Android you put such files in the assets directory. So if you put the raw_resources.dat in the assets subdirectory of your project, it will end up in the assets directory in the APK and you can use:
getClass().getResourcesAsStream("/assets/raw_resources.dat");
It is also possible to customize the build process so that the file doesn't land in the assets directory in the APK.
InputStream in = getResources().openRawResource(resourceName);
This will work correctly. Before that you have to create the xml file / text file in raw resource. Then it will be accessible.
Edit Some times com.andriod.R will be imported if there is any error in layout file or image names. So You have to import package correctly, then only the raw file will be accessible.
This worked for for me: getResources().openRawResource(R.raw.certificate)