Q:

How to read text-file using java (android studio)?

I am very new to android development and I was following Stanford CS193A lectures to learn something. While trying to create dictionary(without using stand-ford library), i feel like I did most of the things right but I am not able to launch app on phone. Here my java code. Please help me.



    package com.hfad.dictionarytwo;

    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;

    import androidx.appcompat.app.AppCompatActivity;

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.Scanner;

    public class MainActivity extends AppCompatActivity {

        private HashMap<String, String> dictionary;
        private ArrayList<String> list;
        private ArrayAdapter<String> adapter;
        private ArrayList<String> fiveDefns;

        @Override
        protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            dictionary = new HashMap<String,String>();
            list = new ArrayList<String>();
            fiveDefns = new ArrayList<String>();
            readWordsFromFile();

            pickRandomWords();
        }

        private void readWordsFromFile(){
            Scanner scan = new Scanner(getResources().openRawResource(R.raw.grewords));
            //following delimator is for spliting at tab
            while (scan.hasNextLine()){
                String line = scan.nextLine();
                String[] parts = line.split("\t");
                if (parts.length >= 2){
                String word = parts[0];
                String defn = parts[1];
                list.add(word);
                dictionary.put(word,defn);
                }

            }
        }

        private void pickRandomWords() {
            //folowing code shuffles all the words and takes the first three words
            ArrayList<String> threeWords = new ArrayList<String>();
            Collections.shuffle(list);
            for (int i = 0; i < 5; i++) {
                threeWords.add(list.get(i));
            }
            //display the first word, after shuffling ofcourse
            final String theWord = threeWords.get(0);
            TextView theWordView = findViewById(R.id.the_word);
            theWordView.setText(theWord);

            fiveDefns.clear();
            for (String word : threeWords) {
                fiveDefns.add(dictionary.get(word));
            }

            //shuffle it again
            Collections.shuffle(fiveDefns);
            //make adapter to show three definitions on screen
            if (adapter == null) {
                adapter = new ArrayAdapter<>(this,
                        android.R.layout.simple_list_item_1, fiveDefns);
            } else {
                adapter.notifyDataSetChanged();

            }


            ListView listView = findViewById(R.id.word_list);
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //get the posiiton of definition user clicked from threeDefn arraylist
                    String defnClicked = (String) fiveDefns.get(position);
                    //want to know if it is right definition
                    String rightAnswer = dictionary.get(theWord);
                    if (defnClicked.equals(rightAnswer)) {
                        //note that just 'this' will not work b/c we want to refer to over all activity
                        //not this little activity, which is small activity inside overall activity
                        Toast.makeText(MainActivity.this, "You are awesome", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "You Suck", Toast.LENGTH_SHORT).show();
                    }

                    pickRandomWords();
                }
            });
        }

    }



I have grewords txt file in my res directory .

A:

In your activity change condition in readWordsFromFile() and call pickRandomWords() from readWordsFromFile().
See the below code.
Make sure that your file has content like :
abcd kolkata valsad
123 auto vapi
789 neha palghar
klj ma ghfgh
mnk fgdgdf papa

Note: In your text file data should be in the above format.because you split words using space("\t").

public class MainActivity extends AppCompatActivity {

        private HashMap<String, String> dictionary;
        private ArrayList<String> list;
        private ArrayAdapter<String> adapter;
        private ArrayList<String> fiveDefns;

        @Override
        protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            dictionary = new HashMap<String,String>();
            list = new ArrayList<String>();
            fiveDefns = new ArrayList<String>();
            readWordsFromFile();

        }

        private void readWordsFromFile(){
            Scanner scan = new Scanner(getResources().openRawResource(R.raw.grewords));
            //following delimator is for spliting at tab
            while (scan.hasNextLine()){
                String line = scan.nextLine();
                if(line.contains(" ")) {
                    String[] parts = line.split(" ");
                    if (parts.length >= 1) {
                        String word = parts[0];
                        String defn = parts[1];
                        list.add(word);
                        dictionary.put(word, defn);
                    }
                }

            }
            pickRandomWords();
        }

        private void pickRandomWords() {
            //folowing code shuffles all the words and takes the first three words
            ArrayList<String> threeWords = new ArrayList<String>();
            Collections.shuffle(list);
            for (int i = 0; i < 3; i++) {
                threeWords.add(list.get(i));
            }
            //display the first word, after shuffling ofcourse
            final String theWord = threeWords.get(0);
            TextView theWordView = findViewById(R.id.the_word);
            theWordView.setText(theWord);

            fiveDefns.clear();
            for (String word : threeWords) {
                fiveDefns.add(dictionary.get(word));
            }

            //shuffle it again
            Collections.shuffle(fiveDefns);
            //make adapter to show three definitions on screen
            if (adapter == null) {
                adapter = new ArrayAdapter<>(this,
                        android.R.layout.simple_list_item_1, fiveDefns);
            } else {
                adapter.notifyDataSetChanged();

            }

            ListView listView = findViewById(R.id.word_list);
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //get the posiiton of definition user clicked from threeDefn arraylist
                    String defnClicked = (String) fiveDefns.get(position);
                    //want to know if it is right definition
                    String rightAnswer = dictionary.get(theWord);
                    if (defnClicked.equals(rightAnswer)) {
                        //note that just 'this' will not work b/c we want to refer to over all activity
                        //not this little activity, which is small activity inside overall activity
                        Toast.makeText(MainActivity.this, "You are awesome", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "You Suck", Toast.LENGTH_SHORT).show();
                    }

                    pickRandomWords();
                }
            });
        }

}

** Note:** you just replace the above code in your file.

