当我使用findfindViewById定义两个浮动按钮时,为什么我的应用程序崩溃?

时间:2019-10-31 12:22:24

标签: android

当我尝试通过findViewById(..)设置2个按钮时。但是,我的应用崩溃了。

我一直在寻找它并修复代码中的一些错误,但是即使如此,该应用程序仍然崩溃,我也不知道原因。

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.i(TAG,"called onCreate");
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    less_button= findViewById(R.id.lessButton);
    plus_button = findViewById(R.id.plusButton);
    setContentView(R.layout.activity_main);


    if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)
            == PackageManager.PERMISSION_DENIED){
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA}, 100);
    }

    mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.opencv_camera_activity_surface_view);
    mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
    mOpenCvCameraView.setCvCameraViewListener(this);

    flash = findViewById(R.id.fabFlashLight);

    flash.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(((JavaCameraView) mOpenCvCameraView).isFlashModeOn()){

                ((JavaCameraView) mOpenCvCameraView).turnOffTheFlash();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    flash.setImageDrawable(getDrawable(R.drawable.ic_twotone_flash_off_24px));
                }

            }
            else{
                ((JavaCameraView) mOpenCvCameraView).turnOnTheFlash();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    flash.setImageDrawable(getDrawable(R.drawable.ic_twotone_flash_on_24px));
                }
            }
        }
    });

    zoom = findViewById(R.id.seekBar);

    zoom.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            ((JavaCameraView) mOpenCvCameraView).setSeekBarZoom(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            seekBar.setProgress(((JavaCameraView) mOpenCvCameraView).getSeekBarZoom());
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });


    first = findViewById(R.id.floatingActionButton);
    second = findViewById(R.id.floatingActionButton2);
    third = findViewById(R.id.floatingActionButton3);
    first.hide();
    second.hide();
    third.hide();


    mFirstButton = findViewById(R.id.firstButton);
    mSecondButton = findViewById(R.id.secondButton);
    mThirdButton = findViewById(R.id.thirdButton);
    mFirstButton.setVisibility(View.INVISIBLE);
    mSecondButton.setVisibility(View.INVISIBLE);
    mThirdButton.setVisibility(View.INVISIBLE);

    res = findViewById(R.id.textView);
    res.setText("");

    try {
        mPhotoFile = createImageFile();
    } catch (IOException e) {
        e.printStackTrace();
    }

这是我得到的错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.maxwellar, PID: 24791
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.maxwellar/com.example.maxwellar.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3042)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3282)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1970)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7156)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
        at android.support.v7.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:249)
        at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
        at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
        at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:191)
        at com.example.maxwellar.MainActivity.<init>(MainActivity.java:96)
        at java.lang.Class.newInstance(Native Method)
        at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
        at android.support.v4.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:43)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1219)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3030)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3282) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1970) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7156) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)

4 个答案:

答案 0 :(得分:3)

您首先需要使用setContentView(R.layout.activity_main),随后您将可以使用findViewById(...)而不会出现错误。 如您在文档中所读,setContentView负责:

  

从布局资源设置活动内容。该资源将是   膨胀,将所有顶级视图添加到活动中。

因此,在没有调用setContentView的情况下,活动不知道(在您的情况下)应该在何处查找按钮ID。

答案 1 :(得分:0)

您应该先设置 contentView(),然后才能调用findViewById()方法。在设置setContentView()之前,活动不知道其视图在哪里。因此它找不到任何视图。下面是解决您问题的方法。

就我而言,它工作正常。

class MainActivity : AppCompatActivity() {

private lateinit var less_button: Button
private lateinit var plus_button: Button

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    setContentView(R.layout.activity_main)
    less_button= findViewById(R.id.lessButton);
    plus_button = findViewById(R.id.plusButton);

    less_button.setOnClickListener{
        Toast.makeText(this, "Less Button Clicked", Toast.LENGTH_SHORT).show()
    }
    plus_button.setOnClickListener{
        Toast.makeText(this, "Plus Button Clicked", Toast.LENGTH_SHORT).show()
    }

}
}

现在我的布局是

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<androidx.constraintlayout.widget.Guideline
    android:id="@+id/guideline"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.5" />

<Button
    android:id="@+id/lessButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="A Button"
    app:layout_constraintBottom_toTopOf="@+id/guideline"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<Button
    android:id="@+id/plusButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="B Activity"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/lessButton" />


</androidx.constraintlayout.widget.ConstraintLayout>

答案 2 :(得分:0)

您在onCreate中的贴花错误

您已经在setContentView之前初始化了视图,视图应该在setcontentview之后初始化

requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
less_button= findViewById(R.id.lessButton);
plus_button = findViewById(R.id.plusButton);

答案 3 :(得分:-1)

您是否检查了布局中的XML代码?也许您正在调用未定义视图的ID。