Help with thread / handlers

Put your problem here if it does not fit any of the other categories.

Help with thread / handlers

Postby sam_jk » Fri Feb 10, 2012 8:48 pm

Hi all,

I'm quite new to Android, and am trying to write a simple app to get me started. The idea is that the user is asked maths questions, and 4 answers are presented, 1 of them being the correct answer. The user can select and is told whether they are right or not.

I have got that much working. My problem now is that I am trying to get the code to wait a second then create a new question. After answering the question and issuing a wait command, the screen does not update with what the answer was for the user. This is due to the fact that the GUI does not update until the main thread has stopped. Instead, after a second the next question appears.

I know that I have to use either a handler or a thread to solve this issue, but I'm not sure which. Eventually my app will use a time limit so then I will need use of this even further. I've looked at examples and tutorials using Handlers but don't really understand them and can't get anything to work. I was hoping that someone here could explain how I could use a Handler or thread to deal with this situation. Currently my code does this (very brief pseudo-code):

onCreate
{
generate question
set answers
update screen
}

on click (called from XML)
{
check answer
update screen
wait a second
generate question
}

So my main problem is not knowing how a handler should work, and what it should be doing.
sam_jk
Freshman
Freshman
 
Posts: 2
Joined: Fri Feb 10, 2012 8:40 pm

Top

Re: Help with thread / handlers

Postby sam_jk » Fri Feb 10, 2012 10:26 pm

Hi guys,

I finally got it working using AsyncTask (below). Could someone let me know if what I've done is an okay way of doing it, or am I doing something badly / inefficiently?

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package android.mathsapp;
  2.  
  3. import java.util.Random;
  4.  
  5. import android.app.Activity;
  6. import android.os.AsyncTask;
  7. import android.os.Bundle;
  8. import android.view.View;
  9. import android.widget.Button;
  10. import android.widget.TextView;
  11.  
  12. public class MathsAppActivity extends Activity {
  13.        
  14.         private String question;
  15.         private int answer;
  16.         private TextView questionText, answerAText, answerBText, answerCText, answerDText;
  17.        
  18.         private int[] answers = new int[4];
  19.         int answerButton;
  20.         int answerButtonId;
  21.         private Random r = new Random();
  22.        
  23.     /** Called when the activity is first created. */
  24.     @Override
  25.     public void onCreate(Bundle savedInstanceState) {
  26.         super.onCreate(savedInstanceState);
  27.         setContentView(R.layout.main);
  28.          questionText = (TextView) findViewById(R.id.question);
  29.          answerAText = (Button) findViewById(R.id.answerA);
  30.          answerBText = (Button) findViewById(R.id.answerB);
  31.          answerCText = (Button) findViewById(R.id.answerC);
  32.          answerDText = (Button) findViewById(R.id.answerD);
  33.          generateQuestion(0);
  34.     }
  35.    
  36.     public void generateQuestion(int delay)
  37.         {
  38.                 new GenerateQuestion().execute(delay);
  39.                
  40.         }
  41.        
  42.     private class GenerateQuestion extends AsyncTask<Integer, Void, Void> {
  43.  
  44.                 @Override
  45.                 protected Void doInBackground(Integer... params) {
  46.                         try {
  47.                                 Thread.sleep(params[0]);
  48.                         } catch (InterruptedException e) {
  49.                                 // TODO Auto-generated catch block
  50.                                 e.printStackTrace();
  51.                         }
  52.                         int type = getRandomInt(1, 4);
  53.                         if(type==1)
  54.                         { // addition
  55.                                 generateAdditionQuestion();
  56.                         }
  57.                         else if(type==2)
  58.                         { // subtraction
  59.                                 generateAdditionQuestion();
  60.                         }
  61.                         else if(type==3)
  62.                         { // multiplication
  63.                                 generateAdditionQuestion();
  64.                         }
  65.                         else
  66.                         { // division
  67.                                 generateAdditionQuestion();
  68.                         }
  69.                         setAnswers();
  70.                         return null;
  71.                        
  72.                 }
  73.                
  74.                 protected void onPostExecute(Void unused)
  75.                 {
  76.                         updateScreen();
  77.                 }
  78.         }
  79.    
  80.         public void generateAdditionQuestion()
  81.         {
  82.                 int numberA = getRandomInt(1, 1000);
  83.                 int numberB = getRandomInt(1, 1000);
  84.                 question = numberA + " + " + numberB;
  85.                 answer = numberA + numberB;    
  86.         }
  87.        
  88.         public void setAnswers()
  89.         {
  90.                 answerButton = getRandomInt(0,3);
  91.                 switch (answerButton)
  92.                 {
  93.                         case 0:
  94.                                 answerButtonId = R.id.answerA;
  95.                                 break;
  96.                         case 1:
  97.                                 answerButtonId = R.id.answerB;
  98.                                 break;
  99.                         case 2:
  100.                                 answerButtonId = R.id.answerC;
  101.                                 break;
  102.                         case 3:
  103.                                 answerButtonId = R.id.answerD;
  104.                                 break;
  105.                 }
  106.                 for(int i=0; i<4; i++)
  107.                 {
  108.                         if (answerButton==i)
  109.                                 answers[i] = answer;
  110.                         else
  111.                                 answers[i] = getRandomInt(answer-getRandomInt(10,100),answer+getRandomInt(10,100));
  112.                 }
  113.                
  114.         }
  115.        
  116.        
  117.        
  118.         /*
  119.          * Called when answer is clicked
  120.          */
  121.         public void checkAnswer(View v) throws InterruptedException
  122.         {
  123.                 new CheckAnswer().execute(v);
  124.         }
  125.        
  126.  
  127.         private class CheckAnswer extends AsyncTask<View, Void, Void> {
  128.  
  129.                 @Override
  130.                 protected Void doInBackground(View... params) {
  131.                         Button clickedButton = (Button)params[0];
  132.                         if (clickedButton.getId()==answerButtonId)
  133.                         {
  134.                                 question = "Correct!";
  135.                         }
  136.                         else
  137.                         {
  138.                                 question = "Incorrect!";
  139.                         }
  140.                         return null;
  141.                        
  142.                 }
  143.                
  144.                 protected void onPostExecute(Void unused)
  145.                 {
  146.                         updateScreen();
  147.                        
  148.                         generateQuestion(1000);
  149.                 }
  150.         }
  151.        
  152.         public void updateScreen()
  153.         {
  154.                 questionText.setText(question);
  155.                 answerAText.setText(Integer.toString(answers[0]));
  156.                 answerBText.setText(Integer.toString(answers[1]));
  157.                 answerCText.setText(Integer.toString(answers[2]));
  158.                 answerDText.setText(Integer.toString(answers[3]));
  159.         }
  160.        
  161.         private int getRandomInt(int min, int max){
  162.         if ( min > max ) {
  163.             throw new IllegalArgumentException("Start cannot exceed End.");
  164.         }
  165.        
  166.         int randomNum = r.nextInt(max - min + 1) + min;                
  167.         return randomNum;
  168.         }
  169.        
  170. }
  171.  
