使用db helper将方法更改为AsyncTask

时间:2015-05-23 18:34:12

标签: java android multithreading android-asynctask

我的主线程中有一个方法,它从我的db helper类获取值并返回一个字符串,并将另一个字符串分配给texview。

但是我想在后台执行操作并在我的主UI线程上发布结果。阅读文档我正在努力知道如何创建AsyncTask,或者至少在不影响功能的情况下构建它以实现这一目标。我目前的主线程方法:

     public String showNextRandomQuestion3() {

            SQLDatabaseHelper db = new SQLDatabaseHelper(this);

            //get the data from the database
            List<List<String>> listList = db.getAllAnswersByQuestion1();

            //Get the question/text/answer Strings
            List<String> questionStrings = listList.get(0); //question Strings
            List<String> answerSetIds = listList.get(1);

            //Generate random index
            Random r = new Random();
            int rand = Math.abs((r.nextInt() % questionStrings.size()));

            //get answer description for randomly selected question
            String questionString = questionStrings.get(rand);  
            String answerSetId = answerSetIds.get(rand);

            String regex = "\\[|\\]";
            questionString = questionString.replaceAll(regex, "");
            answerSetId = answerSetId.replaceAll(regex, "");

            questionView.setText(questionString);

            return answerSetId;
            }

非常感谢任何有关为此创建AsyncTask的方法的帮助。

进行建议更改后,我收到以下异常:

05-23 21:23:44.510: D/AndroidRuntime(4598): Shutting down VM
05-23 21:23:44.510: W/dalvikvm(4598): threadid=1: thread exiting with uncaught exception (group=0x415aad88)
05-23 21:23:44.520: E/AndroidRuntime(4598): FATAL EXCEPTION: main
05-23 21:23:44.520: E/AndroidRuntime(4598): Process: com.example.quizapp, PID: 4598
05-23 21:23:44.520: E/AndroidRuntime(4598): java.util.NoSuchElementException
05-23 21:23:44.520: E/AndroidRuntime(4598):     at java.util.StringTokenizer.nextToken(StringTokenizer.java:208)
05-23 21:23:44.520: E/AndroidRuntime(4598):     at com.example.quizapp.MainActivity.showNextAnswers(MainActivity.java:431)
05-23 21:23:44.520: E/AndroidRuntime(4598):     at com.example.quizapp.MainActivity$7.onClick(MainActivity.java:339)
05-23 21:23:44.520: E/AndroidRuntime(4598):     at android.view.View.performClick(View.java:4569)
05-23 21:23:44.520: E/AndroidRuntime(4598):     at android.view.View$PerformClick.run(View.java:18553)
05-23 21:23:44.520: E/AndroidRuntime(4598):     at android.os.Handler.handleCallback(Handler.java:743)
05-23 21:23:44.520: E/AndroidRuntime(4598):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-23 21:23:44.520: E/AndroidRuntime(4598):     at android.os.Looper.loop(Looper.java:136)
05-23 21:23:44.520: E/AndroidRuntime(4598):     at android.app.ActivityThread.main(ActivityThread.java:5212)
05-23 21:23:44.520: E/AndroidRuntime(4598):     at java.lang.reflect.Method.invokeNative(Native Method)
05-23 21:23:44.520: E/AndroidRuntime(4598):     at java.lang.reflect.Method.invoke(Method.java:515)
05-23 21:23:44.520: E/AndroidRuntime(4598):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
05-23 21:23:44.520: E/AndroidRuntime(4598):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
05-23 21:23:44.520: E/AndroidRuntime(4598):     at dalvik.system.NativeStart.main(Native Method)
05-23 21:23:46.460: I/Process(4598): Sending signal. PID: 4598 SIG: 9
05-23 21:23:46.770: D/dalvikvm(5085): GC_FOR_ALLOC freed 50K, 74% free 3071K/11416K, paused 10ms, total 10ms
05-23 21:23:46.790: I/dalvikvm-heap(5085): Grow heap (frag case) to 19.905MB for 15422416-byte allocation
05-23 21:23:46.980: I/Adreno-EGL(5085): <qeglDrvAPI_eglInitialize:410>: EGL 1.4 

Upoin单击一个按钮我需要调用此方法以及其他几种方法,这就是我没有将onClick放在AsyncTask中的原因:

        NextQuestionButton.setOnClickListener(new OnClickListener(){;
                @Override
        public void onClick(View v) {  

//                  showNextAnswers();                      showNextQuestion();
                    showNextRandomQuestion3();
                    countQuestions();

                }});

1 个答案:

答案 0 :(得分:0)

可能以下代码适合您。

//Define This in Activity Class;
private String answerId;

private class Task extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
            SQLDatabaseHelper db = new SQLDatabaseHelper(MainActivity.this);

            //get the data from the database
            List<List<String>> listList = db.getAllAnswersByQuestion1();

            //Get the question/text/answer Strings
            List<String> questionStrings = listList.get(0); //question Strings
            List<String> answerSetIds = listList.get(1);

            //Generate random index
            Random r = new Random();
            int rand = Math.abs((r.nextInt() % questionStrings.size()));

            //get answer description for randomly selected question
            String questionString = questionStrings.get(rand);  
            String answerSetId = answerSetIds.get(rand);

            String regex = "\\[|\\]";
            answerId = answerSetId.replaceAll(regex, "");
            return mQuestionString = questionString.replaceAll(regex, "");

    }

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

}