g33k g33k - 1 month ago 12
Android Question

object not locked by thread before wait

In my android app i am trying to call a method after a specific time interval. Eg. After every 5 secs

So i did something like this:

// I am writing this code inside onCreate
letsChange(); //method name
try{
Wait(1000);
}catch(Exception e){
e.printstackstrace();
}


But while running it its showing me this error
object not locked by thread before wait()


What to do please help me.
Thank You So Much

Answer

Adding synchronized to onCreate() will acquire the lock (the current instance of the Activity) and let you call wait() inside, but this is definitely not want you want to do as it will block the main/UI thread and cause your app to be non-responsive.

What you probably want instead is the following:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        //code you want to run after the delay
    }
};
, 1000);

This will cause the code inside run() to be run after the desired delay (1000ms)

Comments