试图加载一个文本文件到数组一行,但数组保持空,我做错了什么?(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,所以我只是试图打印出数组中的第一个元素,但应用程序在启动时崩溃,并给我错误"尝试从null数组读取"

EDIT - Solution
-I没有初始化数组。(我知道我有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)。

但是为了真正做到这一点,你必须创建一个数组对象来填充(查看这里的各种方法)

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

所以,我建议使用像ArrayList<String>这样的动态集合类,而不是固定大小的数组。谷歌一下就知道了;在发布这个问题之前,你应该做的研究…后来。

最新更新