質問

I'm having an error while trying to get an intent from another application. At start, I had the intent to run the IP camera stream, and it worked like a charm. But later when I click on the screen to get a snapshot, click yes to share and then cancel the sharing intent to go back to the IP camera stream, I get an error there NullPointerException.

Here is my code:

public class Activity_streamCam extends Activity {
private static final boolean DEBUG = false;
Activity activity;
final Context context = this;
URL url_snap;
private static final String TAG = "MJPEG";
PowerManager powerManager = null;
WakeLock wakeLock = null;
String URL1, test, URL2;

private boolean suspending = false;

private MjpegView mv;

@SuppressWarnings("deprecation")
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.stream_camera);
    this.powerManager = (PowerManager) this
            .getSystemService(Context.POWER_SERVICE);

    this.wakeLock = this.powerManager.newWakeLock(
            PowerManager.FULL_WAKE_LOCK, "My Lock");

    Intent intent = getIntent();
    // URL1 = intent.getExtras().getString("key");
    Bundle extras = intent.getExtras();
    if (extras != null) {
        URL1 = extras.getString("key");
        // Check for presence of URL1
        if (URL1 != null) {
            test = URL1 + "axis-cgi/mjpg/video.cgi?resolution=320x240";
        }
    }

    mv = (MjpegView) findViewById(R.id.mv);
    new DoRead().execute(test);

    mv.setOnTouchListener(new View.OnTouchListener() {

        @SuppressLint("Wakelock")
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            try {
                url_snap = new URL(
                        "http://plazacam.studentaffairs.duke.edu/axis-cgi/jpg/image.cgi?resolution=320x240");

                Bitmap bmp = snapShotManager.takeSnapshot(url_snap);
                final File share = snapShotManager.saveSnap(bmp);

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        context);

                // set title
                alertDialogBuilder.setTitle("Success snapshot");

                // set dialog message
                alertDialogBuilder
                        .setMessage("Would you like to share it ?")
                        .setCancelable(true)
                        .setPositiveButton("Yes",
                                new DialogInterface.OnClickListener() {


                                    public void onClick(
                                            DialogInterface dialog, int id) {
                                        mv.stopPlayback();
                                        mv.destroyDrawingCache();
                                        Intent sendIntent = new Intent(
                                                Intent.ACTION_SEND);
                                        sendIntent.setType("image/jpeg");
                                        sendIntent.putExtra(
                                                Intent.EXTRA_STREAM, Uri
                                                        .parse("file://"
                                                                + share));
                                        sendIntent
                                                .putExtra(
                                                        Intent.EXTRA_TEXT,
                                                        "This snapshot was taken by DroidCamViewer app, check it out ! :)");

                                        try {
                                            startActivity(Intent
                                                    .createChooser(
                                                            sendIntent,
                                                            "share"));
                                        } catch (Exception e) {




                                        }

                                    }
                                })
                        .setNegativeButton("No",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(
                                            DialogInterface dialog, int id) {
                                        dialog.cancel();

                                    }
                                });

                AlertDialog alertDialog = alertDialogBuilder.create();

                alertDialog.show();

            } catch (IOException e) {
                Log.i(getString(R.string.logTag), "Snap I/O exception !!");
                e.printStackTrace();
            }

            return false;
        }
    });

}

public void onResume() {
    if (DEBUG)
        Log.d(TAG, "onResume()");

    super.onResume();

    if (mv != null) {
        if (suspending) {
            suspending = false;
            new RestartApp().execute();
            this.wakeLock.acquire();
        }
    }

}

public void onStart() {
    if (DEBUG)
        Log.d(TAG, "onStart()");
    super.onStart();
}

public void onPause() {

    if (DEBUG)
        Log.d(TAG, "onPause()");
    super.onPause();

}

public void onStop() {
    if (DEBUG)
        Log.d(TAG, "onStop()");
    super.onStop();

}

public void onRestart() {

    if (DEBUG)
        Log.d(TAG, "onRestart()");

    super.onRestart();
    if (mv != null) {
        if (suspending) {
            suspending = false;
            new RestartApp().execute();
            this.wakeLock.acquire();
        }
    }
}

public void onDestroy() {
    if (DEBUG)
        Log.d(TAG, "onDestroy()");
    super.onDestroy();
    mv.stopPlayback();
    mv.destroyDrawingCache();
}

