1

I have used timer to call certain function after specific time period.

I have done that with following piece of code:

Timer myTimer = new Timer();
        myTimer.schedule(new TimerTask() {          
            public void run() {
                Toast.makeText(getApplicationContext(),"Insidedsfdsf Click  " , Toast.LENGTH_LONG).show();
               UpdateTask();
            }
    }, 1, 1000);




public void UpdateTask() {
            // TODO Auto-generated method stub
            try
            {


                Toast.makeText(getApplicationContext(),"update  " , Toast.LENGTH_LONG).show();



            Intent intent = getIntent();

            String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
            String id = intent.getStringExtra(MainActivity.EXTRA_ID);
            String[] lst = null;
            String[] lstNew = null;
            ListView lm=(ListView)findViewById(R.id.listView1);
            TextView tv = (TextView)findViewById(R.id.textView1);
            TextView tvNewMessages = (TextView)findViewById(R.id.tvNewMessages);

            tv.setText("Welcome " + message);



            CallSoap cs=new CallSoap();



            lst=cs.GetMessage(id);

            lstNew=cs.GetNewMessage(id);



            final int numOfMessages=lstNew.length;  

            //Toast.makeText(getApplicationContext(),"Call  "+lstNew.length , Toast.LENGTH_LONG).show();





            tvNewMessages.setText("You have "+ numOfMessages +" new messages");

            ArrayAdapter<String> adpt = new ArrayAdapter<String>(Messages.this, android.R.layout.simple_list_item_1,lst){
                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    View v = super.getView(position, convertView, parent);

                    if(position<numOfMessages){
                        v.setBackgroundColor(Color.RED);
                        }
                    else
                    {
                    v.setBackgroundColor(Color.WHITE);
                    }
                    return v;
                }
            };

            lm.setAdapter(adpt);

            }
            catch(Exception ex)
            {
                ex.printStackTrace();
                //Toast.makeText(getApplicationContext(),"Call  "+ex.getMessage() , Toast.LENGTH_LONG).show();
            }
        }

But i am finding that my UpdateTask function is not getting called and in logcat its showing me error:

can't create handler inside thread

Please help me.

C Sharper
  • 8,284
  • 26
  • 88
  • 151
  • you can't update UI from TimerTask. You should use runonUiThread. search for relevant answers – Andro Selva Aug 27 '13 at 11:45
  • 1
    Please for the sake of everyone don't poll for new messages. Instead let Android tell you when a new message arrives, in case you are looking for new sms. http://stackoverflow.com/questions/4117701/android-sms-broadcast-receiver Or if this is some other custom message then use GCM. – M-Wajeeh Aug 27 '13 at 11:53

3 Answers3

2

Timer task runs on a different thread. Ui should be updated on the ui thread.

So you can use a Handler. or Use runOnUiThread

Handler m_handler;
Runnable m_handlerTask ;  
m_handler = new Handler();   
m_handlerTask = new Runnable()
{
  @Override 
  public void run() { 

    // do something  
    m_handler.postDelayed(m_handlerTask, 1000);    

  }
  };
 m_handlerTask.run();

Also check this as a side note

Android Thread for a timer

Edit:

You are initializing your views everytime. Move it to onCreate and declare them as class members

  ListView lm=(ListView)findViewById(R.id.listView1);
  TextView tv = (TextView)findViewById(R.id.textView1);
  TextView tvNewMessages = (TextView)findViewById(R.id.tvNewMessages);
Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • but it keeps waiting whole application for that particular period – C Sharper Aug 27 '13 at 11:48
  • @NavatKayAahe i don't understand your requirement. what is that you are doing? – Raghunandan Aug 27 '13 at 11:49
  • i am updating messages from database on every 15-20seconds, so when i used handler, it was doing so, but the problem was that, it was not allowing to make me logout (logout i took textview, and on click of that i had written code to make user logout)...thats why i used timer.. – C Sharper Aug 27 '13 at 11:52
  • this code gets called only once, i want to repeatedly call it – C Sharper Aug 27 '13 at 12:02
  • @NavatKayAahe no it repeats. also if you need to update lsitview update the underlying data that populates the listview and call `notifyDataSetChanged`. your design is not good – Raghunandan Aug 27 '13 at 12:02
  • 1
    yeah, its running, fine, thanx – C Sharper Aug 27 '13 at 12:04
1

you have to use this :

Handler h = new Handler();
Runnable r = new Runnable(){

 @Override 
  public void run() { 

  //perform action here. 
   h.postDelayed(m_handlerTask, 1000);    

}
};
h.run();
Piyush
  • 18,895
  • 5
  • 32
  • 63
1

or you can try CountDownTime

 new CountDownTimer(x, x) {

     public void onTick(long millisUntilFinished) {
            Toast.makeText(getApplicationContext(),"Insidedsfdsf Click  " , Toast.LENGTH_LONG).show();
     }

     public void onFinish() {
           UpdateTask();
     }
  }.start();
Ahmed Ekri
  • 4,601
  • 3
  • 23
  • 42