1

Whenever I try to run my libdgx app on my phone via ADB, android studio is unable to find a file in the "android/assets" folder. However, when I run the desktop version it works fine.

I'm using this to read from a file:

File file = new File("BlocksProgression.txt");
reader = new BufferedReader(new FileReader(file));

As explained, this works fine when I run the desktop launcher, but the android launcher returns this error:

W/System.err: java.io.FileNotFoundException: BlocksProgression.txt (No such file or directory)

I've been searching for over an hour now, but I can't seem to find how to setup the assets folder correctly.

Any help would be appreciated.

Jack Jhonsen
  • 119
  • 6

2 Answers2

1

Found the answer: https://github.com/libgdx/libgdx/wiki/File-handling#reading-from-a-file

Turns out Libgdx wants you to use a FileHandle object to read the file. Using this my code becomes:

FileHandle file = Gdx.files.internal("BlocksProgression.txt");
String data = file.readString();

And this simply returns the text as string. Hope this can help some people out.

Jack Jhonsen
  • 119
  • 6
0

Well, when using File file = new File("BlocksProgression.txt") you're not reading from the assets but you're reading from the default files directory the proper way to read a file from assets would be the following

BufferedReader reader = null;
try {
    reader = new BufferedReader(
        new InputStreamReader(getAssets().open("BlocksProgression.txt"), "UTF-8")); 

    // do reading, usually loop until end of file reading 
    String mLine;
    while ((mLine = reader.readLine()) != null) {
       //process line
       ...
    }
} catch (IOException e) {
    //log the exception
} finally {
    if (reader != null) {
         try {
             reader.close();
         } catch (IOException e) {
             //log the exception
         }
    }
}

This code was from this answer

Pedro Cavaleiro
  • 769
  • 6
  • 18
  • Thanks for you answer, I understand that I'm not reading from the assets folder like this. When I try to call getAssets it can't resolve the method because it's not in that class, however, I don't know in which class it is, do I have to extend some class so I can call getAssets. Which class contains the getAssets function? Thanks – Jack Jhonsen Aug 11 '18 at 16:42
  • EDIT: So I've found out getAssets can only be called in an activity otherwise I should use the static class ContextInstance, however, I can't seem to find that class to import. Also I'm unable to extend 'Activity' (also not found), perhaps my project wasn't setup correctly. – Jack Jhonsen Aug 11 '18 at 16:54
  • Perhaps try this import, `import android.app.Activity;` – Pedro Cavaleiro Aug 11 '18 at 18:07
  • Hmm, that doesn't work, but I've found the issue. I'll post it as answer for other people with the same problem. Thanks for your help anyway! – Jack Jhonsen Aug 11 '18 at 18:17