Reputation: 1311
I have this simple function that registers the user on the Google Messaging service
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regId = gcm.register(Config.GOOGLE_PROJECT_ID);
Log.d("RegisterActivity", "registerInBackground - regId: "
+ regId);
msg = "Device registered, registration ID=" + regId;
storeRegistrationId(context, regId);
appUtil.shareRegIdWithAppServer(context, regId);
Log.d("RegisterActivity", "should be rig: " + msg);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
Log.d("RegisterActivity", "Error: " + msg);
}
Log.d("RegisterActivity", "AsyncTask completed: " + msg);
return msg;
}
@Override
protected void onPostExecute(String msg) {
Toast.makeText(getApplicationContext(),
"Registered with GCM Server." + msg, Toast.LENGTH_LONG)
.show();
}
}.execute(null, null, null);
}
Edite
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getSharedPreferences(
MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(REG_ID, regId);
editor.putInt(APP_VERSION, appVersion);
editor.commit();
}
End edite
When I execute it, it successfully registers on the GCM server and the user gets his registration ID successfully. BUT I get the following exception that stops and closes the application.
E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.sparr_000.newgcm, PID: 25967
java.lang.RuntimeException: An error occured while executing doInBackground()
I am new to android. I have read the documentation, watched related videos and searched online but I found no solution. What is wrong with my code and How can I get rid off this exception and continue running my app in peace?
Upvotes: 0
Views: 501
Reputation: 250
There could be many places where the error might be as you have code running after the registration. Try to break your code into small pieces or use a debugger to know which step fails. Like comment out storeRegistrationId(context, regId); appUtil.shareRegIdWithAppServer(context, regId); and try running if it works then add the next or debug the rest of the functions to know which one fails. Instead of sending the context, get the context of you application from the current class.
Upvotes: 1