0

I am creating a custom Android ActionBar search following this tutorial.

The handleMenuSearch(); is activated on onOptionsItemSelected.

protected void handleMenuSearch(){
    ActionBar action = getSupportActionBar(); //get the actionbar

    if(isSearchOpened){ //test if the search is open

        action.setDisplayShowCustomEnabled(false); //disable a custom view inside the actionbar
        action.setDisplayShowTitleEnabled(true); //show the title in the action bar

        //hides the keyboard
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(edtSeach.getWindowToken(), 0);

        //add the search icon in the action bar
        mSearchAction.setIcon(getResources().getDrawable(R.drawable.search));

        isSearchOpened = false;
    } else { //open the search entry

        action.setDisplayShowCustomEnabled(true); //enable it to display a
        // custom view in the action bar.
        action.setCustomView(R.layout.search_bar);//add the custom view
        action.setDisplayShowTitleEnabled(false); //hide the title

        edtSeach = (EditText)action.getCustomView().findViewById(R.id.edtSearch); //the text editor

        edtSeach.requestFocus();

        edtSeach.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                loadData(edtSeach.getText().toString());
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            public void afterTextChanged(Editable s) {

            }
        });

        //open the keyboard focused in the edtSearch
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(edtSeach, InputMethodManager.SHOW_IMPLICIT);


        //add the close icon
        mSearchAction.setIcon(getResources().getDrawable(R.drawable.ximage));

        isSearchOpened = true;
    }
}

What I want to achieve is to activate the searching once the activity is started.

I tried to put handleMenuSearch(); under onCreate but this gives me NullPointerException

The reason for this I guess is because I cannot call mSearchAction from onCreate.

public boolean onPrepareOptionsMenu(Menu menu) {
        mSearchAction = menu.findItem(R.id.search);
        return super.onPrepareOptionsMenu(menu);
    }
user2872856
  • 2,003
  • 2
  • 21
  • 54

1 Answers1

0

Problem solved by using Handler.

protected void onResume() {
        super.onResume();
        new Handler().postDelayed(new Runnable() {
            public void run() {
                handleMenuSearch();
            }
        }, 1000);
    }
user2872856
  • 2,003
  • 2
  • 21
  • 54