0

Before I begin, I want to make clear that I have read previous answers to similar topics (mainly this one) and the answer given even in the comments didn't work for me (adding the intent != null before intent.getAction() didn't work).

I'm trying to make a foreground service for a Mayan Horoscope. The purpose of the service is to read the horoscope symbols and a prediction from an SQLite Database and whenever it recieves a text message with the following: "MAYA dd/MM/yyyy" (the DOB), the service would obtain the info and send a text message automatically. I have gotten that to work as a background service without error, but I want to give it a notification so the user can see if the service is running or not.

I have followed other tutorials (tutorial 1 and tutorial 2) to make the foreground service and it works fine without error.

My problem now is that whenever I start the service, stop the service and finally clear the ram (killing the app) I get the Nullpointer Exception all the time on my service's Line 57 (no matter what code I have it's always line 57). On my phone it gives me the message "Unfortunately HoroscopoMaya has stopped working." TWICE!

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>

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

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:name=".ServicioAstralMaya"
             android:exported="false" />
</application>
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />

MainActivity.java:

public void startService( View view )
{
    if( bRunning == false )
    {
        Intent intent = new Intent( MainActivity.this, ServicioAstralMaya.class );
        intent.setAction( Constants.ACTION.START_FOREGROUND_ACTION );
        startService( intent );
        txtVStatServ.setText( "INVOCADOS " );
        bRunning = true;
    }
}//END startService( View )

public void stopService( View view )
{
    if( bRunning == true )
    {
        Intent intent = new Intent( MainActivity.this, ServicioAstralMaya.class );
        intent.setAction( Constants.ACTION.STOP_FOREGROUND_ACTION );
        startService( intent );
        txtVStatServ.setText( "DESCANSANDO " );
        bRunning = false;
    }
}//END stopService( View )

ServicioAstralMaya.java (service):

@Override
public int onStartCommand( Intent intent, int flags, int startID )
{
    if( intent != null && intent.getAction().equals( Constants.ACTION.START_FOREGROUND_ACTION
    ) )
    {
        Log.i( TAG, "Servicio iniciado!" );
        isRunning = true;
        startForeground( Constants.NOTIFICATION_ID.SERVICE_ID, getCompatNotification() );
    }else if( intent != null && intent.getAction().equals( Constants.ACTION.STOP_FOREGROUND_ACTION ) )
    {

        Log.i( TAG, "Servicio detenido!" );
        isRunning = false;
        stopForeground( true );
        stopSelf();
    }
    return START_STICKY;
}

private Notification getCompatNotification()
{
    NotificationCompat.Builder builder = new NotificationCompat.Builder( this );
    builder.setSmallIcon( R.drawable.homonculus_32 )
        .setContentTitle( "Horoscopos Maya" )
        .setTicker( "Astros Conectados" )
        .setWhen( System.currentTimeMillis() );
    Intent startIntent = new Intent( this, MainActivity.class );
    PendingIntent contentIntent = PendingIntent.getActivity( this, 0, startIntent,
        0 );
    builder.setContentIntent( contentIntent );
    Notification notification = builder.build();

    return notification;
}//END Notification getCompatNotification()

@Override
public void onDestroy()
{
    super.onDestroy();
    isRunning = false;
}

Constants.java

public interface ACTION
{
    public static final String START_FOREGROUND_ACTION = "edu.ito.jmhg" +
        ".horoscopomaya.action.START_FOREGROUND";
    public static final String STOP_FOREGROUND_ACTION = "edu.ito.jmhg" +
        ".horoscopomaya.action.STOP_FOREGROUND";
}

public interface NOTIFICATION_ID
{
    public static final int SERVICE_ID = 1;
}

Line 57 is this: Log.i( TAG, "Servicio iniciado!" );

The isRunning and bRunning is to check if the service is running so as to show the status in the MainActivity:

bRunning = isServiceRunning( ServicioAstralMaya.class );

