-2

When I try to set 2 button thru findViewById(..). However, my app is crashing.

I've seach about it and fix some mistakes in the code, but even thus the the app remains crashes and I don't know the cause.

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

This is the error I get:

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)
guipivoto
  • 18,327
  • 9
  • 60
  • 75

4 Answers4

3

You need to use setContentView(R.layout.activity_main) firstly and later you will be able to use findViewById(...) without errors. As you can read in documentation setContentView is responsable for:

Setting the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity.

So without calling setContentView activity dosen't know where should look for (in your case) buttons ids.

Panicum
  • 794
  • 1
  • 9
  • 32
  • I did that, but the app remains crashing: setContentView(R.layout.activity_main); less_button= findViewById(R.id.lessButton); plus_button = findViewById(R.id.plusButton); –  Oct 31 '19 at 13:40
  • One obs, I commented the lines where are the findViewById's, and the app works perfectly, but without buttons funcionality that I want. –  Oct 31 '19 at 13:43
  • here's the code: Log.i(TAG,"called onCreate"); 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); –  Oct 31 '19 at 13:45
  • So you are is crashing or not now? With this "findViewById" bellow "setContentView"? If you want have any functionality on this buttons you need to set ".setOnClickListener" on this buttons. And please check this topis: https://stackoverflow.com/a/23353174/9738227 There are some tips that can be usefull. – Panicum Oct 31 '19 at 14:51
  • @LucasVital you can't use `setContentView` before `onCreate` is called, therefore you need to use it in `onCreate`, and you can't use `findViewById` before you call `setContentView` – Vladyslav Matviienko Nov 01 '19 at 06:38
  • @Andropogon No my app remains crash. The app just works when I coment the line where are findViewById(R.id.lessButton or plustButton, what menas that the source of problem is this two lines. –  Nov 01 '19 at 11:29
  • @Andropogon I have followed your tip and and saw the link. I see my stack trace and I have foud the folowwing menssage:"Unable to start activity ComponentInfo{com.example.maxwellar/com.example.maxwellar.MainActivity}: java.lang.ClassCastException: android.support.design.widget.FloatingActionButton cannot be cast to android.widget.Button" But what it's mean??? –  Nov 01 '19 at 11:32
  • @LucasVital It means that you should declare your buttons (less_button and plus_button) as FloatingActionButton instead as Button. Change code at top of your activity from "Button less_button;" to "FloatingActionButton less_button;" and with plus button the same (if this btn is FloatingActionButton in your xml too). – Panicum Nov 01 '19 at 11:39
  • 1
    Guys I have got solve the problem. I had declareted the button as simple button, but the correct was declarate as FloatingActionButton, because the buttons are of type FloatingAction Buttons in the XML. –  Nov 01 '19 at 12:38
0

You should set the contentView() first, then you can call findViewById() method. Before setting the setContentView(), activity doesn't know where are its views. So it cannot find any views. Below is the solution for your problem.

In my case it is working fine..

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

}
}

Now My Layout is

<?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>
0

Hi wrong decalrations in onCreate

You have initialised view before setContentView, Views should b initialised after the 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);
-1

Have you checked the XML code in your layout? Maybe you are calling the ID of a view that is not defined.

Frank
  • 78
  • 7