从Android中的其他Activity获取意图时出现NullPointerException

时间:2014-05-13 13:28:01

标签: android android-intent

我在尝试从其他应用程序获取意图时遇到错误。一开始,我有意运行IP摄像机流,它就像一个魅力。但是稍后当我点击屏幕获取快照时,单击“是”进行共享,然后取消共享意图以返回到IP摄像机流,我收到NullPointerException错误。

这是我的代码:

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)));
    }
}


    }

当我在警告框中单击是然后取消意图或共享位图以返回到流时,会产生NullPointerException。

这是我的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>

1 个答案:

答案 0 :(得分:0)

您可能没有额外内容Intent。当你这样做时:

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

如果NullPointerException没有额外内容,您将获得Intent

为防止这种情况,请执行以下操作:

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
    }
}

这只是一个很好的防守计划。