implementing Handler interaction with the UI thread on a continuous loop










0















Bear with me, I'm still a little new to android.



So I am in the process of making a complex button listener. This listener should recognize a short press, flash in some way (like the normal onClick functionality), as well recognize a long press.



Upon a short press, it would update a (integer) textView by increasing/decreasing the value. If the user holds the button down the textView, it will continuously increase/decrease until the button is released.



Thus far I have found 2 popular threads regarding this sort of issue:



  • Android - Hold Button to Repeat Action

  • Continuously increase integer value as the button is pressed

The problem I have with the the answers in these threads is I feel they can be broken down further. Instead of creating a single class to hold everything regarding the button listener, I would like to separate the physical "Task" that would run on the handler thread into it's own class. In fact, I believe this is what the android documentation recommends doing



https://developer.android.com/training/multiple-threads/communicate-ui#java



Right now I have a working implementation for the normal passing of data between the task on the handler and the UI thread for a single alteration. However, once I start adding in loops, it stops working properly. If I do a for loop (i.e. from 0 to 9), it seems to start ignoring the "delay" part of the post, and does all of the increments, and updates the UI when it's all finished. If I try a while loop, it never updates the textView for similar reasons as why the for loop might have failed.



Here are the classes I have implemented, I'll explain bellow:



public class AutoUpdatingListener implements View.OnTouchListener, View.OnClickListener, View.OnLongClickListener 

private TextView textView;
private int textNumber;
private String decision;
private AutoUpdateTask updateTask;
private static final String MSG_KEY = "textData";

private final Handler handler = new Handler(Looper.getMainLooper())
@Override
public void handleMessage(Message msg)
Bundle bundle = msg.getData();
int data = bundle.getInt(MSG_KEY);

textView.setText(String.format(Locale.getDefault(), "%d", data));

;

public AutoUpdatingListener(TextView textView, String decision)
this.decision = decision;
this.textView = textView;
this.textNumber = Integer.parseInt(textView.getText().toString());

updateTask = new AutoUpdateTask(handler, textNumber, decision, MSG_KEY);


public void onClick(View v)
textNumber = (decision.equals("increase")) ? ++textNumber : (decision.equals("decrease")) ? --textNumber : textNumber;
textView.setText(String.format(Locale.getDefault(),"%d", textNumber));


public boolean onLongClick(View v)
autoUpdate = true;

handler.postDelayed(updateTask, 500);

return true;


public boolean onTouch(View v, MotionEvent event)
if (event.getAction() == MotionEvent.ACTION_UP)
autoUpdate = false;
handler.removeCallbacks(updateTask);


return false;




Here is the Task Object:



public class AutoUpdateTask implements Runnable 
private Handler handler;
private int textNumber;
private final String decision;
private final String MSG_KEY;

public AutoUpdateTask(Handler handler, int tempo, String decision, final String MSG_KEY)
this.handler = handler;
this.tempo = tempo;
this.decision = decision;
this.MSG_KEY = MSG_KEY;


@Override
public void run()
// 2nd variation would be to place the loop here
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

for (int i = 0; i < 10; i++)
textNumber = decision.equals("increase") ? ++tempo : decision.equals("decrease") ? --tempo : tempo;

Message msg = handler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putInt(MSG_KEY, tempo);
msg.setData(bundle);
handler.sendMessage(msg);

SystemClock.sleep(500);





This is all being used in the following context within the onCreate method:



AutoIncrementingListener customListener = new AutoIncrementingListener(textView, "increase");
upArrow.setOnClickListener(customListener);
upArrow.setOnLongClickListener(customListener);
upArrow.setOnTouchListener(customListener);


So essentially if the user does a short click, it updates the field and the action is done. If the user holds the button, it will go to the longClick listener first, and create a task consisting of a reference to the handler, the text to increment, the "increase" determination, and a unique message key.



The task is then posted with a delay onto the handler thread, and it is executed (the number is incremented), and it then creates a message to send back to the UI thread and updates the textView. This process continues until the user releases the button.



This is all in theory, as I've explained above, it currently doesn't quite work as defined.



Update



I have since put the loop into the task's run() method. In this loop I have added a sleep(500) call to stop the increments from firing at the same time.



However, the issue of the UI not updating still persists (despite the sent messages and implemented handleMessage() function). I.E: after about 5 seconds when it completes the loop it finally updates the textView.



Conclusion



I am abandoning this implementation, so sorry for those who have come across this question seeking answers. I hope this thread has given some insight towards your own implementations.



With the above update, I realized through debugging that regardless of execution time, the messages were being sent all together after the loop was done. For those seeking this implementation, they will have to find out how to short-cut this phenomenon.










