Saturday, 22 June 2013

Unique Random Number Generator in Android

Many of my reader ask how to generate unique random number in android without duplication or repetition. In this post I will show simple code snippet which will use to generate random number without repetition or duplication. The code snippet mentioned in this post is used in SmakAndApp quiz game app. User can download SmakAndApp quiz game app from Google Play. 

Initially, I used Random class to generate random number in given range i.e. upto 50 in this example. But problem is, this generate duplicate entry. To know more about Random class visit developer.android.com/reference/java/util/Random.html 

      Random rndNoGnrt = new Random();
      int rndNo = rndNoGnrt.nextInt(50)+1;

To overcome above problem I used List class to create random number without repetition. Given below code is used for unique random number generation.
List<Integer> NumberList = new ArrayList<Integer>();
for (int i = 1; i <= 50; i++) 
     {
  NumberList.add(i); 
    } 
  Collections.shuffle(NumberList);
  NumberList.get(0)
  NumberList.remove(0); 

Searched Key:
Random number generator example in android.
Generate random numbers without duplication.
Generating a unique random number between given numbers.
Generate random number without repetition

Wednesday, 12 June 2013

Timer Execption In Android

FATAL EXCEPTION: Timer-1 
"Only the original thread that created a view hierarchy can touch its views."

Above given exception occurred when I used following piece of code in my app.

public void onClick(View v) 
{
SetGlobal.parseQuestCount++;
SetGlobal.titleQuestCount++;
final Timer tmr = new Timer(); 
tmr.schedule(new TimerTask() {
 public void run() {  
setQuestion();
t.cancel(); 
}}, 1000);
}

This is because setQuestion() method (In my case) can only be called from UI thread, but it is called from  tmr.schedule(new TimerTask(){..}) method. So the following error occured.


To overcome the error use runOnUiThread(Runnable action) method. This Runs the specified action on the UI thread.
public void onClick(View v)
{
SetGlobal.parseQuestCount++;
SetGlobal.titleQuestCount++;

final Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
setQuestion();
tmr.cancel();
}
});
}}, 1000);
}