Put all drawable folder images directly in arraylist - android

I am developing an android game app and I have more then 150 images inside my app!
I want to put all images which exist in drawable package in a ArrayList.
I have this code
InputStream ips = getAssets().open("Arrow001.jpg");
Drawable d = Drawable.createFromStream(ips, null);
questionImageView.setImageDrawable(d);
but i don't want to add them one by one in myArray and i want to use a loop for generate images in arrayList when i run my app!
Thanks for your help

You can get array of all assets files on root assets folder by calling
String[] list = getAssets().list("")
In our case you can write code like below.
for (String assetPath : getAssets().list("")) {
InputStream ips = getAssets().open(assetPath);
//yours code
}

Related

how to get directory of images to access via code

I want to add images with my app. I see option to add images in res/drawable folder. But I have lot of images. How can I access the directory?
e.g. to access sdcard location I can use
File directory = new File(
android.os.Environment.getExternalStorageDirectory()
+ File.separator + AppConstant.PHOTO_ALBUM);
But I have images in drawable folder which will be with app. So how to access directory in android project. So that I can use something like File[] listFiles = directory.listFiles();
Is there better way to save and access images through app?
The solution I can suggest you is to store your images into "Asset" folder in your project and you can easily access all the images at once by following these steps:
Create a folder named "images" in your asset folder.
Copy all your images in that "images" folder.
3.Get your images list like this:
String[] images =getAssets().list("images");
ArrayList<String> listImages = new ArrayList<String>(Arrays.asList(images));
4.Now set the images to your "imageview" like this:
InputStream inputstream=mContext.getAssets().open("images/"
+listImages.get(position));
Drawable drawable = Drawable.createFromStream(inputstream, null);
imageView.setImageDrawable(drawable);
you can access all you images in drawable folder with :
getResources().getDrawable(R.drawable.name_of_drawable)
and also if you want access or load many images , you can use same names ( with postfix / prefix ) and load theme in a loop easily

How to load Textures with Unity3d on Android

i am trying to get this really easy setup to work, and it works on my computer but not on Android.
After trying it for the whole day im now asking since i cant find a single example on the internet.
The setup:
I have a lot of *.png files in a folder. Since the problem is with android i put them into a "StreamingAssets" folder
I have a RawImage called "Overlay"
I have a Dropdown called "Dropdown"
What should happen:
1. The Dropdown_script checks the StreamingAssets folder for all *.png files and adds every Filename to the dropdown options menu.
2. Once the user chooses one of the dropdown values my "Overlay" image changes its texture to the according file.
Pretty easy on PC ... impossible on android(with unity3d) as it seems.
My Dropdown Script:
public class DDScript : MonoBehaviour {
void Start () {
GameObject obj = GameObject.Find("Dropdown");
//Get all filenames
var info = new DirectoryInfo(Application.streamingAssetsPath);
var fileInfo = info.GetFiles("*.png");
//Clear the DropDown Menu Items from the Inspector
obj.GetComponent<Dropdown>().options.Clear();
//Make the first chosen item the first filename
obj.GetComponent<Dropdown>().captionText.text = fileInfo[0].Name.Substring(0, fileInfo[0].Name.IndexOf("."));
foreach (var file in fileInfo)
{
Dropdown.OptionData list = new Dropdown.OptionData(file.Name.Substring(0, file.Name.IndexOf(".")));
obj.GetComponent<Dropdown>().options.Add(list);
}
}
Its not working. It is working on my Computer but it is just not working on Android. I know that under Android everything gets packed into a jar file and there is nothing like a folderstructure. StreamingAssets should still have the files but i can understand that this part maybe cant work. Which would not be that bad, since it just finds the names and puts it into an array, i could do that within the program by hand. Since i know from beforehand how much and which files will be in the folder and it wont change ever.
This is my Change Texture Method
It is invoked by the Dropdown OnValueChange so the "newOverlay" is simply the int from the Dropdown. For debugging purposes i set the filepath to a specific file. later it will change depending on newOverlay
public IENumerator SetOverlay(int newOverlay)
{
GameObject obj = GameObject.Find("Overlay");
img = (RawImage)obj.GetComponent<RawImage>();
string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "testfile.png");
WWW www = new WWW(filePath);
yield return www;
img.texture = www.texture;
}
And i do not understand why this is not working!
The Documentation reads:
" This means that if you do not use Unity’s WWW class to retrieve the file then you will need to use additional software"
So using www is the right way. But it is not working!
No Texture gets loaded. i dont get the red questionmark, my image is just plain white. Please can someone help me here? Maybe i just cant see the forest due to all of the trees or the day was too long.
I really just cant believe that it is this hard to load a bunch of images that are within my apk file wiht unity :(
Thank you very much in advance
Edit: Solution (somehow)
First of all the problem was that System.IO.Path.Combine adds a back-slash between file and folder, but not between the folders themself!!!!
public void SetOverlay(int newOverlay)
{
GameObject obj = GameObject.Find("Overlay");
img = (RawImage)obj.GetComponent<RawImage>();
string filePath = Application.streamingAssetsPath + "/testfile.png";
WWW www = new WWW(filePath);
while (!www.isDone)
{}
img.texture = www.texture;
GameObject.Find("DebugText").GetComponent<Text>().text = filePath;
}
Havent found a solution to the Filename problem yet but im glad that this stupid "bug" is resolved
Have you tried putting the png files into the drawable folder and accessing them with BitmapFactory.decodeResources()?

Use assets folder images for gallery

I am creating an android application.In that one layout file uses a gallery.
I want to know how to use the images from assets folder as gallery images.
for e.g.
for a specific layout file new_am.xml I use the images from assets/new_am folder for the Gallery of that layout.
I know how to use it in case of minimum amount of images , but in my app each folder in assets contains more than 50 images.
You can dynamically access assets folders and set images to Gallery like below,
File fA=new File("file:///android_asset/folderA");
File[] filesA =fA.listFiles();
File fB=new File("file:///android_asset/folderB");
File[] filesB =fB.listFiles();
Also you can collect asset's folders names dynamically.
Hope this will help you.
// to reach asset
AssetManager assetManager = getAssets();
// to get all item in dogs folder.
String[] images = assetManager.list("FolderA");
InputStream inputStream = getAssets().open("FolderA/" + images[0]);
// load image as Drawable
Drawable d = Drawable.createFromStream(inputStream, null);
mImageView.setImageDrawable(d); //set to an Image view
inputStream.close();

load Image from specific folder on the sdcard?

I'm attempting to create a gallery/gridview that is loaded with images from a specific folder that resides on an SDCard. The path to the folder is known, ("mnt/sdcard/iWallet/Images") , but in the examples I've seen online I am unsure how or where to specify the path to the pictures folder I want to load images from. I have read through dozens of tutorials, even the HelloGridView tutorial at developer.android.com but those tutorials do not teach me what i am seeking.
Every tutorial I have read so far has either:
A) called the images as a Drawable from the /res folder and put them into an array to be loaded, not using the SDCard at all.
B) Accessed all pictures on the SDCard using the MediaStore but not specifying how to set the path to the folder I want to display images form
or
C) Suggested using BitmapFactory, which I haven't the slightest clue how to use.
If I'm going about this in the wrong way, please let me know and direct me toward the proper method to do what I'm trying to do.
my target android sdk version 1.6...
thanks..
You can directly create Bitmaps from decodeFile (String pathName) that will give you Bitmap object that can be set on ImageView
Update: Below is sudo code with minor errors modify it to suit your needs
File path = new File(Environment.getExternalStorageDirectory(),"iWallet/Images");
if(path.exists())
{
String[] fileNames = path.list();
}
for(int i = 0; i < fileNames .length; i++)
{
Bitmap mBitmap = BitmapFactory.decodeFile(path.getPath()+"/"+ fileNames[i]);
///Now set this bitmap on imageview
}
Actually, you are wrong to mention fixed path to access SD-card directory, because in some device it is /mnt/sdcard and in other /sdcard.
so to access root directory of sd-card, use the getExternalStorageDirectory(), it gives you actual path of root directory.
This function will resturn all the files from specific folder you need to pass path till ur folder
public static List getFilesFromDir(File aStartingDir)
{
List result = new ArrayList();
File[] filesAndDirs = aStartingDir.listFiles();
List filesDirs = Arrays.asList(filesAndDirs);
Iterator filesIter = filesDirs.iterator();
File file = null;
while ( filesIter.hasNext() ) {
file = (File)filesIter.next();
result.add(file); //always add, even if directory
if (!file.isFile()) {
//must be a directory
//recursive call!
List deeperList = getFileListing(file);
result.addAll(deeperList);
}
}
Collections.sort(result);
return result;
}
BitmapDrawable d = new BitmapDrawable(getResources(), path+".jpg"); // path is ur resultant //image
img.setImageDrawable(d);
Hope it help u...
You can access your directory using File java class, then iterate through all the files in there, create a bitmap for each file using Bitmapfactory.decodeFile() then add the bitmaps to your gallery.

