Java – Tried to load a text file into an array line by line, but the array remains empty, what am I doing wrong? (Java, Android Studio)

Tried to load a text file into an array line by line, but the array remains empty, what am I doing wrong? (Java, Android Studio)… here is a solution to the problem.

Tried to load a text file into an array line by line, but the array remains empty, what am I doing wrong? (Java, Android Studio)

private String[] words;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mDecorView = getWindow().getDecorView();

loadWords();

TextView tv = (TextView) findViewById(R.id.word);
    tv.setText(words[0]);
}

public void loadWords()
{

try {
        InputStream file = new FileInputStream("words.txt");
        InputStreamReader sr = new InputStreamReader(file);
        BufferedReader br = new BufferedReader(sr);

int n = 0;
        while(br.readLine() != null)
        {
            words[n] = br.readLine();
            n++;
        }

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

Ok, so I just wanted to print out the first element in the array, but the app crashes during startup and gives me the error “tried to read from an empty array”

Edit – Solution
– I didn’t initialize the array. (I know I have 100 rows)
– My input stream is incorrect (my file cannot be found).
– I tried to update the TextView
from the second layout (not selected at the time).

String[] words = new String[100];

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mDecorView = getWindow().getDecorView();
    loadWords();
}

public void changeView(View view) {

setContentView(R.layout.game_view);
    TextView tv = (TextView) findViewById(R.id.word);
    tv.setText(words[0]);
}

public void loadWords()
{
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(getAssets().open("words.txt")));
        for(int i = 0; i<words.length; i++)
        {
            words[i] = br.readLine();
        }
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Solution

You need to initialize the array, but you didn’t. The declaration and initialization of arrays is different, isn’t it?

The initialization of the array looks like this:

private String[] words = new String[2000];

Please try. However, try using ArrayList instead of array

Related Problems and Solutions