Search code examples
androidandroid-studiotext-filesreadfile

Reading .txt files in Android with a delay


I am a beginner to Android Studio and my current project reads words (basically a dictionary) from .txt files and outputs a random word to the user. The user in turn enters another word with one character different to what is shown to him. Everything works perfectly, except that when I switch on to reading another .txt file (another language's dictionary in this case), the program kind of slows down to read all those words from that file. I am basically reading all the words once and adding them to an arraylist of strings to work on later. At this point I don't know what the source of problem of that momentary lag might be because there are at most 1-2 thousand words in each .txt file and I think phones are fast enough to read them at once, but I am not knowledgeable about it anyway. I know there are better alternatives to .txt like using sql but I am familiar to reading .txt files for now and would like to work on it for now. Can someone recommend me something to solve that momentary lag? Thank you in advance. Here is my code, these two method are called when the language is changed:

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) {

        }
    });

Solution

  • What is the point or target to read the words from the file? If you want to persist the data (as sqlite) you can create a String resource which contains an array of strings. Every time the app start, you would be able to read them from the resources.

    First, go to your app folder on android studio, then res > values right click on values and then new > values resource file. Name as you want. Into the resources tag create something like this:

    <string-array name="words">
        <item>Word 1</item>
        <item>Word 2</item>
    </string-array>
    

    When you need the array, just do the following:

    getResources().getStringArray(R.array.words)
    

    Where "words" is the name of the string array. Notice that if you are on a fragment, you will need the Context to access to the resources.

    This arrays are not editable, so you can not add more words in execution time, all the words need to be created before into the resource file.

    Hope it helps you.