Reputation: 1391
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
handler
inside thread that has not calledLooper.prepare()
error.
What is the right approach to call the function?
Upvotes: 0
Views: 918
Reputation: 74780
If WebActivity
is actually an activity (i.e. extends Activity
), you have several things wrong.
You must not create Activity
objects 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 Activity
expects to be called from UI-thread ( or at least from Looper
thread). The function you call most like uses Handler
in some way, either directly or indirectly. And when this function creates a Handler
and then posts a message or Runnable
you'll get the error you see.
But again, this is because Activity
is 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. So Activity
is not even supposed to work.
As a solution, if you have control over WebActivity
, move createExternalStoragePrivateFile()
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.
Upvotes: 1