简体   繁体   English

从Android中的资产文件读取

[英]Reading from assets file in android

I'm working on a Hangman game to teach myself Android development. 我正在开发一个Hangman游戏,以自学Android开发。 I've done it all in Java already for PC and have that working well. 我已经在PC上用Java完成了所有这些工作,并且运行良好。 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! 我使用的是Android Studio 2.1,并且显示器不断向我抛出错误,我看不清自己在看什么!

The part I'm struggling with is getting it to read from the file "WordsDoc" in assets. 我苦苦挣扎的部分是让它从资产中的“ WordsDoc”文件中读取。 The code I've got is: 我得到的代码是:

Edit 2 编辑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 编辑3

Example of the file WordsDoc.txt is as below: WordsDoc.txt文件的示例如下:

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

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. 您正在尝试在setContentView(R.layout.activity_main)之前访问视图,这就是视图为空的原因。

Put this line: 把这一行:

setContentView(R.layout.activity_main);

immediately after this: 在此之后:

 super.onCreate(savedInstanceState);

in your MainActivity. 在您的MainActivity中。 Like this: 像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM