-4

I am a beginner to Android development and am trying to make an application whose requirement is to display random number in a text box, and continue to display the random numbers with one second or any programmable delay, till the time the toggle button is in 'ON' state. Does anyone have suggestion on it, or if possible sharing a partial source code would be good.

Another suggestion that I would require is regarding any good book to start off with android development with its internal details also. If there is any sort of book on android as that we have for other development languages (ex. Complete Reference to Java, Complete Reference to C, C++ etc)

Thanks in advance

Veger
  • 37,240
  • 11
  • 105
  • 116
user1986379
  • 53
  • 1
  • 2

3 Answers3

1

I have read some Andoid books and I strongly suggest Android in Practice. After you have read it, you'll know that the majority of people asking questions here on StackOverflow would substantially benefit from this book alone. It's excellent price-value and the authors definitely knew what they were writing about.

Edit: Regarding the implementation (UPDATED, eliminated boolean)

public final class MyActivity extends Activity implements Runnable {
    private Handler uiThreadHandler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // basics
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_activity_layout);
        // find text widget here, store in editText as also required in Chintan's solution
        // get the current activity's handler, it's the UI thread
        uiThreadHandler = new Handler();
        // initiate the updates if that's the initial state
        scheduletUpdate();
        // register callbacks for button etc as required also in Chintan's solution
    }
    @Override
    public void run() {
        //update your editText field here -- this is run in the UI thread so it's safe!
        scheduleUpdate();
    }
    private void scheduleUpdate() {
        uiThreadHandler.postDelayed(this, 1000); // 1000 ms
    }
    // etc, some stuff missing
}

Edit: Regarding how to stop the scheduling of executing the run() method, you use the following code, which should be obvious from the Handler documentation (UPDATED, eliminated boolean):

uiThreadHandler.removeCallbacks(this);
class stacker
  • 5,357
  • 2
  • 32
  • 65
  • May i know, where is the code to stop this `uiThreadHandler.postDelayed(this, 1000);'. Because, its toggle button, because when my toggle button switch `off`, it must stop updation. – Chintan Rathod Jan 22 '13 at 12:22
  • @ChintanRathod See my updated answer. You're not very familiar with Handlers, are you? – class stacker Jan 22 '13 at 12:36
  • @ChintanRathod As I think of it, I can really get rid of the processUpdates flag, which would only be useful in a situation where real concurrency exists -- not the case here. Thanks for inspiring me to provide an even more elegant, lean solution. Will update my answer now. – class stacker Jan 22 '13 at 12:43
  • Yes, I am familiar with Handlers, that is why I used more precise `Cases` in which you can put other branches also like `START`,`STOP` and others. +1 for your answer. – Chintan Rathod Jan 22 '13 at 12:46
  • 1
    @ChintanRathod Thank you for challenging my response. I enjoyed it. – class stacker Jan 22 '13 at 12:59
0

As a beginner, I would suggest you to go through http://www.mybringback.com/series/android-basics/ this tutorials and you will be able to do what you have asked by yourselves. They also have easy to follow video tutorials.

zdesam
  • 2,936
  • 3
  • 25
  • 32
0

Use Thread like,

class MyThread extends Thread
{
    private volatile boolean isRunning = false;

    public synchronized void requestStop() {
        isRunning = true;
    }

    @Override
    public void run() {
        //place code here...
        try {
            while (!isRunning) {
                // do your coding
                handler.sendMessage(handler.obtainMessage(WhatAbout.CHANGE_TEXT.ordinal(), 0, 0));
                Thread.sleep(1000 * 1); //1000 ms = 1 sec
            }


        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Now define following code to handle multiple messages.

public enum WhatAbout {
    CHANGE_TEXT
}

public WhatAbout[] wa = WhatAbout.values();

Then use [Handler][1], which helps you to communicate BackgroundThread and UIThread. Without using handler, you can't change UI.

Put following code in your onCreate method.

handler = new Handler() {
  @Override
  public void handleMessage(Message msg) {
    if (msg.what < wa.length) {
    switch (wa[msg.what]) 
    {
    case CHANGE_TEXT:
         editText.setText(randomVariable);
         break;
    }
  }
};

When you toggle switch off, use following code to stop thread.

if (thread != null) {
    thread .requestStop();
    thread = null;
}
Chintan Rathod
  • 25,864
  • 13
  • 83
  • 93
  • Your solution seems rather complicated to me. I don't think he'll need a Thread for that. And why do you ignore thread interrupts and introduce a flag of your own? – class stacker Jan 22 '13 at 10:28
  • @ClassStacker, do you have any solution other then this??? You have posted an answer, only a practical tutorial suggestion. Is it considered as answer ? can't you post this in comment? – Chintan Rathod Jan 22 '13 at 10:30
  • In this, @ClassStacker, i think you have poor knowledge about thread. If you put your `Thread` in `sleep` mode, probably you have to surround it with `try and catch`. – Chintan Rathod Jan 22 '13 at 12:24
  • Your response is completely besides my point. I asked you why you need a separate flag for ending the thread, when you could use the interrupt mechanism, which you already treat (although not in a fashion where it allows you to end the thread). But thanks for your assessment of my knowledge, I appreciate it. – class stacker Jan 22 '13 at 12:39
  • @ClassStacker, I searched for more than 10 times and found this solution as well in http://stackoverflow.com/questions/4756862/how-to-stop-a-thread and http://stackoverflow.com/questions/8505707/android-best-and-safe-way-to-stop-thread answers. You can see that variable can handle whole thread very safely. – Chintan Rathod Jan 22 '13 at 12:54
  • I know this discussion, but in your case, the interrupt mechanism isn't dangerous at all. The interrupt mechanism _either_ sets a flag which you can poll (just like your additional flag), _or_ it interrupts a blocking call which then throws an exception (which you already catch). Since you have to catch it either way, why not use it? Interrupts only tend to be ugly once your thread performs I/O operations. EDIT: In one of the discussions you reference, one answer from a person with a high reputation suggests using the interrupt mechanism. The chosen answer is not always the best...? ;) – class stacker Jan 22 '13 at 13:03