Hello guys
am totally new to java development but I red some tutorial on web on how to create different application on Android Studio.
I've created simple webview application with navigation drawer and everything work perfect, when I tried to add Parse.com SDK to use notification service my program crashes whenever I send a push notification.
jaaja.jpg
if I opened the application and send push it will Recieve it no crash in app, the problem occurs only when application is closed.
My Android Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    package="com.iqpslb.osamasw">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    <permission android:protectionLevel="signature"
        android:name="com.iqpslb.osamasw.permission.C2D_MESSAGE" />
    <uses-permission android:name="com.iqpslb.osamasw.permission.C2D_MESSAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".SplashScreen"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".add"
            android:label="@string/title_activity_add"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".Our_Partner"
            android:label="@string/title_activity_our__partner"
            android:parentActivityName=".MainActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.iqpslb.osamasw.MainActivity" />
        </activity>
        <activity
            android:name=".About_Leaderboard"
            android:label="@string/title_activity_about__leaderboard"
            android:parentActivityName=".MainActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.iqpslb.osamasw.MainActivity" />
        </activity>

        <service android:name="com.parse.PushService" />
        <receiver
            android:name="com.iqpslb.osamasw.Receiver"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.parse.push.intent.RECEIVE" />
                <action android:name="com.parse.push.intent.DELETE" />
                <action android:name="com.parse.push.intent.OPEN" />
            </intent-filter>
        </receiver>
        <receiver android:name="com.parse.GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <category android:name="com.iqpslb.osamasw" />
            </intent-filter>
        </receiver>
        <meta-data android:name="com.parse.push.notification_icon"
            android:resource="@drawable/ic_stat_name"/>
    </application>

</manifest>

Reciever.java

package com.iqpslb.osamasw;

import android.content.Context;
import android.content.Intent;

import com.parse.ParsePushBroadcastReceiver;

public class Receiver extends ParsePushBroadcastReceiver {

    @Override
    public void onPushOpen(Context context, Intent intent) {
        //Log.e("Push", "Clicked");
        Intent i = new Intent(context, MainActivity.class);
        i.putExtras(intent.getExtras());
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}

Main Activity.java

package com.iqpslb.osamasw;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.parse.Parse;
import com.parse.ParseInstallation;


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private WebView mWebView;
    ProgressBar progressBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Parse.initialize(getApplicationContext(), getString(R.string.parse_app_id), getString(R.string.parse_client_key));
        ParseInstallation.getCurrentInstallation().saveInBackground();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ConnectivityManager cManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
        NetworkInfo nInfo = cManager.getActiveNetworkInfo();
        if (nInfo != null && nInfo.isConnected()){
            Toast.makeText(getApplicationContext(), "Welcome", Toast.LENGTH_LONG).show();
            mWebView = (WebView) findViewById(R.id.activity_main_webview);
            progressBar = (ProgressBar) findViewById(R.id.progressBar1);
            WebSettings webSettings = mWebView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            mWebView.loadUrl("");
            mWebView.setWebViewClient(new HelloWebViewClient());
        }else{
            Toast.makeText(getApplicationContext(),"No Internet Connection", Toast.LENGTH_LONG).show();
        }



        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }
    private class HelloWebViewClient extends WebViewClient {


        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url)
        {
            webView.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {

            super.onPageFinished(view, url);

            progressBar.setVisibility(view.GONE);
        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    { //if back key is pressed
        if((keyCode == KeyEvent.KEYCODE_BACK)&& mWebView.canGoBack())
        {
            mWebView.goBack();
            return true;

        }

        return super.onKeyDown(keyCode, event);

    }

    @Override
    public void onBackPressed() {

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                MainActivity.this);

        // set title
        alertDialogBuilder.setTitle("Exit");

        // set dialog message
        alertDialogBuilder
                .setMessage("Do you really want to exit?")
                .setCancelable(false)
                .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // if this button is clicked, close
                        // current activity
                        MainActivity.this.finish();
                    }
                })
                .setNegativeButton("No",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                    }
                });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_exit) {
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    MainActivity.this);

            // set title
            alertDialogBuilder.setTitle("Exit");

            // set dialog message
            alertDialogBuilder
                    .setMessage("Do you really want to exit?")
                    .setCancelable(false)
                    .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, close
                            // current activity
                            MainActivity.this.finish();
                        }
                    })
                    .setNegativeButton("No",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, just close
                            // the dialog box and do nothing
                            dialog.cancel();
                        }
                    });

            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_home) {
            Intent intent = new Intent(this,MainActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_add) {
            Intent intent = new Intent(this,add.class);
            startActivity(intent);
        } else if (id == R.id.nav_partner) {
            Intent intent = new Intent(this,Our_Partner.class);
            startActivity(intent);

        } else if (id == R.id.nav_about) {
            Intent intent = new Intent(this,About_Leaderboard.class);
            startActivity(intent);
        } else if (id == R.id.nav_exit) {
        finish();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.iqpslb.osamasw"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.2"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.parse.bolts:bolts-android:1.3.0'
    compile 'com.parse:parse-android:1.12.0'
}

Dani AI

Generated

Short summary and root cause

The crash log you posted shows a NullPointerException inside com.parse.PushService because Parse's internal plugin context was null — in plain terms, the Parse SDK had not been initialized when the push service started. That happens when Parse.initialize(...) runs in an Activity (for example MainActivity.onCreate): a push can arrive while the app is closed and the OS may start the PushService before any Activity runs. ’s request for the stack trace was exactly the right diagnostic step. (stackoverflow.com)

What to do (robust fix)

Move Parse initialization into a custom Application subclass so it always runs before any service or receiver. Create a small class that extends android.app.Application, call Parse.initialize(...) in its onCreate(), and register that class in your AndroidManifest.xml with the application android:name attribute. Example (modern Parse SDK style):

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Parse.initialize(new Parse.Configuration.Builder(this)
            .applicationId(getString(R.string.parse_app_id))
            .clientKey(getString(R.string.parse_client_key)) // if needed
            .server(getString(R.string.parse_server_url))   // for Parse Server
            .build()
        );
    }
}

