AsyncTask 在 Android 模拟器上不断崩溃演示应用程序 运行

AsyncTask keeps crashing demo app running on Android emulator

我目前正在通过阅读一本书来学习 Android 应用程序开发,而我目前正在为一些表面上看起来相当简单的事情而苦苦挣扎。该界面由一个按钮和一个文本视图组成。该练习的目的是演示在执行耗时任务时如何使用单独的线程。

我试过调试,onProgressUpdate 方法的 values 数组确实包含传递给它的值,并且在尝试为 [=17] 设置文本时似乎总是会发生崩溃=].如果有任何帮助,我将不胜感激。

代码:

package com.ebookfrenzy.asyncdemo;

import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private TextView myTextView;
    private String tag = "Test";

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

    public void buttonClick(View view) {
        AsyncTask task = new MyTask().execute();
    }

    private class MyTask extends AsyncTask<String,Integer,String> {
        @Override
        protected void onPreExecute() {

        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            Log.i(tag,"publish: " + Integer.toString(values[0]));
            myTextView.setText("Counter = " + values[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            myTextView.setText(result);
        }

        @Override
        protected String doInBackground(String... strings) {
            int i = 0;
            while (i <= 20) {
                Log.i(tag,"before publish: " + Integer.toString(i));
                publishProgress(i);
                try {
                    Thread.sleep(1000);
                    i++;
                } catch(Exception e) {

                }
            }

            return "Button Pressed";
        }
    }
}

Logcat 输出(由我为故障排除添加的 Log.i 项创建)通常如下所示,但如果提示应用程序不断崩溃的警告消息弹出“发布前” item 不断填充 i 每次递增,直到我关闭警告消息:

2020-12-13 23:17:04.499 31729-31772/com.ebookfrenzy.asyncdemo I/Test: before publish: 0
2020-12-13 23:17:04.503 31729-31729/com.ebookfrenzy.asyncdemo I/Test: publish: 0

Logcat的错误部分:

    --------- beginning of crash
2020-12-13 23:19:47.635 353-353/com.ebookfrenzy.asyncdemo E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.ebookfrenzy.asyncdemo, PID: 353
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.ebookfrenzy.asyncdemo.MainActivity$MyTask.onProgressUpdate(MainActivity.java:34)
        at com.ebookfrenzy.asyncdemo.MainActivity$MyTask.onProgressUpdate(MainActivity.java:25)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:715)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2020-12-13 23:19:47.639 353-353/com.ebookfrenzy.asyncdemo I/Process: Sending signal. PID: 353 SIG: 9

我认为myTextView必须为空。

试试这个。

if (myTextView != null){
  myTextView.setText("Counter = " + values[0]);
}

并且您应该在 onCreate() 方法中初始化 myTextView

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myTextView = (TextView) findViewById(R.id.mytextviewid); // put 
}