Libgdx: how to pick a random texture?

I'm trying to pick a random texture from a fodler placed in assets and use it but it's giving me errors. I'm doing so in the main game screen class

    final  File dir = new File("img");
Random rand = new Random();
File[] files = dir.listFiles();
File file = files[rand.nextInt(files.length)];
Image = new Texture(Gdx.files.internal(file.getPath()));


The error is

java.lang.NullPointerException: Attempt to get length of null array


to my knowledge this error should only be there if File[] files = dir.listFiles(); is null, and it isn't, currently two pictures are there. So what's happening?

I tried supplying the full path in the first line to img folder but to no avail. Plus I don't want to supply the full path anyway, it will change from device to another.

• So just to make sure: Have you confirmed with your debugger that the files are listed in files? – Tyyppi_77 Feb 12 '17 at 15:05
• @Tyyppi_77 no matter what I do, files is always null, probably some android permission not allowing directory reading, not sure how else to debug it, I'm trying console.log to no avail – Lynob Feb 12 '17 at 15:34
• What is your directory tree? This might be an issue with relative/absolute paths. – Tyyppi_77 Feb 12 '17 at 15:35
• @Tyyppi_77 the images are in /home/user/Documents/android/game/android/assets/img and my code is in /home/user/Documents/android/game/core/src/com/game/MainGame.java – Lynob Feb 12 '17 at 15:45
• So what if you hardcode that path in? I'm not sure how your IDE treats the working directory, but try changing "img" to a complete path. – Tyyppi_77 Feb 12 '17 at 15:52

Try this :

// Get directory
FileHandle dir = Gdx.files.internal("img");

// Get a random texture of dir
Texture randomTexture = new Texture(dir.list()[random.nextInt(dir.list().length)]);


Should work perfectly if your textures are in assets/img/

Hope it helps

• At l.159 of GameScreen you try to get width of a null texture, check were you load that texture. – Sebastien Servouze Feb 12 '17 at 19:26

Try to refresh (right click > refresh) the folder, which contains the files you want to load, within eclipse (or whatever else you are using). This solved many problems I had loading files so far.

• the images are there, I can see them, plus I see no refresh option in android studio – Lynob Feb 12 '17 at 15:26
• I'm afraid I can't help with android studio, but in case you get different projects for development with libGdX, like it is with eclipse, you might want to copy the image folder into the other projects "assets" folders. The program tries to access only one of them (desktop, android, iOS, ..) and the other projects pull from that folder. That did it for me once or twice too. Edit: I see you are not developing for different platforms a time, so my suggestion is pretty much nonsense. Sorry. – Rufrage Feb 12 '17 at 16:29