Then register the class in the manifest with android:name=".MyApp". This guarantees Parse is ready before PushService or GCM/FCM receivers run. (docs.parseplatform.org)

Extra cautions and testing

Make sure the class named by android:name actually extends Application — pointing android:name at a BroadcastReceiver or other component is not correct. Test pushes with the app closed and watch logcat for the “Parse push service cannot start” message if you see problems. Also note Android 8+ (Oreo) imposes background-service limits that can affect older push implementations; update the SDK or migrate to a Parse Server + FCM path if you support modern Android releases. Finally, Parse.com’s hosted service was retired in 2017, so consider Parse Server or other hosted push providers for long-term support. (developer.android.com)

Acknowledgement: ’s post shows the crash and the immediate fix (adding an android:name entry). The best-practice approach is the Application-based initialization above so the behavior is explicit and future-proof.

Recommended Answers

All 4 Replies

if you are totally new to Java, maybe you should start with getting acquainted with the language.
It's a bit like learning to swim: if you don't know how, jumping in the deep end when noone else is around, might get you in trouble you can't get out of.

When it crashed, did you get a traceback of the crash? Java (and Dalvik) will provide a nice stack trace to show you where the problem actually occurred. Since you say it only happens when closing the application, then I suspect you have munged something in your code that on exit the system cleanup code can't deal with it. I'm not going to analyze your 350+ lines of provided code to tell you why...

this what I got from sending push notification while app is closed.

01-23 10:24:04.406 27976-27976/? E/Zygote: MountEmulatedStorage()
01-23 10:24:04.406 27976-27976/? I/libpersona: KNOX_SDCARD checking this for 10285
01-23 10:24:04.406 27976-27976/? E/Zygote: v2
01-23 10:24:04.406 27976-27976/? I/libpersona: KNOX_SDCARD not a persona
01-23 10:24:04.411 27976-27976/? I/SELinux: Function: selinux_compare_spd_ram, SPD-policy is existed. and_ver=SEPF_GT-I9500_5.0.1 ver=38
01-23 10:24:04.421 27976-27976/? I/SELinux: Function: selinux_compare_spd_ram , priority [1] , priority version is VE=SEPF_GT-I9500_5.0.1_0038
01-23 10:24:04.421 27976-27976/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
01-23 10:24:04.426 27976-27976/? I/art: Late-enabling -Xcheck:jni
01-23 10:24:04.501 27976-27976/com.iqpslb.osamasw D/ResourcesManager: creating new AssetManager and set to /data/app/com.iqpslb.osamasw-1/base.apk
01-23 10:24:04.606 27976-27976/com.iqpslb.osamasw D/AndroidRuntime: Shutting down VM
01-23 10:24:04.616 27976-27976/com.iqpslb.osamasw E/AndroidRuntime: FATAL EXCEPTION: main
                                                                    Process: com.iqpslb.osamasw, PID: 27976
                                                                    java.lang.RuntimeException: Unable to create service com.parse.PushService: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context com.parse.ParsePlugins$Android.applicationContext()' on a null object reference
                                                                        at android.app.ActivityThread.handleCreateService(ActivityThread.java:3158)
                                                                        at android.app.ActivityThread.access$1900(ActivityThread.java:177)
                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1531)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                        at android.os.Looper.loop(Looper.java:145)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5942)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at java.lang.reflect.Method.invoke(Method.java:372)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)
                                                                     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context com.parse.ParsePlugins$Android.applicationContext()' on a null object reference
                                                                        at com.parse.PushService.onCreate(PushService.java:230)
                                                                        at android.app.ActivityThread.handleCreateService(ActivityThread.java:3148)
                                                                        at android.app.ActivityThread.access$1900(ActivityThread.java:177) 
                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1531) 
                                                                        at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                        at android.os.Looper.loop(Looper.java:145) 
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5942) 
                                                                        at java.lang.reflect.Method.invoke(Native Method) 
                                                                        at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389) 
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184) 

thanks to this tutorial I knew what I MISSED
https://www.youtube.com/watch?v=8cKy1yT8ZKc
my code is fine just one line solve my problem
android:name = ".Reciever"
add this to application tag in Android Manifest and no more crashed :P
problem solved but no one solve it here .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.