The_Martian
The_Martian

Reputation: 3767

ResultReceiver.send throws nullpointerexception

I have searched for an answer but I couldn't find one. I am reverse geocoding latitude and latitude in IntentService then when I try to ResultReceiver.send it throws nullpointerexception. I debugged the arguments and they contain the address and the result code just like they are supposed to. I searched on any uninitialized objects but I couldn't fine one. Can anyone give me a clue on what's going on?

This is the method that reversegeocodes the lat and lon.

@Override
    public void onHandleIntent(Intent intent) {
        // TODO Auto-generated method stub
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        String errorMessage = "";

        // Get the location passed to this service through an extra.
        Location location = intent.getParcelableExtra(
                Constants.LOCATION_DATA_EXTRA);

        List<Address> addresses = null;

        try {
            addresses = geocoder.getFromLocation(
                    location.getLatitude(),
                    location.getLongitude(),
                    // In this sample, get just one addresse.
                    1);
        } catch (IOException ioException) {
            // Catch network or other I/O problems.
            errorMessage = getString(R.string.service_not_available);
            Log.e(TAG, errorMessage, ioException);
        } catch (IllegalArgumentException illegalArgumentException) {
            // Catch invalid latitude or longitude values.
            errorMessage = getString(R.string.invalid_lat_lon);
            Log.e(TAG, errorMessage + ". " +
                    "Latitude = " + location.getLatitude() +
                    ", Longitude = " +
                    location.getLongitude(), illegalArgumentException);
        }

        // Handle case where no address was found.
        if (addresses == null || addresses.size()  == 0) {
            if (errorMessage.isEmpty()) {
                errorMessage = getString(R.string.no_address_found);
                Log.e(TAG, errorMessage);
            }
            deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
        } else if (!"".equals(addresses) || null != addresses || addresses.size() > 0) {
            Address address = addresses.get(0);
            ArrayList<String> addressFragments = new ArrayList<String>();

            // Fetch the address lines using getAddressLine,
            // join them, and send them to the thread.
            for(int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                addressFragments.add(address.getAddressLine(i));
            }
            //Log.i(TAG, getString(R.string.no_address_found));
            if (!TextUtils.isEmpty(String.valueOf(addressFragments)))
            //this is the line number 95 mentioned in the logcat
            deliverResultToReceiver(Constants.SUCCESS_RESULT, TextUtils.join(System.getProperty("line.separator"), addressFragments));
        }
        //GetAddressString(addresses);
        //return st;
    }

private void deliverResultToReceiver(int resultCode, String message) {
        Bundle bundle = new Bundle();
        try {
            if (message != null || !"".equals(message))
        bundle.putString(Constants.RESULT_DATA_KEY, message);
               //this is line number 113 mentioned in the logcat
                mReceiver.send(resultCode, bundle);
            } catch (NullPointerException npe) {
                // TODO Auto-generated catch block
                npe.printStackTrace();
            }
    }

Here is the logcat

