手电筒应用程序中的空指针异常

时间:2015-02-10 18:18:40

标签: java android

我一直在尝试使用图片按钮(初学者)创建一个基本的手电筒应用程序。我在代码中没有语法错误,但在运行时确实有一些NULL指针异常。

这是我的主要活动课: -

 public class FlashLight extends Activity{

        Camera camera = null;
        Parameters params = null;
        boolean isFlashOn = false;
        boolean hasFlash;
        ImageButton btnSwitch = (ImageButton) findViewById(R.id.imageButton1);

        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            hasFlash = getApplicationContext().getPackageManager()
                    .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
            if(!hasFlash)
            {
                AlertDialog alert = new AlertDialog.Builder(FlashLight.this).create();
                alert.setTitle("Error");
                alert.setMessage("Application Not Supported");
                alert.setButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // closing the application
                        finish();
                    }
                });
                return;
            }
         // get the camera
            getCamera();

            // displaying button image
            toggleButtonImage();


            // Switch button click event to toggle flash on/off
            btnSwitch.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (isFlashOn) {
                        // turn off flash
                        turnOffFlash();
                    } else {
                        // turn on flash
                        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 toggleButtonImage() {
            try{
            if(isFlashOn){
                btnSwitch.setImageResource(R.drawable.switchon);
            }else{
                btnSwitch.setImageResource(R.drawable.switchoff);
            }
            }
            catch(RuntimeException e){
                Log.e("Could not toggle Button image ", e.getMessage());
            }
        }

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

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

                // changing button/switch image
                toggleButtonImage();
            }
            }
            catch(RuntimeException e){
                Log.e("Could not turn on Flash ", e.getMessage());          
            }
        }

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

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

                // changing button/switch image
                toggleButtonImage();
            }
            }
            catch(RuntimeException e){
                Log.e("Could not turn off flash ", e.getMessage());         
            }
        }
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.flash_light, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.action_settings) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

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

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

            // on pause turn off the flash
            turnOffFlash();
        }

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

        @Override
        protected void onResume() {
            super.onResume();
            // on resume turn on the flash
            if(hasFlash)
                turnOnFlash();
        }

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

            // on starting the app get the camera params
            getCamera();
        }

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

            // on stop release the camera
            if (camera != null) {
                camera.release();
                camera = null;
            }
        }
    }

虽然这是我的清单文件: -

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

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="FlashLight"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

请帮助识别logcat菜单中的以下错误: -

02-10 23:18:23.409:E / AndroidRuntime(13237):java.lang.RuntimeException:无法实例化活动ComponentInfo {com.example.flashlight / com.example.flashlight.FlashLight}:java .lang.NullPointerException

1 个答案:

答案 0 :(得分:0)

ImageButton btnSwitch为您提供空指针,您没有 的setContentView(R.layout.name_of_your_activity);

更改此功能,它将起作用:

Camera camera = null;
Camera.Parameters params = null;
boolean isFlashOn = false;
boolean hasFlash;
ImageButton btnSwitch; //add this



protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.name_of_your_xml_layout_for_activity);//add this
    btnSwitch=(ImageButton)findViewById(R.id.imageButton1);//add this

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