How to get the extension of Files of resources? - android

In android, I need to load a set of images from res/drawable directory
I use the following code:
Field[] fields = R.drawable.class.getFields();
List<Picture> pictures = new ArrayList<>();
for (Field field : fields) {
String name = field.getName();
if (name.startsWith("img")) {
Picture picture = new Picture(name);
pictures.add(picture);
}
}
Among all files in 'drawable', it finds all files starting as a string 'img'.
For this code to work correctly, I have to manually change the names of image files by myself.
If I can get the extension of each resource in drawable (such as jpg, png, etc.), I don't need to change the file name like this.
Is there any way to achieve this?
I appreciate your help, thanks :D

I answer my question.
I moved all the image files into "asset/imgs"
and use the following code to load them
List<Picture> pictures = new ArrayList<>();
try {
String[] images = assetManager.list("imgs");
for (String name : images) {
Picture picture = new Picture(name);
pictures.add(picture);
}
} catch (IOException e) {
// you can print error or log.
throw new RuntimeException(e);
}

Related

Read images in drawable as File

I want to read all the Images in drawable folder as File object and store them in an array of File.
Is there a way to get list of all images in drawable and read them as File?
Edit: I need to know the following..
How to collect all the images from drawable folder. My images have different meaningful name based on the content. There is no common pattern in the name.
How to read these images as File.
No, because they are not files on the device. They are only files on your development machine. Resources are entries in the APK itself at runtime.
First you need to convert all drawable to bitmap and save to Local Storage then read it as File
You can get all Drawables from this method
public Drawable[] getAllDrawables()
{
Field[] ID_Fields = R.drawable.class.getFields();
Drawable[] drawables = new Drawable[ID_Fields.length];
for(int i = 0; i < ID_Fields.length; i++) {
try {
drawables[i] = ContextCompat.getDrawable(this,ID_Fields[i].getInt(null));
} catch (IllegalArgumentException | IllegalAccessException ignored) {
return null;
}
}
return drawables;
}
Possible Duplicate
Here

Android - How to get the names of pictures in drawable folder?

I´m creating a game for my college project and I was wondering if I can get the names(just the names) of the images I put inside the /drawable folder in android. It can also be the files I put inside the /raw folder, the option that works better.
Use the following snippet
Field[] ID_Fields = R.drawable.class.getFields();
for (Field f : ID_Fields) {
try {
System.out.println(f.getName() + "sample");
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}

How do I randomly select an image from photo gallery

I need to randomly select an image from a user's photo gallery. I don't mean starting an intent as in
Intent gallery = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, GALLERY_PHOTO_REQUEST_CODE);
No. I need to randomly select the image myself. Is there an efficient way to do this? Or do I have to actually read in all the image files and then randomly select a file, and then from the file get the image? By read all files, I mean with something as (snippet: I have a question not an answer)
void addFiles(final File parent, Set<File> images) {
try {
for (final File file : parent.listFiles()) {
if (!file.getParent().contains("Android")) {
if (!file.isDirectory()) {
if (isImageFile(file.getName())) {
images.add(file);
}
} else {
addFiles(file, images);
}
}
}
} catch (Exception e) {
}
}
Please don't be too concerned with the code snippet. If I knew the best way, I would not be asking for help. Does anyone know an efficient way of doing this?
I don't know your code aside from the snippets. Unless you have a large number of files, you could very well read all the files into an array. Then generate a random number with 0 as lowest and arrayList.size()-1 as highest and get that index from the array.
Pseudo code:
private static Random random = new Random();
ArrayList<File> list = readFiles();
File randomFile = list.get(getRandomValue(0, list.size()-1));
...
public static int getRandomValue(int low, int high) {
return random.nextInt((high - low) + 1) + low;
}

Can't see image in ImageView android

I am trying to populate ListView Item with an object from MyClass. One of the property of the class is jpg image. I put my images in images/ folder. I use this code for populating
private static final String ASSETS_DIR = "images/";
String imgFilePath=ASSETS_DIR+r.resourceID;
try{
Bitmap bitmap = BitmapFactory.decodeFile(imgFilePath);
resourceIdView.setImageBitmap(bitmap);
}
catch(Exception e)
{
System.out.println(" Error");
}
r.resourceID is the name of the image for example "AUD.jpg"
resourceIDView is ImageView
The program don't get in the catch part, however I can't see the image
could somebody help me??
From your naming convention I conclude that you are storing your images in the "assets" folder. If yes, then you can use the following lines of code and get this issue resolved:
private static final String ASSETS_DIR = "images/";
String imgFilePath=ASSETS_DIR+r.resourceID;
try{
Drawable d = Drawable.createFromStream(getAssets().open(imgFilePath), null);
resourceIdView.setImageDrawable(d);
}
catch(Exception e)
{
System.out.println(" Error");
}
Hope this helps.
put your image in drawable folder and set so imageview...
resourceIdView.setImageResource(R.drawable.AUD);
You can try to put your images in drawable folder under /res. Use an ImageAdapterthat extend BaseAdapterto populate your ListView. You can use this code : http://www.java2s.com/Code/Android/2D-Graphics/extendsBaseAdaptertocreateImageadapter.htm
What I had was that the image was showing in Designer but not on device, so I put the image in all the drawable-xdpi directories. This worked for me.

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