【问题标题】:Android java.lang.NullPointerException on not empty object [duplicate]非空对象上的Android java.lang.NullPointerException [重复]
【发布时间】:2021-09-18 01:29:01
【问题描述】:

我正在尝试隐藏图像视图:

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

我得到一个错误:

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

allImageView.setVisibility(View.GONE); 行中的错误 为什么会这样?如何设置可见性?

【问题讨论】:

  • "变量不为空" - wrong
  • 或者你使用了错误的布局......或者你试图获取作为片段一部分的视图......或者变量在不同的范围内......或者时间错误

标签: android visibility


【解决方案1】:

您必须在获取视图并调用 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;
        }
    });
}

【讨论】:

  • 我这样做了。但我没想过要展示这一点。这不是重要的部分
猜你喜欢
  • 1970-01-01
  • 2015-03-10
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
  • 2021-12-24
  • 2018-12-31
相关资源
最近更新 更多