简体   繁体   中英

android setOnClickListener gives null pointer exception?

I have written code for onClick method for Custom Dialog top of the another view. It gives me nullpointer exception . I've also tried using Layout inflater. It gives me error on ok.setOnclickListener . What's wrong in my code?

 ImageButton search =(ImageButton) findViewById(R.id.search);
            search.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    Dialog searchDialog = new Dialog(Page.this);

                    /*LayoutInflater inflater = (LayoutInflater) getApplicationContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);


                     View layout = inflater.inflate(R.layout.search, null);
                     searchDialog.addContentView(layout, new LayoutParams(
                                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
                     searchDialog.setContentView(layout);*/

                    searchDialog.setContentView(R.layout.search);
                    searchDialog.setTitle("Search Dialog");
                    searchDialog.setCancelable(true);

                    Button ok = (Button)findViewById(R.id.OkButton);
                    ok.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            String searchString = null;
                            EditText searchText = (EditText)findViewById(R.id.searchText);
                            if(searchText.getText()!=null){
                                searchString = searchText.getText().toString();
                            }
                            Log.i("TAG","Search word :"+searchString);

                        }
                    });

                    searchDialog.show();



                }


            });

You are looking for the button in the activity that creates the dialog instead of the dialog itself. The findViewById line should be:

Button ok = (Button)searchDialog.findViewById(R.id.OkButton);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM