[英]Reading .txt files in Android with a delay
我是 Android Studio 的初学者,我当前的项目从 .txt 文件中读取单词(基本上是字典)并向用户输出一个随机单词。 用户依次输入另一个单词,其字符与显示给他的字符不同。 一切正常,除了当我打开另一个.txt 文件(在这种情况下是另一种语言的字典)时,程序会减慢从该文件中读取所有这些单词的速度。 我基本上将所有单词都读一遍,然后将它们添加到 arraylist 字符串中,以便稍后处理。 在这一点上,我不知道瞬时滞后问题的根源可能是什么,因为每个 .txt 文件中最多有 1-2 千字,我认为手机的速度足以一次读取它们,但我是反正对它一无所知。 我知道 .txt 有更好的替代品,比如使用 sql 但我现在对阅读 .txt 文件很熟悉,并且想暂时使用它。 有人可以推荐我一些东西来解决这个瞬间的滞后吗? 先感谢您。 这是我的代码,更改语言时会调用这两个方法:
public void restartGame() throws IOException {
//availableWords is the list of all words
availableWords = new ArrayList<>();
//currentStream is an InputStream targeted to the current .txt file
currentStream.reset();
//I read all the words and add them to the arraylist
Scanner reader = new Scanner(currentStream);
while (reader.hasNext())
availableWords.add(reader.next());
//I choose a random word from the arraylist to begin with
String chosenWord = availableWords.get((int) (availableWords.size() * Math.random()));
wordOutput.setText(chosenWord);
availableWords.remove(chosenWord);
String previousText = "";
for( int i = 0; i < 4; i++) {
for (int chars = 0; chars < currentWordLength; chars++)
previousText += " ";
previousText += "\n";
}
previousWords.setText(previousText);
wordInput.setText("");
restartButton.setVisibility(View.GONE);
wordInput.setVisibility(View.VISIBLE);
enterButton.setVisibility(View.VISIBLE);
}
//a spinner to let user select a language
languageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//chosen language is assigned to a variable
currentLanguage = parent.getSelectedItem().toString();
//corresponding inputStream is assigned to currentStream so that in restartGame method, the game restarts with the chosen language
ArrayList<InputStream> wordLengthLanguage = wordsFile.get(currentWordLength - 3);
currentStream = wordLengthLanguage.get(languages.indexOf(currentLanguage));
try {
restartGame();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
从文件中读取单词的要点或目标是什么? 如果你想持久化数据(作为 sqlite),你可以创建一个包含字符串数组的字符串资源。 每次应用程序启动时,您都可以从资源中读取它们。
首先,go 到 android studio 上的应用文件夹,然后res > values
右键单击 values 然后new > values resource file
。 随心所欲地命名。 在资源标签中创建如下内容:
<string-array name="words">
<item>Word 1</item>
<item>Word 2</item>
</string-array>
当您需要数组时,只需执行以下操作:
getResources().getStringArray(R.array.words)
其中“words”是字符串数组的名称。 请注意,如果您在片段上,则需要 Context 才能访问资源。
这个 arrays 是不可编辑的,所以在执行时不能添加更多的词,所有的词都需要先创建到资源文件中。
希望它可以帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.