I'm using an ORM for Android called Sugar to persist my models on the database and I'm using it inside my AsyncTask.
Here is its declaration:
public class LoginTask extends AsyncTask<Object, Integer, String> {
private Context context;
private ProgressDialog progressDialog;
public LoginTask(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context) {
{
setMessage("Authenticating...");
setTitle("Login");
setCancelable(false);
setIndeterminate(true);
show();
}
};
}
@Override
protected String doInBackground(Object... params) {
String email = (String) params[0];
String password = (String) params[1];
try {
User user = LoginWebService.loginUser(email, password,
context);
user.save();
} catch (CommunicationException e) {
e.printStackTrace();
return e.getMessage();
}
return null;
}
@Override
protected void onPostExecute(final String result) {
progressDialog.dismiss();
}
}
The line user.save() above, that saves the user model in the db, is the one that causes the exception. The strange thing is that if I declare the task above as an inner class from the activity, it works fine, but if I declare the task on a separate file, it throws this exception:
E/AndroidRuntime(17172): at com.app.task.LoginTask.doInBackground(LoginTask.java:47)
E/AndroidRuntime(17172): at com.app.task.LoginTask.doInBackground(LoginTask.java:1)
E/AndroidRuntime(17172): at android.os.AsyncTask$2.call(AsyncTask.java:264)
E/AndroidRuntime(17172): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
E/AndroidRuntime(17172): ... 5 more
E/AndroidRuntime(17172): Caused by: java.lang.RuntimeException: Cant create handler inside thread that has not called Looper.prepare()
I can't see what makes the difference as I can't see any sense on this.