Trying to read a text file in res/raw with scanner

Hello,

I am trying to read a file with a Scanner so I can use the input of the strings to construct other objects. However my scanner is always throwing a NullPointerException when trying to create it. I have a pig.txt text file in the res/raw folder but my scanner can not seem to access it. I do not know what I am doing wrong. I have comment out other code of the method but still get an exception.

public void loadAchievements() {
    try {
        Scanner s = new Scanner(getResources().openRawResource(R.raw.pig));

        /**
         * s = s.useDelimiter("."); Scanner StringScanner; StringScanner =
         * new Scanner(s.next()); StringScanner =
         * StringScanner.useDelimiter(":"); String keep =
         * StringScanner.next(); String StringKeeper = StringScanner.next();
         * this.achievementBoard.add(new Achievement_Item(keep,
         * StringKeeper)); StringScanner.close(); s.close();
         **/
    } catch (NullPointerException e) {
        e.printStackTrace();
        System.out.println("NULLPOINTER");
    }
}

Upvotes: 0

Views: 1158

Answers (2)

I had this problem today, and I resolved somehow.
I know that old question, but I would share it if others have stuck.





 public class Question {

        private int numberOfQuestion;
        private String[] myquestion;

        public Question(InputStream file_name) {
            Scanner scanner = null;

            try {
                scanner = new Scanner(file_name);

            } catch (Exception e) {
                Log.d("Question", "Scanner :" + e);
                System.exit(1);
            }

            this.numberOfQuestion = scanner.nextInt();
            scanner.nextLine();
            myquestion = new String[numberOfQuestion];

            for (int i = 0; i < numberOfQuestion; ++i) {
                myquestion[i] = scanner.nextLine();

            }

            scanner.close();


        }
    ---------------------------------------------------------
call:

try { 
  MyScanner myScanner = new MyScanner(getResources().openRawResource( R.raw.input_question)); 
   } catch (Exception e) { 
        Log.d("Error", "input_question.txt"); 
  }

Upvotes: 1

Marcin S.
Marcin S.

Reputation: 11191

openRawResource() method can only be used to open drawable, sound, and raw resources; it will fail on string and color resources. Since your pig.txt is a text file that contains a String, openRawResource() won't be able to open a new stream therefore your stream is null.

Upvotes: 0

Related Questions