Reputation:
I have following code to run a function in another thread:
Button buttonb = (Button) this.findViewById(R.id.buttonb);
buttonb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
…
progressBar.setVisibility(View.VISIBLE);
Thread thread = new Thread() {
@Override
public void run() {
matrixOperation(sourcePhoto);
}
};
thread.start();
progressBar.setVisibility(View.INVISIBLE);
…
}
});
But on running i am getting this error:
Can't create handler inside thread that has not called Looper.prepare()
I searched and found that one reason for this error is “You cannot execute an AsyncTask from a background thread. See the "Threading Rules" section of” But this is not background thread I am calling it from my Main Activity.
Please tell me how I can fix this.
Upvotes: 1
Views: 433
Reputation: 14185
The Handler
class uses Looper
s to perform its scheduling, and threads that have just been created does not have an associated looper – hence the error.
As you have not provided the handler creation code, I'm assuming you want to call code on the main thread. In this case, create the Handler
as follows:
Handler handler = new Handler(Looper.getMainLooper());
Anything scheduled to run on that Handler
will execute on the main Looper
, which is running on the main thread.
Upvotes: 1