Henry
Henry

Reputation: 79

Implementing onClick() for a button inside a layout set in the AlertDialog

I don't know why it gets NullPointerException provided that my Button has been initialized. Here is my code. Hope you guys can help. Thanks

public boolean onOptionsItemSelected(MenuItem item)
{   switch (item.getItemId())
        {   
            case SEARCH:
                inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                AlertDialog.Builder search = new AlertDialog.Builder(this);
                search.setTitle(R.string.search);
                searchDialog = inflater.inflate(R.layout.search,null);
                search.setView(searchDialog);

                   //The problem should be here
                searchButton = (Button) findViewById(R.id.searchButton);
                   //R.id.searchButton is inside the layout, search.xml
                searchButton.setOnClickListener(new OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {   //For testing
                        Toast.makeText(getApplicationContext(), 
                                "Search was clicked!", Toast.LENGTH_SHORT).show();
                    }
                });
                AlertDialog searchDialog = search.create();
                searchDialog.show();
                return true;
                .
                .
                .

Upvotes: 0

Views: 143

Answers (1)

Shankar Agarwal
Shankar Agarwal

Reputation: 34765

searchDialog = inflater.inflate(R.layout.search,null);

the above line is changed and and for initializing a button you must use the reference of view.

public boolean onOptionsItemSelected(MenuItem item)
{   switch (item.getItemId())
        {   
            case SEARCH:
                inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                AlertDialog.Builder search = new AlertDialog.Builder(YourActivity.this);
                search.setTitle(R.string.search);
                View view = inflater.inflate(R.layout.search,null);
                search.setView(view);

                   //The problem should be here
                searchButton = (Button)view.findViewById(R.id.searchButton);
                   //R.id.searchButton is inside the layout, search.xml
                searchButton.setOnClickListener(new OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {   //For testing
                        Toast.makeText(getApplicationContext(), 
                                "Search was clicked!", Toast.LENGTH_SHORT).show();
                    }
                });
                AlertDialog searchDialog = search.create();
                searchDialog.show();
                return true;
                .
                .
                .

Upvotes: 1

Related Questions