简体   繁体   English

带有进度栏的AsyncTask

[英]AsyncTask with progressbar

The following code is a part of my app and it isn't working and I don't know why. 以下代码是我的应用程序的一部分,它无法正常工作,我也不知道为什么。

I don't know at which place I can put the "new MormaKaugummi().execute();". 我不知道可以在哪里放置“新的MormaKaugummi()。execute();”。 At any place the App crashed and gave me the error "Unfortunately, Criminal Life has stopped." 该应用程序在任何地方崩溃了,并给我以下错误:“不幸的是,犯罪生活已经停止。”

The "counter textview" is in an another activity in the same app. “计数器textview”在同一应用程序的另一个活动中。

(The name of the App is Criminal Life). (该应用程序的名称为犯罪生活)。

I need a unique solution because I'm new in Android programming. 我需要一个独特的解决方案,因为我是Android编程的新手。

public class Morma extends AppCompatActivity {

class MormaKaugummi extends AsyncTask<String, String, String> {

    private int count = 0;
    private void count() {
        count++;
    }

    private void update() {
        TextView counter = (TextView) findViewById(R.id.counter);
        String Kcounter = Integer.toString(count);
        counter.setText(Kcounter);
    }

    @Override
    protected String doInBackground(String... params) {
        count();
        update();
        return null;
    }
}

private ProgressBar progressBarKaugummi;
private int progressStatusKaugummi = 0;
private Handler handlerKaugummi = new Handler();

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_morma);
    Button buttonMormaKaugummiKlauen = (Button) findViewById(R.id.buttonMormaKaugummiKlauen);

    buttonMormaKaugummiKlauen.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            progressBarKaugummi = (ProgressBar) findViewById(R.id.progressBarMormaKaugummi);
            new Thread(new Runnable() {
                public void run() {
                    while (progressStatusKaugummi < 100) {
                        progressStatusKaugummi += 1;
                        handlerKaugummi.post(new Runnable() {
                            public void run() {
                                progressBarKaugummi.setProgress(progressStatusKaugummi);
                            }
                        });
                        try {
                            Thread.sleep(4000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
            if (progressStatusKaugummi == 100) {
                progressBarKaugummi.setProgress(0);
                recreate();
                new MormaKaugummi().execute();
            }
        }
    });

That's the logcat 那是logcat

11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:856)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:  Caused by: java.lang.NullPointerException
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at peppermine_studios.criminallife.Morma$MormaKaugummi.update(Morma.java:26)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at peppermine_studios.criminallife.Morma$MormaKaugummi.doInBackground(Morma.java:32)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at peppermine_studios.criminallife.Morma$MormaKaugummi.doInBackground(Morma.java:15)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:856) 
11-07 13:48:35.514 622-622/peppermine_studios.criminallife W/EGL_emulation: eglSurfaceAttrib not implemented
11-07 13:48:35.674 622-622/peppermine_studios.criminallife W/EGL_emulation: eglSurfaceAttrib not implemented
11-07 13:48:37.364 622-1376/? I/Process: Sending signal. PID: 622 SIG: 9

You are trying to do findviewbyId and update the text view in your doInBackground method via the update function, which you cannot do. 您正在尝试执行findviewbyId并通过update功能来update doInBackground方法中的文本视图,但您不能这样做。

As for the crash its happening because of a null pointer exception as you can read for yourself in the logcat's caused by clause it tells you the exact line number where the null pointer exception is thrown 至于崩溃是由于空指针异常而发生的,您可以在logcat的by子句中自己读取,它告诉您抛出空指针异常的确切行号

Caused by: java.lang.NullPointerException
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime:     at peppermine_studios.criminallife.Morma$MormaKaugummi.update(Morma.java:26)

as you can see here, its caused by null pointer at line 26 in Morma.java and I am guessing that your TextView counter is null since you are trying to initialize a variable to reference a UI element from a non-UI thread, the counter variable will be initialized as null obviously. 如您在此处看到的,它是由Morma.java中第26行的空指针引起的,我猜测您的TextView counter为null,因为您试图初始化变量以引用非UI线程中的UI元素,该计数器变量显然将初始化为null。

Now for the solution: 现在为解决方案:

What you need to do is put the update function in the onPostExecute method for the async task class. 您需要做的是将更新功能放在异步任务类的onPostExecute方法中。 Reason: onPostExceute runs on whatever thread the asyntcTask.execute method was called from so you are supposed to do your UI update in the onPostExecute method 原因:onPostExceute在调用asyntcTask.execute方法的任何线程上运行,因此您应该在onPostExecute方法中进行UI更新

@Override
protected String doInBackground(String... params) {
    count();
    return null;
}

@Override
protect void onPostExecute(String result) {
    update();
}

Also since you are returning null from doInBackground anyway you should Extend AsyncTask<String,String,Void> ideally. 另外,由于无论如何都从doInBackground返回null, doInBackground应该理想地扩展AsyncTask<String,String,Void>

EDIT 1: 编辑1:

Added code 添加代码

public class Morma extends AppCompatActivity {

// make the text view class variable if you want to update it outside of onCreate.
private TextView mCounterTextView;

class MormaKaugummi extends AsyncTask<Void, Void, Void> {

    private int count = 0;
    private void count() {
        count++;
    }

    private void update() {
        String Kcounter = Integer.toString(count);
        mCounterTextView.setText(Kcounter);
    }

    @Override
    protected void doInBackground(Void... aVoid) {
        count();
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        update();
    }
}

private ProgressBar progressBarKaugummi;
private int progressStatusKaugummi = 0;
private Handler handlerKaugummi = new Handler();

@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_morma);
Button buttonMormaKaugummiKlauen = (Button) findViewById(R.id.buttonMormaKaugummiKlauen);

// initiate all your view items in onCreate.
mCounterTextView = (TextView) findViewById(R.id.counter);

buttonMormaKaugummiKlauen.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        progressBarKaugummi = (ProgressBar) findViewById(R.id.progressBarMormaKaugummi);
        new Thread(new Runnable() {
            public void run() {
                while (progressStatusKaugummi < 100) {
                    progressStatusKaugummi += 1;
                    handlerKaugummi.post(new Runnable() {
                        public void run() {
                            progressBarKaugummi.setProgress(progressStatusKaugummi);
                        }
                    });
                    try {
                        Thread.sleep(4000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        if (progressStatusKaugummi == 100) {
            progressBarKaugummi.setProgress(0);
            recreate();
            new MormaKaugummi().execute();
        }
    }
});

You need to initialize all your view elements like the textview in onCreate itself and keep the reference as a class variable if you are going to use that view outside of onCreate. 如果要在onCreate之外使用该视图,则需要初始化所有视图元素(例如onCreate本身中的textview),并将引用保留为类变量。

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

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