尝试将文本文件逐行加载到数组中,但数组保持为空,我做错了什么? (Java、android 工作室)

Trying to load a text file into an array line by line but the array stays null, 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();
    }
}

好的,所以我只是想打印出数组中的第一个元素,但是应用程序在启动过程中崩溃并给我错误 "Attempt to read from null array"

编辑 - 解决方案
-我没有初始化数组。(我知道我有100行)
-我的输入流不正确(找不到我的文件)
-我试图从第二个布局(当时未选择)更新 TextView

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();
    }
}

您需要初始化数组,但您没有这样做。数组的声明和初始化是不同的不是吗?

数组的初始化将像这样完成:

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

请尝试。但是,请尝试用 ArrayList 代替 array

很可能您从未初始化过数组。你刚刚声明了它。

重点是:您的代码只是说:我想使用一个字符串数组 (String[] words)。

但为了真正做到这一点 - 您必须创建一个数组对象来填充(请参阅 here 了解如何做到这一点的各种方法)

另一方面:"just creating an array";可能很难;考虑到您可能不知道数组中需要多少行(但您需要在初始化数组对象时知道这一点)。

因此,我建议使用 ArrayList<String> 之类的动态集合 class 而不是固定大小的数组。就google吧;以及你在发布这个问题之前应该做的研究......好吧,之后。