private boolean isServiceRunning( Class<?> serviceClass )
{
    ActivityManager manager = (ActivityManager)getSystemService( Context.ACTIVITY_SERVICE );
    for( ActivityManager.RunningServiceInfo service : manager.getRunningServices( Integer
        .MAX_VALUE ) )
    {
        if( serviceClass.getName().equals( service.service.getClassName() ) ) {
            return true;
        }
    }
    return false;
}//END boolean isServiceRunning( Class<?> )

and in the service: public static boolean isRunning;

I have even tried calling the stopService and doing the stopForeground(true); and stopSelf(); in the onDestroy() method but still to no avail. And the error is STILL line 57 of my service class.

Logcat:

FATAL EXCEPTION: main
Process: edu.ito.jmhg.horoscopomaya, PID: 21642
java.lang.RuntimeException: Unable to start service  edu.ito.jmhg.horoscopomaya.ServicioAstralMaya@426d11c8 with null: java.lang.NullPointerException
...
Caused by: java.lang.NullPointerException at edu.ito.jmhg.horoscopomaya.ServicioAstralMaya.onStartCommand(ServicioAstralMaya.java:57)

I am running Android KitKat 4.4.4 (API 19) with Android Studio 2 using a rooted Samsung Grand Prime.

EDIT

I don't know if this is somewhat relevant, but I did notice something about Android Studio. No matter what changes I make, when I run the app I get notified that "No changes to deploy"

Event Log:

19:32:47 Executing tasks: [:app:assembleDebug]
19:33:50 Gradle build finished in 1m 3s 59ms
19:33:51 No changes to deploy

I've changed the code of my service and the line error is still 57, which is now ) ) right after if( intent.getAction().equals( Constants.ACTION.START_FOREGROUND_ACTION

ServicioAstralMaya.java (service):

@Override
public int onStartCommand( Intent intent, int flags, int startID )
{
    if( intent != null && intent.getAction() != null )
    {
        if( intent.getAction().equals( Constants.ACTION.START_FOREGROUND_ACTION
        ) )
        {
            Log.i( TAG, "Servicio iniciado!" );
            isRunning = true;
            startForeground( Constants.NOTIFICATION_ID.SERVICE_ID, getCompatNotification() );
        }else if( intent.getAction().equals( Constants.ACTION.STOP_FOREGROUND_ACTION ) )
        {
            Log.i( TAG, "Servicio detenido!" );
            isRunning = false;
            stopForeground( true );
            stopSelf();
        }
    }
    return START_STICKY;
}

Also, since I've changed to Android 2 my gradle updated and I had this weird error where I had to change the buildToolsVersion in build.gradle from buildToolsVersion "24.0 rc2" to buildToolsVersion "23.0.2"

build.gradle:

apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "edu.ito.jmhg.horoscopomaya"
    minSdkVersion 19
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
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'
}
Community
  • 1
  • 1
jmhg92
  • 121
  • 2
  • 14

2 Answers2

1

The problem was Android Studio itself!!

Like I said in the edit, Android Studio gave me the "No changes to deploy", which was very strange, so I searched about it and found this solution

Just go to "File -> Settings -> Build, Execution, Deployement -> Instant Run" and just disable it. With this Android Studio builds from scratch each time but it's better than not building it right.

I kept the if condition mentioned by @Francesc just to be on the safe side and my app doesn't give me the NullPointerException anymore.

Community
  • 1
  • 1
jmhg92
  • 121
  • 2
  • 14
0

jmhg92 solution did solved my NullPointerExceptions with Services, Models and Fragments when instant run was Active

Just go to "File -> Settings -> Build, Execution, Deployement -> Instant Run"

However, if you want to keep Instant Run you can just UnCheck "Restart Activity on Code Changes"

Preferences > Build, Execution, Deployment > Instant Run > Uncheck "Restart Activity on Code Changes"

So far I have been able to use Instant Run and haven't received any Exceptions.

Hope this solution is useful to someone.

Community
  • 1
  • 1
Carlitos
  • 343
  • 5
  • 7