not found as file or resource in assets folder - android

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.

Related

Access resources from Android library

I'm using Android Studio 2.0 and I've created an Android library to keep some classes and a XML data file. The file is placed in the /res directory but I cannot find any way to access it. I always get a FileNotFoundException.
The code I use to open and serialize the file is:
try {
SomeClass someClass = new SomeClass();
someClass.entries = new ArrayList<SomeEntry>();
Serializer serializer = new Persister();
InputStream file=assetManager.open("simple.xml");
someClass= serializer.read(SomeClass.class, file);
}
catch (Exception ex)
{
ex.getMessage();
}
simple.xml should be inside assets folder.
And make sure that assetManager object is equal to getApplicationContext().getAssets().open("simple.xml");

How to get path of any file from my my application data folder

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

How to get URI from an asset File?

I have been trying to get the URI path for an asset file.
uri = Uri.fromFile(new File("//assets/mydemo.txt"));
When I check if the file exists I see that file doesn't exist
File f = new File(filepath);
if (f.exists() == true) {
Log.e(TAG, "Valid :" + filepath);
} else {
Log.e(TAG, "InValid :" + filepath);
}
Can some one tell me how I can mention the absolute path for a file existing in the asset folder
There is no "absolute path for a file existing in the asset folder". The content of your project's assets/ folder are packaged in the APK file. Use an AssetManager object to get an InputStream on an asset.
For WebView, you can use the file Uri scheme in much the same way you would use a URL. The syntax for assets is file:///android_asset/... (note: three slashes) where the ellipsis is the path of the file from within the assets/ folder.
The correct url is:
file:///android_asset/RELATIVEPATH
where RELATIVEPATH is the path to your resource relative to the assets folder.
Note the 3 /'s in the scheme. Web view would not load any of my assets without the 3. I tried 2 as (previously) commented by CommonsWare and it wouldn't work. Then I looked at CommonsWare's source on github and noticed the extra forward slash.
This testing though was only done on the 1.6 Android emulator but I doubt its different on a real device or higher version.
EDIT: CommonsWare updated his answer to reflect this tiny change. So I've edited this so it still makes sense with his current answer.
Finally, I found a way to get the path of a file which is present in assets from this answer in Kotlin. Here we are copying the assets file to cache and getting the file path from that cache file.
#Throws(IOException::class)
fun getFileFromAssets(context: Context, fileName: String): File = File(context.cacheDir, fileName)
.also {
if (!it.exists()) {
it.outputStream().use { cache ->
context.assets.open(fileName).use { inputStream ->
inputStream.copyTo(cache)
}
}
}
}
Get the path to the file like:
val filePath = getFileFromAssets(context, "fileName.extension").absolutePath
Please try this code working fine
Uri imageUri = Uri.fromFile(new File("//android_asset/luc.jpeg"));
/* 2) Create a new Intent */
Intent imageEditorIntent = new AdobeImageIntent.Builder(this)
.setData(imageUri)
.build();
Be sure ,your assets folder put in correct position.
Works for WebView but seems to fail on URL.openStream(). So you need to distinguish file:// protocols and handle them via AssetManager as suggested.
Try this out, it works:
InputStream in_s =
getClass().getClassLoader().getResourceAsStream("TopBrands.xml");
If you get a Null Value Exception, try this (with class TopBrandData):
InputStream in_s1 =
TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml");
InputStream is = getResources().getAssets().open("terms.txt");
String textfile = convertStreamToString(is);
public static String convertStreamToString(InputStream is)
throws IOException {
Writer writer = new StringWriter();
char[] buffer = new char[2048];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
String text = writer.toString();
return text;
}
try this :
Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.cat);
I had did it and it worked
Yeah you can't access your drive folder from you android phone or emulator because your computer and android are two different OS.I would go for res folder of android because it has good resources management methods. Until and unless you have very good reason to put you file in assets folder. Instead You can do this
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.yourfile);
byte[] b = new byte[in_s.available()];
in_s.read(b);
String str = new String(b);
} catch (Exception e) {
Log.e(LOG_TAG, "File Reading Error", e);
}
If you are okay with not using assets folder and want to get a URI without storing it in another directory, you can use res/raw directory and create a helper function to get the URI from resID:
internal fun Context.getResourceUri(#AnyRes resourceId: Int): Uri =
Uri.Builder()
.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
.authority(packageName)
.path(resourceId.toString())
.build()
Now if you have a mydemo.txt file under res/raw directory you can simply get the URI by calling the above helper method
context.getResourceUri(R.raw.mydemo)
Reference: https://stackoverflow.com/a/57719958
Worked for me Try this code
uri = Uri.fromFile(new File("//assets/testdemo.txt"));
String testfilepath = uri.getPath();
File f = new File(testfilepath);
if (f.exists() == true) {
Toast.makeText(getApplicationContext(),"valid :" + testfilepath, 2000).show();
} else {
Toast.makeText(getApplicationContext(),"invalid :" + testfilepath, 2000).show();
}

Android Show image by path

i want to show image in imageview without using id.
i will place all images in raw folder and open
try {
String ss = "res/raw/images/inrax/3150-MCM.jpg";
in = new FileInputStream(ss);
buf = new BufferedInputStream(in);
Bitmap bMap = BitmapFactory.decodeStream(buf);
image.setImageBitmap(bMap);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
but this is not working i want to access image using its path not by name
read a stream of bytes using openRawResource()
some thing like this should work
InputStream is = context.getResources().openRawResource(R.raw.urfilename);
Check this link
http://developer.android.com/guide/topics/resources/accessing-resources.html#ResourcesFromCode
It clearly says the following
While uncommon, you might need access your original files and directories. If you do, then saving your files in res/ won't work for you, because the only way to read a resource from res/ is with the resource ID
If you want to give a file name like the one mentioned in ur code probably you need to save it on assets folder.
You might be able to use Resources.getIdentifier(name, type, package) with raw files. This'll get the id for you and then you can just continue with setImageResource(id) or whatever.
int id = getResources().getIdentifier("3150-MCM", "raw", getPackageName());
if (id != 0) //if it's zero then its not valid
image.setImageResource(id);
is what you want? It might not like the multiple folders though, but worth a try.
try {
// Get reference to AssetManager
AssetManager mngr = getAssets();
// Create an input stream to read from the asset folder
InputStream ins = mngr.open(imdir);
// Convert the input stream into a bitmap
img = BitmapFactory.decodeStream(ins);
} catch (final IOException e) {
e.printStackTrace();
}
here image directory is path of assets
like
assest -> image -> somefolder -> some.jpg
then path will be
image/somefolder/some.jpg
now no need of resource id for image , you can populate image on runtime using this

How to get access to raw resources that I put in res folder?

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)

Categories

Resources