Search code examples
javaandroidandroid-edittextkeypress

How to automatically press enter key when edittext is not null?


I'm make a EditText and the value i got from Firebase, it is possible if edittext is not null then enter key pressed automatically

private void init(){
    Log.d(TAG, "init: initializing");

    if (mSearchText != null){
       what must i write here?
    }

    mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
            if(actionId == EditorInfo.IME_ACTION_SEARCH
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || keyEvent.getAction() == KeyEvent.ACTION_DOWN
                    || keyEvent.getAction() == KeyEvent.KEYCODE_ENTER){

                //execute our method for searching
                geoLocate();
            }

            return false;
        }
    });

Solution

  • [1] you can try below code

    String yourtext=mSearchText.getText().toString().trim();
    if(!TextUtils.isEmpty(yourtext)) //or else you can use  if(yourtext!=null && !yourtext.equalsIgnoreCase(""))
    {
        mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if(actionId == EditorInfo.IME_ACTION_SEARCH
                        || actionId == EditorInfo.IME_ACTION_DONE
                        || keyEvent.getAction() == KeyEvent.ACTION_DOWN
                        || keyEvent.getAction() == KeyEvent.KEYCODE_ENTER){
    
                    //execute your method for searching
                    geoLocate();
                }
    
                return false;
            }
        });
    }
    

    [2] else you can achieve your functionality using this(Direct method calling)

    String yourtext=mSearchText.getText().toString().trim();
    if(!TextUtils.isEmpty(yourtext)) //or else you can use  if(yourtext!=null && !yourtext.equalsIgnoreCase(""))
    {
         //execute your method for searching
                    geoLocate();
    }