-2

I'm trying to hide an image view:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);

    allImageView = findViewById(R.id.allImageView); // The variable is not null


searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if(newText.equals("")) {
                    allImageView.setVisibility(View.VISIBLE);
                } else {
                    allImageView.setVisibility(View.GONE); // Trying to hide the image view
                }
                return true;
            }
        });
}

And I get an error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setVisibility(int)' on a null object reference

error in line allImageView.setVisibility(View.GONE); Why does this happen? how can I set the visibility?

Ziv Sion
  • 424
  • 4
  • 14
  • "The variable is not null" - [wrong](https://stackoverflow.com/q/19078461/6296561) – Zoe Jul 07 '21 at 13:39
  • or duplicate of [findViewByID returns null](https://stackoverflow.com/questions/3264610/findviewbyid-returns-null) – Selvin Jul 07 '21 at 13:39
  • or you use wrong layout .... or you are trying to get view which is a part of fragment ... or variable is in different scope ... or timing is wrong – Selvin Jul 07 '21 at 13:41

1 Answers1

-1

You have to set the view of the activity before to get views and to call super.onCreate()

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(saveInstanceState)
    //put that here replacing your layout
    setContentView(R.layout.your_layout)
    allImageView = findViewById(R.id.allImageView);


    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            if(newText.equals("")) {
                allImageView.setVisibility(View.VISIBLE);
            } else {
                allImageView.setVisibility(View.GONE);
            }
            return true;
        }
    });
}
SebastienRieu
  • 1,443
  • 2
  • 10
  • 20