I created a PhoneGap plugin for android which sends an email.
public PluginResult execute(String action, JSONArray args, String callbackId) {
try {
// i want to call a function from other class so i did the
// below, but it is throwing the above said error...
WebActivity wb = new WebActivity();
wb.createExternalStoragePrivateFile(img);
//sending email code here
}
}
In above code while accessing the function of another class , i am getting the error:
cannot create
handlerinside thread that has not calledLooper.prepare()error.
What is the right approach to call the function?
If
WebActivityis actually an activity (i.e. extendsActivity), you have several things wrong.You must not create
Activityobjects yourself. Well, you can, but than you have to assign a context to them (which I’m not sure even possible without using internals), and manage Activity lifecycle.You can’t just create an Activity object and call a function. This function may have lifecycle and context dependencies (i.e. you may have to “resume” the activity).
The error you see is the result of that each
Activityexpects to be called from UI-thread ( or at least fromLooperthread). The function you call most like usesHandlerin some way, either directly or indirectly. And when this function creates aHandlerand then posts a message orRunnableyou’ll get the error you see.But again, this is because
Activityis not meant to be used the way you’ve used. You cannot just create activity and start calling it’s method. You basically violate it’s state model. SoActivityis not even supposed to work.As a solution, if you have control over
WebActivity, movecreateExternalStoragePrivateFile()function into some independent class or make it static (if possible), or both. You most likely will need to fix a thing or two there, to make it work. But at least you’ll be able to call the function from other places.