How can i get the path of the image which i uploaded to assests or drawable in android?
This is the code i have used..
existingFileName="res/drawable-ldpi/login.png";
File f= new File(existingFileName);
// Log.d("Image path",);
if(f.exists())
{
Log.d("EXISTS", "====Fi开发者_如何转开发le Exists===");
}
Still it is showing me no image exist.
thanks for help in advance, aby
If you are putting your images in drawable folder, I don't think you can access them like this. Try this
Drawable image= getResources().getDrawable(R.drawable.<id>);
id will be your file name.
If you store the image in the "res/drawable" folder you can do:
Drawable drawable = getResources().getDrawable(R.drawable.name)
See http://developer.android.com/reference/android/content/res/Resources.html#getDrawable
For the case you store your image in the assets folder, you need to use getAssets()
( http://developer.android.com/reference/android/content/Context.html#getAssets() )
You can do something like this:
InputStream is = getAssets().open(imageName);
BufferedInputStream buf = new BufferedInputStream(is);
Bitmap bitmap = BitmapFactory.decodeStream(buf);
Remember that for both case you need to have a Context
(ie an Activity
)
There is no need to check
the existence of an asset file before you read it. AssetManager takes care of it
. If file is missing, it throws an exception. Your coding practice should be to always enclose that part of code in try catch and split the logic. Extra code is not needed. If you try an open a file that doesn't exist you will get an exception.
Though, if you still want to do that manual job, try below code.
AssetManager mg = getResources().getAssets();
try {
//do all considering file exists
mg.open(pathInAssets);
} catch (IOException ex) {
//do all in case file is missing
}
If your file is located in assets/folder/file.ext, then pathInAssets
would be "folder/file.ext"
Check for file existence in androids assets folder?
How to check Android Asset resource?
Usually if you use res/drawable, your ressource identifier is compiled into the R.java file. So if you use an identifier from there, you can be sure the file IS there, otherwise you cannot compile your project.
If however you like to exchange R.java later and really need to list the ressources in res/drawable, you can do it with java Reflection, examining the R class like this:
Class<?> c=R.drawable.class;
Field[] fs=c.getFields();
for(Field f: fs)
Log.v("test", f.getName());
You will then get a list of the ressources, without the file extension. The Ressource Identifier (an integer) for every ressource is then read with int id=f.getInt(null);
.
Use the DDMS perspective in eclipse to browse for the image on an emulator running your app.
If you get this error.. "Cannot make a static
reference to the non-static
method getResources()
from the type ContextWrapper
"
Try Drawable image=Classname.this.getResources().getDrawable(R.drawable.<id>);
here Classname.this
means the ClassContext/Application Context.
精彩评论