share|improve this question




























    0















    Bear with me, I'm still a little new to android.



    So I am in the process of making a complex button listener. This listener should recognize a short press, flash in some way (like the normal onClick functionality), as well recognize a long press.



    Upon a short press, it would update a (integer) textView by increasing/decreasing the value. If the user holds the button down the textView, it will continuously increase/decrease until the button is released.



    Thus far I have found 2 popular threads regarding this sort of issue:



    • Android - Hold Button to Repeat Action

    • Continuously increase integer value as the button is pressed

    The problem I have with the the answers in these threads is I feel they can be broken down further. Instead of creating a single class to hold everything regarding the button listener, I would like to separate the physical "Task" that would run on the handler thread into it's own class. In fact, I believe this is what the android documentation recommends doing



    https://developer.android.com/training/multiple-threads/communicate-ui#java



    Right now I have a working implementation for the normal passing of data between the task on the handler and the UI thread for a single alteration. However, once I start adding in loops, it stops working properly. If I do a for loop (i.e. from 0 to 9), it seems to start ignoring the "delay" part of the post, and does all of the increments, and updates the UI when it's all finished. If I try a while loop, it never updates the textView for similar reasons as why the for loop might have failed.



    Here are the classes I have implemented, I'll explain bellow:



    public class AutoUpdatingListener implements View.OnTouchListener, View.OnClickListener, View.OnLongClickListener 

    private TextView textView;
    private int textNumber;
    private String decision;
    private AutoUpdateTask updateTask;
    private static final String MSG_KEY = "textData";

    private final Handler handler = new Handler(Looper.getMainLooper())
    @Override
    public void handleMessage(Message msg)
    Bundle bundle = msg.getData();
    int data = bundle.getInt(MSG_KEY);

    textView.setText(String.format(Locale.getDefault(), "%d", data));

    ;

    public AutoUpdatingListener(TextView textView, String decision)
    this.decision = decision;
    this.textView = textView;
    this.textNumber = Integer.parseInt(textView.getText().toString());

    updateTask = new AutoUpdateTask(handler, textNumber, decision, MSG_KEY);


    public void onClick(View v)
    textNumber = (decision.equals("increase")) ? ++textNumber : (decision.equals("decrease")) ? --textNumber : textNumber;
    textView.setText(String.format(Locale.getDefault(),"%d", textNumber));


    public boolean onLongClick(View v)
    autoUpdate = true;

    handler.postDelayed(updateTask, 500);

    return true;


    public boolean onTouch(View v, MotionEvent event)
    if (event.getAction() == MotionEvent.ACTION_UP)
    autoUpdate = false;
    handler.removeCallbacks(updateTask);


    return false;




    Here is the Task Object:



    public class AutoUpdateTask implements Runnable 
    private Handler handler;
    private int textNumber;
    private final String decision;
    private final String MSG_KEY;

    public AutoUpdateTask(Handler handler, int tempo, String decision, final String MSG_KEY)
    this.handler = handler;
    this.tempo = tempo;
    this.decision = decision;
    this.MSG_KEY = MSG_KEY;


    @Override
    public void run()
    // 2nd variation would be to place the loop here
    android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    for (int i = 0; i < 10; i++)
    textNumber = decision.equals("increase") ? ++tempo : decision.equals("decrease") ? --tempo : tempo;

    Message msg = handler.obtainMessage();
    Bundle bundle = new Bundle();
    bundle.putInt(MSG_KEY, tempo);
    msg.setData(bundle);
    handler.sendMessage(msg);

    SystemClock.sleep(500);





    This is all being used in the following context within the onCreate method:



    AutoIncrementingListener customListener = new AutoIncrementingListener(textView, "increase");
    upArrow.setOnClickListener(customListener);
    upArrow.setOnLongClickListener(customListener);
    upArrow.setOnTouchListener(customListener);


    So essentially if the user does a short click, it updates the field and the action is done. If the user holds the button, it will go to the longClick listener first, and create a task consisting of a reference to the handler, the text to increment, the "increase" determination, and a unique message key.



    The task is then posted with a delay onto the handler thread, and it is executed (the number is incremented), and it then creates a message to send back to the UI thread and updates the textView. This process continues until the user releases the button.



    This is all in theory, as I've explained above, it currently doesn't quite work as defined.



    Update



    I have since put the loop into the task's run() method. In this loop I have added a sleep(500) call to stop the increments from firing at the same time.



    However, the issue of the UI not updating still persists (despite the sent messages and implemented handleMessage() function). I.E: after about 5 seconds when it completes the loop it finally updates the textView.



    Conclusion



    I am abandoning this implementation, so sorry for those who have come across this question seeking answers. I hope this thread has given some insight towards your own implementations.



    With the above update, I realized through debugging that regardless of execution time, the messages were being sent all together after the loop was done. For those seeking this implementation, they will have to find out how to short-cut this phenomenon.










    share|improve this question


























      0












      0








      0








      Bear with me, I'm still a little new to android.



      So I am in the process of making a complex button listener. This listener should recognize a short press, flash in some way (like the normal onClick functionality), as well recognize a long press.



      Upon a short press, it would update a (integer) textView by increasing/decreasing the value. If the user holds the button down the textView, it will continuously increase/decrease until the button is released.



      Thus far I have found 2 popular threads regarding this sort of issue:



      • Android - Hold Button to Repeat Action

      • Continuously increase integer value as the button is pressed

      The problem I have with the the answers in these threads is I feel they can be broken down further. Instead of creating a single class to hold everything regarding the button listener, I would like to separate the physical "Task" that would run on the handler thread into it's own class. In fact, I believe this is what the android documentation recommends doing



      https://developer.android.com/training/multiple-threads/communicate-ui#java



      Right now I have a working implementation for the normal passing of data between the task on the handler and the UI thread for a single alteration. However, once I start adding in loops, it stops working properly. If I do a for loop (i.e. from 0 to 9), it seems to start ignoring the "delay" part of the post, and does all of the increments, and updates the UI when it's all finished. If I try a while loop, it never updates the textView for similar reasons as why the for loop might have failed.



      Here are the classes I have implemented, I'll explain bellow:



      public class AutoUpdatingListener implements View.OnTouchListener, View.OnClickListener, View.OnLongClickListener 

      private TextView textView;
      private int textNumber;
      private String decision;
      private AutoUpdateTask updateTask;
      private static final String MSG_KEY = "textData";

      private final Handler handler = new Handler(Looper.getMainLooper())
      @Override
      public void handleMessage(Message msg)
      Bundle bundle = msg.getData();
      int data = bundle.getInt(MSG_KEY);

      textView.setText(String.format(Locale.getDefault(), "%d", data));

      ;

      public AutoUpdatingListener(TextView textView, String decision)
      this.decision = decision;
      this.textView = textView;
      this.textNumber = Integer.parseInt(textView.getText().toString());

      updateTask = new AutoUpdateTask(handler, textNumber, decision, MSG_KEY);


      public void onClick(View v)
      textNumber = (decision.equals("increase")) ? ++textNumber : (decision.equals("decrease")) ? --textNumber : textNumber;
      textView.setText(String.format(Locale.getDefault(),"%d", textNumber));


      public boolean onLongClick(View v)
      autoUpdate = true;

      handler.postDelayed(updateTask, 500);

      return true;


      public boolean onTouch(View v, MotionEvent event)
      if (event.getAction() == MotionEvent.ACTION_UP)
      autoUpdate = false;
      handler.removeCallbacks(updateTask);


      return false;




      Here is the Task Object:



      public class AutoUpdateTask implements Runnable 
      private Handler handler;
      private int textNumber;
      private final String decision;
      private final String MSG_KEY;

      public AutoUpdateTask(Handler handler, int tempo, String decision, final String MSG_KEY)
      this.handler = handler;
      this.tempo = tempo;
      this.decision = decision;
      this.MSG_KEY = MSG_KEY;


      @Override
      public void run()
      // 2nd variation would be to place the loop here
      android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

      for (int i = 0; i < 10; i++)
      textNumber = decision.equals("increase") ? ++tempo : decision.equals("decrease") ? --tempo : tempo;

      Message msg = handler.obtainMessage();
      Bundle bundle = new Bundle();
      bundle.putInt(MSG_KEY, tempo);
      msg.setData(bundle);
      handler.sendMessage(msg);

      SystemClock.sleep(500);





      This is all being used in the following context within the onCreate method:



      AutoIncrementingListener customListener = new AutoIncrementingListener(textView, "increase");
      upArrow.setOnClickListener(customListener);
      upArrow.setOnLongClickListener(customListener);
      upArrow.setOnTouchListener(customListener);


      So essentially if the user does a short click, it updates the field and the action is done. If the user holds the button, it will go to the longClick listener first, and create a task consisting of a reference to the handler, the text to increment, the "increase" determination, and a unique message key.



      The task is then posted with a delay onto the handler thread, and it is executed (the number is incremented), and it then creates a message to send back to the UI thread and updates the textView. This process continues until the user releases the button.



      This is all in theory, as I've explained above, it currently doesn't quite work as defined.



      Update



      I have since put the loop into the task's run() method. In this loop I have added a sleep(500) call to stop the increments from firing at the same time.



      However, the issue of the UI not updating still persists (despite the sent messages and implemented handleMessage() function). I.E: after about 5 seconds when it completes the loop it finally updates the textView.



      Conclusion



      I am abandoning this implementation, so sorry for those who have come across this question seeking answers. I hope this thread has given some insight towards your own implementations.



      With the above update, I realized through debugging that regardless of execution time, the messages were being sent all together after the loop was done. For those seeking this implementation, they will have to find out how to short-cut this phenomenon.










      share|improve this question
















      Bear with me, I'm still a little new to android.



      So I am in the process of making a complex button listener. This listener should recognize a short press, flash in some way (like the normal onClick functionality), as well recognize a long press.



      Upon a short press, it would update a (integer) textView by increasing/decreasing the value. If the user holds the button down the textView, it will continuously increase/decrease until the button is released.



      Thus far I have found 2 popular threads regarding this sort of issue:



      • Android - Hold Button to Repeat Action

      • Continuously increase integer value as the button is pressed

      The problem I have with the the answers in these threads is I feel they can be broken down further. Instead of creating a single class to hold everything regarding the button listener, I would like to separate the physical "Task" that would run on the handler thread into it's own class. In fact, I believe this is what the android documentation recommends doing



      https://developer.android.com/training/multiple-threads/communicate-ui#java



      Right now I have a working implementation for the normal passing of data between the task on the handler and the UI thread for a single alteration. However, once I start adding in loops, it stops working properly. If I do a for loop (i.e. from 0 to 9), it seems to start ignoring the "delay" part of the post, and does all of the increments, and updates the UI when it's all finished. If I try a while loop, it never updates the textView for similar reasons as why the for loop might have failed.



      Here are the classes I have implemented, I'll explain bellow:



      public class AutoUpdatingListener implements View.OnTouchListener, View.OnClickListener, View.OnLongClickListener 

      private TextView textView;
      private int textNumber;
      private String decision;
      private AutoUpdateTask updateTask;
      private static final String MSG_KEY = "textData";

      private final Handler handler = new Handler(Looper.getMainLooper())
      @Override
      public void handleMessage(Message msg)
      Bundle bundle = msg.getData();
      int data = bundle.getInt(MSG_KEY);

      textView.setText(String.format(Locale.getDefault(), "%d", data));

      ;

      public AutoUpdatingListener(TextView textView, String decision)
      this.decision = decision;
      this.textView = textView;
      this.textNumber = Integer.parseInt(textView.getText().toString());

      updateTask = new AutoUpdateTask(handler, textNumber, decision, MSG_KEY);


      public void onClick(View v)
      textNumber = (decision.equals("increase")) ? ++textNumber : (decision.equals("decrease")) ? --textNumber : textNumber;
      textView.setText(String.format(Locale.getDefault(),"%d", textNumber));


      public boolean onLongClick(View v)
      autoUpdate = true;

      handler.postDelayed(updateTask, 500);

      return true;


      public boolean onTouch(View v, MotionEvent event)
      if (event.getAction() == MotionEvent.ACTION_UP)
      autoUpdate = false;
      handler.removeCallbacks(updateTask);


      return false;




      Here is the Task Object:



      public class AutoUpdateTask implements Runnable 
      private Handler handler;
      private int textNumber;
      private final String decision;
      private final String MSG_KEY;

      public AutoUpdateTask(Handler handler, int tempo, String decision, final String MSG_KEY)
      this.handler = handler;
      this.tempo = tempo;
      this.decision = decision;
      this.MSG_KEY = MSG_KEY;


      @Override
      public void run()
      // 2nd variation would be to place the loop here
      android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

      for (int i = 0; i < 10; i++)
      textNumber = decision.equals("increase") ? ++tempo : decision.equals("decrease") ? --tempo : tempo;

      Message msg = handler.obtainMessage();
      Bundle bundle = new Bundle();
      bundle.putInt(MSG_KEY, tempo);
      msg.setData(bundle);
      handler.sendMessage(msg);

      SystemClock.sleep(500);





      This is all being used in the following context within the onCreate method:



      AutoIncrementingListener customListener = new AutoIncrementingListener(textView, "increase");
      upArrow.setOnClickListener(customListener);
      upArrow.setOnLongClickListener(customListener);
      upArrow.setOnTouchListener(customListener);


      So essentially if the user does a short click, it updates the field and the action is done. If the user holds the button, it will go to the longClick listener first, and create a task consisting of a reference to the handler, the text to increment, the "increase" determination, and a unique message key.



      The task is then posted with a delay onto the handler thread, and it is executed (the number is incremented), and it then creates a message to send back to the UI thread and updates the textView. This process continues until the user releases the button.



      This is all in theory, as I've explained above, it currently doesn't quite work as defined.



      Update



      I have since put the loop into the task's run() method. In this loop I have added a sleep(500) call to stop the increments from firing at the same time.



      However, the issue of the UI not updating still persists (despite the sent messages and implemented handleMessage() function). I.E: after about 5 seconds when it completes the loop it finally updates the textView.



      Conclusion



      I am abandoning this implementation, so sorry for those who have come across this question seeking answers. I hope this thread has given some insight towards your own implementations.



      With the above update, I realized through debugging that regardless of execution time, the messages were being sent all together after the loop was done. For those seeking this implementation, they will have to find out how to short-cut this phenomenon.







      android multithreading handler






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 18 '18 at 21:37







      Matthew Strom

















      asked Nov 15 '18 at 4:51









      Matthew StromMatthew Strom

      277




      277






















          1 Answer
          1






          active

          oldest

          votes


















          0














          You cannot do what you are doing this way.
          The reason is the during onLongClick you run a loop that runs all at once without giving the UI time to refresh.



          What does this mean?



          Well, what you are actually doing is sending 10 messages, one after the other all delayed by 500ms. This means that they will arrive all at once, one after the other (with no delay between them) only that you'll have a 500ms gap until the first one arrives.



          What you need to do is increase the delay so each message will have its own delay and be 500ms longer than the previous one.



          handler.postDelayed(updateTask, 500*(i+1));


          That is the first thing.



          The second problem is that you create the updateTask in the C'Tor of the AutoUpdatingListener and so each update task sends the same number for update event if it was just incremented.



          The problem is that even if you change it to this code:



          for (int i = 0; i < 10; i++) // example usage of a long press (looping update)
          this.textNumber = Integer.parseInt(textView.getText().toString());
          updateTask = new AutoUpdateTask(handler, textNumber, decision, MSG_KEY);
          handler.postDelayed(updateTask, 500*(i+1));



          It would not work since during the loop the tasks did not run yet and so the number did not have a chance to update.



          Soooooo you can cheat and increase the number during the loop but this defies all logic.



          for (int i = 0; i < 10; i++) // example usage of a long press (looping update)
          this.textNumber = Integer.parseInt(textView.getText().toString());
          updateTask = new AutoUpdateTask(handler, textNumber+i, decision, MSG_KEY);
          handler.postDelayed(updateTask, 500*(i+1));




          Conclusion
          You cannot have the loop that sends the increment and the handler that does the increment in the same thread...






          share|improve this answer























          • Thanks for the feed back on this iteration. I agree that this implementation doesn't make sense, and your explanation corresponds correctly with my inclinations. That being said, what are your thoughts on this if the loop was placed inside the run() method of the AutoUpdateTask as my comment in that method alluded to?

            – Matthew Strom
            Nov 15 '18 at 18:47











          • That would be better as it would increment the number on a diferent thread. The problem remains of waiting for the ui to update when you send the next number but if you send the increments with long enough delays you might be able to pull it off.

            – Itamar Kerbel
            Nov 15 '18 at 20:27











          • If you found my answer as helpful please mark it as answered. If not what else is missing?

            – Itamar Kerbel
            Nov 17 '18 at 8:42












          • Although your answer was helpful in figuring out why my code is acting the way it is, it didn't provide suggestions to fixing the issue. I was waiting until I found out how to fix it, then I was going to put an answer forth.

            – Matthew Strom
            Nov 18 '18 at 17:14











          • Actually, since the issue to this problem has now revealed more specific issues with a smaller scope, I will go with your answer for the sake of this question being fairly broad. I have been deciding to go with a different language entirely with this project anyways to make issues like these much more simple to solve. I do appreciate the explanations and help!

            – Matthew Strom
            Nov 18 '18 at 21:33











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53312609%2fimplementing-handler-interaction-with-the-ui-thread-on-a-continuous-loop%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          You cannot do what you are doing this way.
          The reason is the during onLongClick you run a loop that runs all at once without giving the UI time to refresh.



          What does this mean?



          Well, what you are actually doing is sending 10 messages, one after the other all delayed by 500ms. This means that they will arrive all at once, one after the other (with no delay between them) only that you'll have a 500ms gap until the first one arrives.



          What you need to do is increase the delay so each message will have its own delay and be 500ms longer than the previous one.



          handler.postDelayed(updateTask, 500*(i+1));


          That is the first thing.



          The second problem is that you create the updateTask in the C'Tor of the AutoUpdatingListener and so each update task sends the same number for update event if it was just incremented.



          The problem is that even if you change it to this code:



          for (int i = 0; i < 10; i++) // example usage of a long press (looping update)
          this.textNumber = Integer.parseInt(textView.getText().toString());
          updateTask = new AutoUpdateTask(handler, textNumber, decision, MSG_KEY);
          handler.postDelayed(updateTask, 500*(i+1));



          It would not work since during the loop the tasks did not run yet and so the number did not have a chance to update.



          Soooooo you can cheat and increase the number during the loop but this defies all logic.



          for (int i = 0; i < 10; i++) // example usage of a long press (looping update)
          this.textNumber = Integer.parseInt(textView.getText().toString());
          updateTask = new AutoUpdateTask(handler, textNumber+i, decision, MSG_KEY);
          handler.postDelayed(updateTask, 500*(i+1));




          Conclusion
          You cannot have the loop that sends the increment and the handler that does the increment in the same thread...






          share|improve this answer























          • Thanks for the feed back on this iteration. I agree that this implementation doesn't make sense, and your explanation corresponds correctly with my inclinations. That being said, what are your thoughts on this if the loop was placed inside the run() method of the AutoUpdateTask as my comment in that method alluded to?

            – Matthew Strom
            Nov 15 '18 at 18:47











          • That would be better as it would increment the number on a diferent thread. The problem remains of waiting for the ui to update when you send the next number but if you send the increments with long enough delays you might be able to pull it off.

            – Itamar Kerbel
            Nov 15 '18 at 20:27











          • If you found my answer as helpful please mark it as answered. If not what else is missing?

            – Itamar Kerbel
            Nov 17 '18 at 8:42












          • Although your answer was helpful in figuring out why my code is acting the way it is, it didn't provide suggestions to fixing the issue. I was waiting until I found out how to fix it, then I was going to put an answer forth.

            – Matthew Strom
            Nov 18 '18 at 17:14











          • Actually, since the issue to this problem has now revealed more specific issues with a smaller scope, I will go with your answer for the sake of this question being fairly broad. I have been deciding to go with a different language entirely with this project anyways to make issues like these much more simple to solve. I do appreciate the explanations and help!

            – Matthew Strom
            Nov 18 '18 at 21:33















          0














          You cannot do what you are doing this way.
          The reason is the during onLongClick you run a loop that runs all at once without giving the UI time to refresh.



          What does this mean?



          Well, what you are actually doing is sending 10 messages, one after the other all delayed by 500ms. This means that they will arrive all at once, one after the other (with no delay between them) only that you'll have a 500ms gap until the first one arrives.



          What you need to do is increase the delay so each message will have its own delay and be 500ms longer than the previous one.



          handler.postDelayed(updateTask, 500*(i+1));


          That is the first thing.



          The second problem is that you create the updateTask in the C'Tor of the AutoUpdatingListener and so each update task sends the same number for update event if it was just incremented.



          The problem is that even if you change it to this code:



          for (int i = 0; i < 10; i++) // example usage of a long press (looping update)
          this.textNumber = Integer.parseInt(textView.getText().toString());
          updateTask = new AutoUpdateTask(handler, textNumber, decision, MSG_KEY);
          handler.postDelayed(updateTask, 500*(i+1));



          It would not work since during the loop the tasks did not run yet and so the number did not have a chance to update.



          Soooooo you can cheat and increase the number during the loop but this defies all logic.



          for (int i = 0; i < 10; i++) // example usage of a long press (looping update)
          this.textNumber = Integer.parseInt(textView.getText().toString());
          updateTask = new AutoUpdateTask(handler, textNumber+i, decision, MSG_KEY);
          handler.postDelayed(updateTask, 500*(i+1));




          Conclusion
          You cannot have the loop that sends the increment and the handler that does the increment in the same thread...






          share|improve this answer























          • Thanks for the feed back on this iteration. I agree that this implementation doesn't make sense, and your explanation corresponds correctly with my inclinations. That being said, what are your thoughts on this if the loop was placed inside the run() method of the AutoUpdateTask as my comment in that method alluded to?

            – Matthew Strom
            Nov 15 '18 at 18:47











          • That would be better as it would increment the number on a diferent thread. The problem remains of waiting for the ui to update when you send the next number but if you send the increments with long enough delays you might be able to pull it off.

            – Itamar Kerbel
            Nov 15 '18 at 20:27











          • If you found my answer as helpful please mark it as answered. If not what else is missing?

            – Itamar Kerbel
            Nov 17 '18 at 8:42












          • Although your answer was helpful in figuring out why my code is acting the way it is, it didn't provide suggestions to fixing the issue. I was waiting until I found out how to fix it, then I was going to put an answer forth.

            – Matthew Strom
            Nov 18 '18 at 17:14











          • Actually, since the issue to this problem has now revealed more specific issues with a smaller scope, I will go with your answer for the sake of this question being fairly broad. I have been deciding to go with a different language entirely with this project anyways to make issues like these much more simple to solve. I do appreciate the explanations and help!

            – Matthew Strom
            Nov 18 '18 at 21:33













          0












          0








          0







          You cannot do what you are doing this way.
          The reason is the during onLongClick you run a loop that runs all at once without giving the UI time to refresh.



          What does this mean?



          Well, what you are actually doing is sending 10 messages, one after the other all delayed by 500ms. This means that they will arrive all at once, one after the other (with no delay between them) only that you'll have a 500ms gap until the first one arrives.



          What you need to do is increase the delay so each message will have its own delay and be 500ms longer than the previous one.



          handler.postDelayed(updateTask, 500*(i+1));


          That is the first thing.



          The second problem is that you create the updateTask in the C'Tor of the AutoUpdatingListener and so each update task sends the same number for update event if it was just incremented.



          The problem is that even if you change it to this code:



          for (int i = 0; i < 10; i++) // example usage of a long press (looping update)
          this.textNumber = Integer.parseInt(textView.getText().toString());
          updateTask = new AutoUpdateTask(handler, textNumber, decision, MSG_KEY);
          handler.postDelayed(updateTask, 500*(i+1));



          It would not work since during the loop the tasks did not run yet and so the number did not have a chance to update.



          Soooooo you can cheat and increase the number during the loop but this defies all logic.



          for (int i = 0; i < 10; i++) // example usage of a long press (looping update)
          this.textNumber = Integer.parseInt(textView.getText().toString());
          updateTask = new AutoUpdateTask(handler, textNumber+i, decision, MSG_KEY);
          handler.postDelayed(updateTask, 500*(i+1));




          Conclusion
          You cannot have the loop that sends the increment and the handler that does the increment in the same thread...






          share|improve this answer













          You cannot do what you are doing this way.
          The reason is the during onLongClick you run a loop that runs all at once without giving the UI time to refresh.



          What does this mean?



          Well, what you are actually doing is sending 10 messages, one after the other all delayed by 500ms. This means that they will arrive all at once, one after the other (with no delay between them) only that you'll have a 500ms gap until the first one arrives.



          What you need to do is increase the delay so each message will have its own delay and be 500ms longer than the previous one.



          handler.postDelayed(updateTask, 500*(i+1));


          That is the first thing.



          The second problem is that you create the updateTask in the C'Tor of the AutoUpdatingListener and so each update task sends the same number for update event if it was just incremented.



          The problem is that even if you change it to this code:



          for (int i = 0; i < 10; i++) // example usage of a long press (looping update)
          this.textNumber = Integer.parseInt(textView.getText().toString());
          updateTask = new AutoUpdateTask(handler, textNumber, decision, MSG_KEY);
          handler.postDelayed(updateTask, 500*(i+1));



          It would not work since during the loop the tasks did not run yet and so the number did not have a chance to update.



          Soooooo you can cheat and increase the number during the loop but this defies all logic.



          for (int i = 0; i < 10; i++) // example usage of a long press (looping update)
          this.textNumber = Integer.parseInt(textView.getText().toString());
          updateTask = new AutoUpdateTask(handler, textNumber+i, decision, MSG_KEY);
          handler.postDelayed(updateTask, 500*(i+1));




          Conclusion
          You cannot have the loop that sends the increment and the handler that does the increment in the same thread...







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 15 '18 at 8:12









          Itamar KerbelItamar Kerbel

          671519




          671519












          • Thanks for the feed back on this iteration. I agree that this implementation doesn't make sense, and your explanation corresponds correctly with my inclinations. That being said, what are your thoughts on this if the loop was placed inside the run() method of the AutoUpdateTask as my comment in that method alluded to?

            – Matthew Strom
            Nov 15 '18 at 18:47











          • That would be better as it would increment the number on a diferent thread. The problem remains of waiting for the ui to update when you send the next number but if you send the increments with long enough delays you might be able to pull it off.

            – Itamar Kerbel
            Nov 15 '18 at 20:27











          • If you found my answer as helpful please mark it as answered. If not what else is missing?

            – Itamar Kerbel
            Nov 17 '18 at 8:42












          • Although your answer was helpful in figuring out why my code is acting the way it is, it didn't provide suggestions to fixing the issue. I was waiting until I found out how to fix it, then I was going to put an answer forth.

            – Matthew Strom
            Nov 18 '18 at 17:14











          • Actually, since the issue to this problem has now revealed more specific issues with a smaller scope, I will go with your answer for the sake of this question being fairly broad. I have been deciding to go with a different language entirely with this project anyways to make issues like these much more simple to solve. I do appreciate the explanations and help!

            – Matthew Strom
            Nov 18 '18 at 21:33

















          • Thanks for the feed back on this iteration. I agree that this implementation doesn't make sense, and your explanation corresponds correctly with my inclinations. That being said, what are your thoughts on this if the loop was placed inside the run() method of the AutoUpdateTask as my comment in that method alluded to?

            – Matthew Strom
            Nov 15 '18 at 18:47











          • That would be better as it would increment the number on a diferent thread. The problem remains of waiting for the ui to update when you send the next number but if you send the increments with long enough delays you might be able to pull it off.

            – Itamar Kerbel
            Nov 15 '18 at 20:27











          • If you found my answer as helpful please mark it as answered. If not what else is missing?

            – Itamar Kerbel
            Nov 17 '18 at 8:42












          • Although your answer was helpful in figuring out why my code is acting the way it is, it didn't provide suggestions to fixing the issue. I was waiting until I found out how to fix it, then I was going to put an answer forth.

            – Matthew Strom
            Nov 18 '18 at 17:14











          • Actually, since the issue to this problem has now revealed more specific issues with a smaller scope, I will go with your answer for the sake of this question being fairly broad. I have been deciding to go with a different language entirely with this project anyways to make issues like these much more simple to solve. I do appreciate the explanations and help!

            – Matthew Strom
            Nov 18 '18 at 21:33
















          Thanks for the feed back on this iteration. I agree that this implementation doesn't make sense, and your explanation corresponds correctly with my inclinations. That being said, what are your thoughts on this if the loop was placed inside the run() method of the AutoUpdateTask as my comment in that method alluded to?

          – Matthew Strom
          Nov 15 '18 at 18:47





          Thanks for the feed back on this iteration. I agree that this implementation doesn't make sense, and your explanation corresponds correctly with my inclinations. That being said, what are your thoughts on this if the loop was placed inside the run() method of the AutoUpdateTask as my comment in that method alluded to?

          – Matthew Strom
          Nov 15 '18 at 18:47













          That would be better as it would increment the number on a diferent thread. The problem remains of waiting for the ui to update when you send the next number but if you send the increments with long enough delays you might be able to pull it off.

          – Itamar Kerbel
          Nov 15 '18 at 20:27





          That would be better as it would increment the number on a diferent thread. The problem remains of waiting for the ui to update when you send the next number but if you send the increments with long enough delays you might be able to pull it off.

          – Itamar Kerbel
          Nov 15 '18 at 20:27













          If you found my answer as helpful please mark it as answered. If not what else is missing?

          – Itamar Kerbel
          Nov 17 '18 at 8:42






          If you found my answer as helpful please mark it as answered. If not what else is missing?

          – Itamar Kerbel
          Nov 17 '18 at 8:42














          Although your answer was helpful in figuring out why my code is acting the way it is, it didn't provide suggestions to fixing the issue. I was waiting until I found out how to fix it, then I was going to put an answer forth.

          – Matthew Strom
          Nov 18 '18 at 17:14





          Although your answer was helpful in figuring out why my code is acting the way it is, it didn't provide suggestions to fixing the issue. I was waiting until I found out how to fix it, then I was going to put an answer forth.

          – Matthew Strom
          Nov 18 '18 at 17:14













          Actually, since the issue to this problem has now revealed more specific issues with a smaller scope, I will go with your answer for the sake of this question being fairly broad. I have been deciding to go with a different language entirely with this project anyways to make issues like these much more simple to solve. I do appreciate the explanations and help!

          – Matthew Strom
          Nov 18 '18 at 21:33





          Actually, since the issue to this problem has now revealed more specific issues with a smaller scope, I will go with your answer for the sake of this question being fairly broad. I have been deciding to go with a different language entirely with this project anyways to make issues like these much more simple to solve. I do appreciate the explanations and help!

          – Matthew Strom
          Nov 18 '18 at 21:33



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53312609%2fimplementing-handler-interaction-with-the-ui-thread-on-a-continuous-loop%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Use pre created SQLite database for Android project in kotlin

          Darth Vader #20

          Ondo