Question

I have created a flashlight application, it runs perfectly without adding any ad unit in it. but after adding an ad unit inside the code, when i run for next time the application closes unexpectedly on my emulator and android device as well. here is my source for above mentioned application. activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="@+id/rellayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@layout/radial_background"
tools:context=".MainActivity"
tools:ignore="Overdraw" >
...
...
<com.google.ads.AdView
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView1"
    android:layout_alignParentLeft="true"
    ads:adSize="BANNER"
    ads:adUnitId="xxxxxxx"
    ads:loadAdOnCreate="true"
    ads:testDevices="TEST_EMULATOR" >
</com.google.ads.AdView>

for above actitvity i made changes in my AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jdev.itorch"
android:versionCode="1"
android:versionName="1.1.2" android:installLocation="auto" xmlns:tools="http://schemas.android.com/tools">

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" tools:ignore="OldTargetApi"/>

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity 
        android:name="com.google.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation"
        ></activity>
    <activity
        android:name="com.jdev.itorch.TorchActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

P.S. the code shows no error while the compilation. I have checked the logCat as well, it shows some NullPointerException error when the main activity starts. i don't know what to do with my code that's why i am asking help here.

here is the full length code

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;


public class TorchActivity extends Activity {

ImageButton btnSwitch;

private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
private Parameters params;
MediaPlayer mp;


@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_torch);    




    btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);



    hasFlash = getApplicationContext().getPackageManager()
            .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

    if (!hasFlash) {
        AlertDialog alert = new AlertDialog.Builder(TorchActivity.this)
                .create();
        alert.setTitle("Error");
        alert.setMessage("Sorry, your device doesn't support flash light!");
        alert.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

                finish();
            }
        });
        alert.show();
        return;
    }


    getCamera();


    toggleButtonImage();



    btnSwitch.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (isFlashOn) {

                turnOffFlash();
            } else {

                turnOnFlash();
            }
        }
    });
}



private void getCamera() {
    if (camera == null) {
        try {
            camera = Camera.open();
            params = camera.getParameters();
        } catch (RuntimeException e) {
            Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
        }
    }
}



private void turnOnFlash() {
    if (!isFlashOn) {
        if (camera == null || params == null) {
            return;
        }

        playSound();

        params = camera.getParameters();
        params.setFlashMode(Parameters.FLASH_MODE_TORCH);
        camera.setParameters(params);
        camera.startPreview();
        isFlashOn = true;


        toggleButtonImage();
    }

}



private void turnOffFlash() {
    if (isFlashOn) {
        if (camera == null || params == null) {
            return;
        }

        playSound();

        params = camera.getParameters();
        params.setFlashMode(Parameters.FLASH_MODE_OFF);
        camera.setParameters(params);
        camera.stopPreview();
        isFlashOn = false;


        toggleButtonImage();
    }
}



private void playSound(){
    if(isFlashOn){
        mp = MediaPlayer.create(TorchActivity.this, R.raw.light_switch_off);
    }else{
        mp = MediaPlayer.create(TorchActivity.this, R.raw.light_switch_on);
    }
    mp.setOnCompletionListener(new OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            // TODO Auto-generated method stub
            mp.release();
        }
    }); 
    mp.start();
}


private void toggleButtonImage(){
    if(isFlashOn){
        btnSwitch.setImageResource(R.drawable.btn_switch_on);
    }else{
        btnSwitch.setImageResource(R.drawable.btn_switch_off);
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
}

@Override
protected void onPause() {
    super.onPause();


    turnOffFlash();
}

@Override
protected void onRestart() {
    super.onRestart();
}

@Override
protected void onResume() {
    super.onResume();


    if(hasFlash)
        turnOnFlash();
}

@Override
protected void onStart() {
    super.onStart();


    getCamera();
}

@Override
protected void onStop() {
    super.onStop();


    if (camera != null) {
        camera.release();
        camera = null;
    }
}





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

}

UPDATE here is the LogCat data

03-18 09:11:43.572: D/dalvikvm(1052): GC_FOR_ALLOC freed 80K, 5% free 3068K/3224K, paused 32ms, total 34ms
03-18 09:11:43.582: I/dalvikvm-heap(1052): Grow heap (frag case) to 3.673MB for 635812-byte allocation
03-18 09:11:43.622: D/dalvikvm(1052): GC_FOR_ALLOC freed 4K, 5% free 3684K/3848K, paused 37ms, total 37ms
03-18 09:11:43.792: D/AndroidRuntime(1052): Shutting down VM
03-18 09:11:43.792: W/dalvikvm(1052): threadid=1: thread exiting with uncaught exception (group=0xb3aa7b90)
03-18 09:11:43.832: E/AndroidRuntime(1052): FATAL EXCEPTION: main
03-18 09:11:43.832: E/AndroidRuntime(1052): Process: com.jdev.itorch, PID: 1052
03-18 09:11:43.832: E/AndroidRuntime(1052): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jdev.itorch/com.jdev.itorch.TorchActivity}: java.lang.NullPointerException: println needs a message
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.app.ActivityThread.access$700(ActivityThread.java:135)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.os.Handler.dispatchMessage(Handler.java:102)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.os.Looper.loop(Looper.java:137)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at   android.app.ActivityThread.main(ActivityThread.java:4998)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at java.lang.reflect.Method.invokeNative(Native Method)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at java.lang.reflect.Method.invoke(Method.java:515)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at dalvik.system.NativeStart.main(Native Method)
03-18 09:11:43.832: E/AndroidRuntime(1052): Caused by: java.lang.NullPointerException: println needs a message
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.util.Log.println_native(Native Method)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.util.Log.e(Log.java:232)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at com.jdev.itorch.TorchActivity.getCamera(TorchActivity.java:91)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at com.jdev.itorch.TorchActivity.onStart(TorchActivity.java:199)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.app.Activity.performStart(Activity.java:5253)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2149)
03-18 09:11:43.832: E/AndroidRuntime(1052):     ... 11 more
03-18 09:16:44.422: I/Process(1052): Sending signal. PID: 1052 SIG: 9
Was it helpful?

Solution

I Guess i understand what was the actual problem in this code as mentioned by @Tyler There is a possibility that e.getMessage() could be null but further the example he gave was bit giving an error. i used to declare public volatile String errorMessage = "";

which i implement like this:

private void getCamera() {
    if (camera == null) {
        try {
            camera = Camera.open();
            params = camera.getParameters();
        } catch (RuntimeException e) {
            Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
            if(e.getMessage() == null) {
                errorMessage = "Camera Error.  Failed to Open.  Error message is null"; //here//
            }

            else {
                Log.e("Camera Error.  Failed to Open.  Error: ", e.getMessage());
            }
        }
    }
}

Thank You for your support Regards Jai Sharma.

OTHER TIPS

These three lines from the LogCat look suspicious:

03-18 09:11:43.832: E/AndroidRuntime(1052): Caused by: java.lang.NullPointerException: println needs a message
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.util.Log.println_native(Native Method)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.util.Log.e(Log.java:232)

And here is your only Log.e() call:

Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());

There is a possbility that e.getMessage() could be null. You should try making a check for that.


Edit: Here is an example:

if(e.getMessage() == null) {
    Log.e("Camera Error.  Failed to Open.",  "Error message is null");
}

else {
    Log.e("Camera Error.  Failed to Open.  Error: ", e.getMessage());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top