Working NumberPicker and Android

For the last few weeks, I’ve been working on and off on a small android project. For number selection, I wanted to use something similar to what’s in the Alarm Clock that ships with most Android phones… a simple control made out of 3 elements, a text field, an “increase” button and a “decrease” button. I was really surprised to see that this is not part of the SDK. After checking on the net, I found this site:

It seemed to work well most of the time, but I had a strange behavior that I thought was coming from my side… After displaying the NumberPicker in a Dialog, I was using an OnClick on some button in this dialog, and sometimes the number I was getting from the picker didn’t correspond to what was on screen. Also, after seeing the application running on my phone, I decided to show it to my fiancée, and her first try at it broke the NumberPicker! If you hold one of the buttons, the picker will loop infinitely increasing or decreasing the value.

There might be other issues but here’s my fix to the two of them:

First, the infinitely increasing value problem, it appears that the code that’s constantly run does not have exit conditions, here’s how I fixed it:

private final Runnable mRunnable = new Runnable() {
    public void run() {
    boolean repost = false;
    if (mIncrement) {
        changeCurrent(mCurrent + 1);
            repost = true;
    } else if (mDecrement) {
        changeCurrent(mCurrent - 1);
            repost = true;
        mHandler.postDelayed(this, mSpeed);

I simply check if the button is still pressed before reposting the “increase” callback.

As for the value, if the text edit was currently being edited and the value was fetched before it lost focus, it was still returning the old value… the fix is quite simple:

public int getCurrent() {
    return mCurrent;

Here’s the modified to be used with QuietlyCoding’s package, feel free to comment if you have any questions!


One thought on “Working NumberPicker and Android

  1. Miss says:

    Leave it up to me to break it 😉 Good job fixing it!

Leave a Reply

Your email address will not be published. Required fields are marked *