problem while looping through assets folder :(

i have a subfolder in the Assets folder called images where i store my images(of course) :) The things is that i want to get the name for the images which i'm getting but the problem is that i'm also getting other unknown names like: "android-logo-mask.png" which i guess are android's default images. Is there a way i can skip this "android default images" to get only the names of my images? My plan is to save this names in a database to use it as reference for showing the images later on an ImageView. Is it a good idea to use the image name to show the images? Here is some code if it needs:
Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this.getApplicationContext();
ImageHelper i = new ImageHelper();
i.readImages(context);
}
public class ImageHelper {
public ImageHelper(){}
public void readImages(Context context){
AssetManager am = context.getAssets();
try {
String[] getImages = am.list("images");
for(String imgName : getImages){
Log.e("IMAGE NAME----->", imgName);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks in advance.
Use some other name for images folder like "MyImages". It should work fine then.
"images" should be a path like "/path/assets/images/image.png"
It is very interesting. Even if you don't have an assets/images directory, when you use:
myImageList = Arrays.asList(getResources().getAssets().list("images"));
you'll see android-logo-mask.png and android-logo-shine.png listed in the results.
That led me to wondering where those actual image files live in the Android code. I don't know the code base at all, but:
https://android.googlesource.com/platform/frameworks/base/+/master/core/res/assets/images/
lists those two in an assets directory under res. (Different from the assets directory where I store my project assets, that's not under res).
Being required to provide a path to an individual file for the AssetManagers list method (which returns an array) just doesn't make any sense. And the method documentation says:
Return a String array of all the assets at the given path.
It makes me wonder if there's an error in the list method, or if there was some other reason it was designed to return particular system assets when an asset list is required.
In a similar fashion, if I use:
myAssetList = Arrays.asList(getResources().getAssets().list(""));
I see "sounds" and "webkit" included, which don't correspond to any existing subdirectory of my assets.
If it occurs that the system adds files in this "images" folder, why not create a new folder for your images that you are sure to contain only your files ?

Categories

Resources