1

In my latest project i use a .txt file called "atestfile.txt" which resides inside my projects /raw folder, which i created:

location of file

and this is its content:

file content

now using these few simple lines of code..

code

i want my application to insert the words from the textfile into my ArrayList line by line as seen in this questions awesome first answer.

However, no Toast will appear, and even worse, i will receive an IndexOutOfBoundsException for the test.get(3); line i use and the application crashes.

I tried all day to get rid of this error but have not succeeded yet in doing so. So since there are a lot of smart people around here and i'd love to learn something about this problem, i thought i'd ask you guys for help first before throwing my computer out of the window.

I'll provide you guys with my error message, copy & pasteable code aswell as my packet structure for some more help on this issue.

package com.niklas.cp.citypopulation;

huge error message

   final ArrayList<String> test = new ArrayList<String>();

    try {

        Scanner scanner = new Scanner(new File("android.resource:// com.niklas.cp.citypopulation/raw/atestfile.txt"));

        while(scanner.hasNextLine()){


            makeToast(scanner.nextLine(),1);
            test.add(scanner.nextLine());

        }
        scanner.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    String abc = test.get(3);
    tv_highscore.setText(abc);
Ali Khaki
  • 1,184
  • 1
  • 13
  • 24
Niklas Daute
  • 75
  • 1
  • 7
  • 3
    Don't put text in as images. Please post the actual text here. – Gabe Sechan Oct 22 '18 at 15:48
  • 2
    Also your stacktrace indicates the test array has a length of 0 but you are expecting it to contain your text file values, so maybe there not being input correctly – Jer Oct 22 '18 at 15:56
  • 2
    please do not use images. Your bug is in `new File("android.resource:// com.niklas.cp.citypo...`. There is a space there after `/`. This is causing an exception before the exception that you posted. – Sherif elKhatib Oct 22 '18 at 16:02
  • @SherifelKhatib Hey, i'll make sure not to use any images in any of my next questions. And good catch, i corrected the space after the `/`, unfortunately, it didn't solve the issue. – Niklas Daute Oct 22 '18 at 16:25
  • @NiklasDaute You should also edit this question and replace the images. You can use the **edit** link below your question in order to do so. – MC Emperor Oct 22 '18 at 16:50

1 Answers1

2

You are calling scanner.nextLine() twice in each loop, but only adding second line to test, thus test will have only three lines.
You have to write like this

while(scanner.hasNextLine()) {
   String s = scanner.nextLine();
   makeToast(s,1);
   test.add(s);
}

If it throws FileNotFoundException try the following

InputStream file = getResources().openRawResource(R.raw.atestfile);
Scanner scanner = new Scanner(file);
Jaisel Rahman
  • 120
  • 1
  • 7