02-26 16:03:58.601: I/SELinux(7548): Function: selinux_android_load_priority [0], There is no sepolicy file.
02-26 16:03:58.601: I/SELinux(7548):  
02-26 16:03:58.601: I/SELinux(7548): Function: selinux_android_load_priority [1], There is no sepolicy version file.
02-26 16:03:58.601: I/SELinux(7548):  
02-26 16:03:58.601: I/SELinux(7548): Function: selinux_android_load_priority , priority version is VE=SEPF_SM-G800H_4.4.2_0018
02-26 16:03:58.601: I/SELinux(7548):  
02-26 16:03:58.601: I/SELinux(7548):  
02-26 16:03:58.601: I/SELinux(7548): selinux_android_seapp_context_reload: seapp_contexts file is loaded from /seapp_contexts
02-26 16:03:58.601: E/SELinux(7548): [DEBUG] seapp_context_lookup: seinfoCategory = default
02-26 16:03:58.601: E/dalvikvm(7548): >>>>> Normal User
02-26 16:03:58.601: E/dalvikvm(7548): >>>>> com.mypackage [ userId:0 | appId:10201 ]
02-26 16:03:58.621: E/SELinux(7548): [DEBUG] seapp_context_lookup: seinfoCategory = default
02-26 16:03:58.621: D/dalvikvm(7548): Late-enabling CheckJNI
02-26 16:03:58.671: D/TimaKeyStoreProvider(7548): in addTimaSignatureService
02-26 16:03:58.681: D/TimaKeyStoreProvider(7548): Cannot add TimaSignature Service, License check Failed
02-26 16:03:58.681: D/ActivityThread(7548): Added TimaKesytore provider
02-26 16:03:58.751: W/ActivityThread(7548): Application com.mypackage can be debugged on port 8100...
02-26 16:03:58.941: E/MoreInfoHPW_ViewGroup(7548): Parent view is not a TextView
02-26 16:03:59.001: I/x(7548): Making Creator dynamically
02-26 16:03:59.041: I/Google Maps Android API(7548): Google Play services client version: 6587000
02-26 16:03:59.051: I/Google Maps Android API(7548): Google Play services package version: 6776036
02-26 16:03:59.941: I/dalvikvm(7548): Could not find method android.content.pm.PackageManager.getPackageInstaller, referenced from method com.google.android.gms.common.ew.c
02-26 16:03:59.941: W/dalvikvm(7548): VFY: unable to resolve virtual method 441: Landroid/content/pm/PackageManager;.getPackageInstaller ()Landroid/content/pm/PackageInstaller;
02-26 16:03:59.941: D/dalvikvm(7548): VFY: replacing opcode 0x6e at 0x000f
02-26 16:03:59.981: W/ActivityThread(7548): ClassLoader.loadClass: The class loader returned by Thread.getContextClassLoader() may fail for processes that host multiple 
applications. You should explicitly specify a context class loader. For example: Thread.setContextClassLoader(getClass().getClassLoader());
02-26 16:04:00.021: D/AbsListView(7548): Get MotionRecognitionManager
02-26 16:04:00.081: I/System.out(7548): Thread-618(HTTPLog):isShipBuild true
02-26 16:04:00.081: I/System.out(7548): Thread-618(HTTPLog):SmartBonding Enabling is false, SHIP_BUILD is true, log to file is false, DBG is false
02-26 16:04:00.221: I/Adreno-EGL(7548): <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build:  ()
02-26 16:04:00.221: I/Adreno-EGL(7548): OpenGL ES Shader Compiler Version: E031.24.00.08
02-26 16:04:00.221: I/Adreno-EGL(7548): Build Date: 03/21/14 Fri
02-26 16:04:00.221: I/Adreno-EGL(7548): Local Branch: AU200+patches_03212014
02-26 16:04:00.221: I/Adreno-EGL(7548): Remote Branch: 
02-26 16:04:00.221: I/Adreno-EGL(7548): Local Patches: 
02-26 16:04:00.221: I/Adreno-EGL(7548): Reconstruct Branch: 
02-26 16:04:00.251: I/HWUI(7548): EGLImpl-HWUI Protected EGL context created
02-26 16:04:00.261: D/OpenGLRenderer(7548): Enabling debug mode 0
02-26 16:04:01.301: D/dalvikvm(7548): GC_FOR_ALLOC freed 17677K, 55% free 16268K/35592K, paused 55ms, total 55ms
02-26 16:04:03.161: D/dalvikvm(7548): GC_FOR_ALLOC freed 7882K, 54% free 16547K/35592K, paused 48ms, total 48ms
02-26 16:04:08.201: W/System.err(7548): java.lang.NullPointerException
02-26 16:04:08.201: W/System.err(7548):     at com.mypackage.FetchAddressIntentService.deliverResultToReceiver(FetchAddressIntentService.java:113)
02-26 16:04:08.201: W/System.err(7548):     at com.mypackage.FetchAddressIntentService.onHandleIntent(FetchAddressIntentService.java:95)
02-26 16:04:08.201: W/System.err(7548):     at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
02-26 16:04:08.201: W/System.err(7548):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-26 16:04:08.201: W/System.err(7548):     at android.os.Looper.loop(Looper.java:146)
02-26 16:04:08.211: W/System.err(7548):     at android.os.HandlerThread.run(HandlerThread.java:61)

Upvotes: 1

Views: 1305

Answers (1)

Simon
Simon

Reputation: 19938

The reason why you are getting a null pointer exception is because the ResultReceiver you have created has not been instantiated. The Google training on https://developer.android.com/training/location/display-address.html doesn't seem to specifically deal with this but nonetheless, in the MainActivity of your app that request the "FetchAddressIntentService", you can instantiate the ResultReceiver.

MainActivity.java

protected void startIntentService() {
    Intent intent = new Intent(this, AddressIntentService.class);
    mResultReceiver = new AddressResultReceiver(new Handler()); //instantiate here
    intent.putExtra(RECEIVER, mResultReceiver);
    intent.putExtra(LOCATION_DATA_EXTRA, mLastLocation);
    startService(intent);
}

Then in your FetchAddressIntentService.java, you will extract the mResultReceiver item out of the intent bundle like this:

@Override
protected void onHandleIntent(Intent intent) {
    Bundle parameters = intent.getExtras();
    mReceiver = parameters.getParcelable(RECEIVER); }

Rerun your code and the null pointer exception disappears as we have instantiated.

Upvotes: 7

Related Questions