Parsed in 0.047 seconds, using GeSHi 1.0.8.4
sam_jk
Freshman
Freshman
 
Posts: 2
Joined: Fri Feb 10, 2012 8:40 pm

Re: Help with thread / handlers

Postby Phyll » Sat Feb 11, 2012 9:48 pm

Hi sam_jk,

Guess I might have used a timer to create a delay. Unless the question loading is very lengthy.

Here's an example of a timer. It calls the timer_tick runnable here every 1/10th second. Use that repeating call to update the UI or trigger actions in your code. If you want to wait one second and then start another question all you have to do is start a count and when it reaches 10, call the method to start the question cycle over. If you want to limit the time the user has to answer, start a count and end that question if it counts out before the answer is entered. Just a couple of ideas.


Code: Select all
public class App11 extends Activity {
    private Timer tenthsecondtimer


    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        //Create new daemon timer
        tenthsecondtimer = new Timer(true);
        tenthsecondtimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                TimerMethod();
                }//run
            }, 100, 100);//schedule

        }
    private void TimerMethod() {
        //This method is called directly by the timer
        //and runs in the same thread as the timer.

        //We call the method that will work with the UI
        //through the runOnUiThread method.
        this.runOnUiThread(Timer_Tick);
        }//timermethod

    private Runnable Timer_Tick = new Runnable() {
        public void run() {
            //This method runs in the same thread as the UI.
            //Do something to the UI thread here
            }//run
        };//runnable

    //TODO: Fill In Methods Etc.
    }//class



Hope this helps.

Phyll
Phyll
Master Developer
Master Developer
 
Posts: 648
Joined: Fri Oct 14, 2011 11:19 am

Top

Return to Other Coding-Problems

Who is online

Users browsing this forum: No registered users and 17 guests