Skip to content Skip to sidebar Skip to footer

Android While Loop Alternative

This is my first Android application and I am finding troubles with while loop, I am trying to use a while loop on my Android application but the application freezes. What I'm try

Solution 1:

I resolved the problem using a "Handler" that query the Feature Layer every 5 seconds, this stops the main thread from generating application not responding error:

   Handler m_handler=new Handler();
    Runnable m_runnable;
    m_runnable = new Runnable(){
   publicvoidrun() {

  //query code here
m_handler.postDelayed(m_runnable, 5000);

    }
   };
  m_handler.postDelayed(m_runnable, 0);

Solution 2:

running while loop codes on the main thread freezes the UI, and makes all other processes pause making your app unresponsive use

Threads..

also note that the while loop you are running is running on a default Thread termed as the ui thread so in short run while loops on separate threads.. eg..

newThread(newRunnable() {

    @Overridepublicvoidrun() {
    // Your hard while loop here//get whatever you want and update your ui with ui communication methods.
    }
).start();

for ui communicating methods

View.post(newRunnable() {

    @Overridepublicvoidrun() {
    // TODO Auto-generated method stubToast.makeText(getActivity(), "updated ui", Toast.LENGTH_LONG).show();
    }
});    

the view could be any views you are updating.. also like @TehCoder said you could use asynctask but asynctask is not meant for long workaflow work there are 3 of them but i can't recall the last one

Solution 3:

Maybe you should use an AsyncTask? I'm not quite sure what your problem is tho.

Solution 4:

Loop is not a problem in android (or any language).

There are two scenario might be reason for your freezing,

  1. If you run network call in api, android throw error and crashes. You have to do network related calls in Aysnc Task ot threading

  2. Use try throw catch and exception cases to avoid app crashing and better coding skill.

Post a Comment for "Android While Loop Alternative"