Skip to content Skip to sidebar Skip to footer

Android App That Generates Random Words Every Second And Displays Them On Screen

How can I make an android app that generates a random word every 1 second? Here is my code: new Timer().scheduleAtFixedRate(new TimerTask(){ public void run()

Solution 1:

Undoubtfully, run this within a Thread. Doing this, it will generate the words in background and once it already has, the main UI thread must just append the content to the txt instance.

new Thread(
  new Runnable() { 
    publicvoidrun() {
      // your stuff
    }
  }
).start()

To assign the result to the txt object, you'll probably be unable to do it within this thread. To do so, you'll need to declare a Handler in your Activity and use that handler within your thread, so it uses sendMessage() to the main Activity and the Activity just sets the text.

More on this here and here.

---- EDIT ----

As @FD_ says, there is another way to do the update without the use of a Handler. You would just need to call the runOnUiThread() method, something like this:

runOnUiThread(new Runnable() {
  publicvoidrun() {
    txt.setText(your_new_text);
  }
});

Another way is using an AsyncTask, which is (talking vaguely) an "evolution" of a thread which makes a lot of stuff for you. More on AsyncTasks here.

---- EDIT ----

This would be one of the ways:

new Thread(
  new Runnable() { 
    publicvoidrun() {
      new Timer().scheduleAtFixedRate(new TimerTask() {
        publicvoidrun()   {
          started = true;
          word = "";
          for (int i = 0; i < lenght+1; i++)
          {
            int j = rand.nextInt((max-min) + 1) + min;
            word += tr.Translate(j);
          }

          // This will update your txt instance without the need of a Handler
          runOnUiThread(new Runnable() {
            publicvoidrun() {
              txt.setText(word);
            }
          });
        }
      }, 0, 5000);
    }
  }).start();

Solution 2:

try this:

int i = 0;

publicvoidchangeString() {
    started = true;
    word = "";

    int j = rand.nextInt((max - min) + 1) + min;
    word += tr.Translate(j);

    txt.setText(word);
    new Handler().postDelayed(new Runnable() {

        @Override
        publicvoidrun() {
            if (i < lenght + 1) {
                changeString();
                i++;
            }
        }
    }, 1000);
}

You can do this using timer as well

int i=0;
new Timer().scheduleAtFixedRate(new TimerTask(){
        publicvoidrun()
        {
    started = true;
    word = "";
    int j = rand.nextInt((max-min) + 1) + min;
    word += tr.Translate(j);
    txt.setText(word);
    i++
        }

}, 0, 5000);

try the above. The mistake you were making is using a for loop inside run instead use loop run method it-self.

Post a Comment for "Android App That Generates Random Words Every Second And Displays Them On Screen"