public class DoRead extends AsyncTask<String, Void, MjpegInputStream> {
    protected MjpegInputStream doInBackground(String... url) {

        HttpResponse res = null;
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpParams httpParams = httpclient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 5 * 1000);
        Log.d(TAG, "1. Sending http request");
        try {
            res = httpclient.execute(new HttpGet(URI.create(url[0])));
            Log.d(TAG, "2. Request finished, status = "
                    + res.getStatusLine().getStatusCode());
            if (res.getStatusLine().getStatusCode() == 401) {

                return null;
            }
            return new MjpegInputStream(res.getEntity().getContent());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            Log.d(TAG, "Request failed-ClientProtocolException", e);
            // Error connecting to camera
        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG, "Request failed-IOException", e);
            // Error connecting to camera
        }
        return null;
    }

    protected void onPostExecute(MjpegInputStream result) {

        mv.setSource(result);
        if (result != null)
            result.setSkip(1);
        mv.setDisplayMode(MjpegView.SIZE_BEST_FIT);
        mv.showFps(true);

    }
}

public class RestartApp extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... v) {
        Activity_streamCam.this.finish();
        return null;
    }


    protected void onPostExecute(Void v) {
        startActivity((new Intent(Activity_streamCam.this,
                Activity_streamCam.class)));
    }
}


    }

The NullPointerException results when I click yes on the alert box and then cancel the intent or share the bitmap to go back to the stream.

Here is my logcat

05-13 13:23:13.831: E/AndroidRuntime(276): FATAL EXCEPTION: main
05-13 13:23:13.831: E/AndroidRuntime(276): java.lang.RuntimeException: Unable to start     activity     ComponentInfo{com.marwen.droidcamviewer/com.marwen.droidcamviewer.Activity_streamCam}:     java.lang.NullPointerException
05-13 13:23:13.831: E/AndroidRuntime(276):  at     android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
05-13 13:23:13.831: E/AndroidRuntime(276):  at     android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-13 13:23:13.831: E/AndroidRuntime(276):  at     android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-13 13:23:13.831: E/AndroidRuntime(276):  at     android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-13 13:23:13.831: E/AndroidRuntime(276):  at     android.os.Handler.dispatchMessage(Handler.java:99)
05-13 13:23:13.831: E/AndroidRuntime(276):  at android.os.Looper.loop(Looper.java:123)
05-13 13:23:13.831: E/AndroidRuntime(276):  at     android.app.ActivityThread.main(ActivityThread.java:4627)
05-13 13:23:13.831: E/AndroidRuntime(276):  at     java.lang.reflect.Method.invokeNative(Native Method)
05-13 13:23:13.831: E/AndroidRuntime(276):  at     java.lang.reflect.Method.invoke(Method.java:521)
05-13 13:23:13.831: E/AndroidRuntime(276):  at     com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-13 13:23:13.831: E/AndroidRuntime(276):  at     com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-13 13:23:13.831: E/AndroidRuntime(276):  at dalvik.system.NativeStart.main(Native     Method)
05-13 13:23:13.831: E/AndroidRuntime(276): Caused by: java.lang.NullPointerException
05-13 13:23:13.831: E/AndroidRuntime(276):  at     com.marwen.droidcamviewer.Activity_streamCam.onCreate(Activity_streamCam.java:66)
05-13 13:23:13.831: E/AndroidRuntime(276):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-13 13:23:13.831: E/AndroidRuntime(276):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
05-13 13:23:13.831: E/AndroidRuntime(276):  ... 11 more

Android Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.marwen.droidcamviewer"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="19" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.marwen.droidcamviewer.MainActivity"
        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=".Activity_setPreference"
        android:label="@string/title_activity_main" >
    </activity>
    <activity
        android:name="Activity_streamCam"
        android:label="@string/title_activity_streamCam"
        android:screenOrientation="landscape" >
    </activity>
    <activity
        android:name="Activity_addCam"
        android:label="@string/title_activity_addCam" >
    </activity>
    <activity
        android:name="Activity_about"
        android:label="@string/title_activity_about" >
    </activity>
    <activity
        android:name="Activity_Camera_list"
        android:label="@string/title_activity_about" >
    </activity>
    <activity
        android:name="EditCam"
        android:label="@string/title_activity_EditCam" >
    </activity>
    <activity
        android:name="Activity_manageCam"
        android:label="@string/title_activity_manageCam" >
    </activity>
</application>

</manifest>
役に立ちましたか?

解決

It is possible that you've got an Intent without extras. When you do this:

URL1 = intent.getExtras().getString("key");

You will get a NullPointerException if the Intent has no extras.

To prevent this, do:

Bundle extras = intent.getExtras();
if (extras != null) {
    URL1 = extras.getString("key");
    // Check for presence of URL1
    if (URL1 != null) {
        // Here you can be sure not to get NullPointerException
    }
}

This is just good defensive programming.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top