سؤال

I am on my way through the "Beginning Android Games" book by Mario Zechner I'm glad I picked it up but I am now running into an issue with one of the "Tests" he requires users to code early on in the book. Not that I am against coding them I would rather know what I am doing than to do a half cocked job and it not work out to well when I get further along.

So AssetManager does not seem to want to load my file.

    AssetManager am = getAssets();
    InputStream inputStream = null;
    try {
        am.open("assets/texts/hello.txt");
        String text = loadTextFile(inputStream);
        tv.setText(text);
    } catch (IOException e) {
        tv.setText("Could not Load file");
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                tv.setText("Could not close file");
            }
        }
    }
}

By all standards I should be able to just use the link: "texts/hello.txt" but every time I do it shoots an NPE at me. So I am forced to use the full link. Using the full link allows the program to run it just fails to load up my text document as per instructions it tells me "Could not load file"

Figured I would nip this issue in the bud now so it does not become a major issue later on.

هل كانت مفيدة؟

المحلول

Change you code as :

 AssetManager am = getAssets();
    InputStream inputStream = null;
    try {

         inputStream= am.open("texts/hello.txt"); //<<<<
        String text = loadTextFile(inputStream);
        tv.setText(text);
    } catch (IOException e) {

    // your code here

because you are passing null inputStream to loadTextFile method

نصائح أخرى

// To load text file
        InputStream input;
        try {
          input = assetManager.open("helloworld.txt");

             int size = input.available();
             byte[] buffer = new byte[size];
             input.read(buffer);
             input.close();

             // byte buffer into a string
             String text = new String(buffer);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top