Search code examples
javaandroidassets

Reading from assets file in android


I'm working on a Hangman game to teach myself Android development. I've done it all in Java already for PC and have that working well. I'm using Android Studio 2.1 and the monitor keeps on throwing loads of errors at me and I can't make out what I'm looking at!

The part I'm struggling with is getting it to read from the file "WordsDoc" in assets. The code I've got is:

Edit 2

All code for app so far (really not much!)

    public class MainActivity extends AppCompatActivity {

    static String strWord = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final TextView theWord = (TextView)
                findViewById(R.id.textViewWord);
        final EditText editTextGuess = (EditText)
                findViewById(R.id.editTextGuess);
        final Button buttonGuess = (Button)
                findViewById(R.id.btnGuess);
        final TextView theIncorrectGuesses = (TextView)
                findViewById(R.id.textViewIncorrectLetters);
        setContentView(R.layout.activity_main);
        alertMessage(this,"ERROR");
        strWord = getTheWord();
        theWord.setText(strWord);
        newGame();
        buttonGuess.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){

                theIncorrectGuesses.setText("ABCDEF");
            }
        });
    }
    public String getTheWord() {

        List<String> lines = new ArrayList<String>();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(
                    new InputStreamReader(getAssets().open("WordsDoc.txt")));

            // do reading, usually loop until end of file reading
            String mLine;
            while ((mLine = reader.readLine()) != null) {
                //process line
                lines.add(mLine);
            }
            int intLen = 0;
            String[] strWords = lines.toArray(new String[lines.size()]);
            for (String strTemp : strWords){
                intLen ++;
            }
            int intRand = (int)(Math.random()* intLen);
            return strWords[intRand];

        } catch (IOException e) {
            //log the exception
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    //log the exception
                }
            }
        }
        return null;
    }
    public void newGame() {

    }
    public static void alertMessage(Activity a, String errMsg){

        final AlertDialog.Builder builder = new AlertDialog.Builder(a);
        builder.setTitle("Alert Dialog");
        builder.setMessage(errMsg);
        builder.setIcon(android.R.drawable.ic_dialog_alert);
        builder.setNeutralButton("OK", null);
        builder.create().show();
    }
}

Edit 3

Example of the file WordsDoc.txt is as below:

aardvark
Aarhus
Aaron
... continues 45000 more times

Edit

Errors:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.xxxx.hangman, PID: 4532
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxxx.hangman/com.xxxx.hangman.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
    at com.xxxx.hangman.MainActivity.onCreate(MainActivity.java:34)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    05-05 08:44:32.994 4532-4532/com.xxxx.hangman I/Process: Sending signal. PID: 4532 SIG: 9

Solution

  • Try opening the file with the extension:

        BufferedReader reader = null;
        try {
            reader = new BufferedReader(
                    new InputStreamReader(getAssets().open("WordsDoc.txt")))
          ...
    

    Edit: Solution for my code:

    You are trying to access the view before setContentView(R.layout.activity_main) which is why your view are null.

    Put this line:

    setContentView(R.layout.activity_main);
    

    immediately after this:

     super.onCreate(savedInstanceState);
    

    in your MainActivity. Like this:

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            // the rest goes here