Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Howto send requests to the Google API when a user pauses typing?

I am working on this app where users can enter a location in an autoCompleteTextView and it will suggest locations based on the Google Places Api as is described here.

However i would like to restrict the amount of request send by the app by only sending requests if the user stops typing for a certain amount of time. Does anyone know how to do this?

like image 643
hholtman Avatar asked Nov 02 '12 11:11

hholtman


2 Answers

Similar to this answer but slightly more concise and without introducing extra state. You also don't need the threshold checks since performFiltering is only called when filtering is actually required.

Subclassing AutoCompleteTextView seems to be the only way to go, since you cannot override/replace the TextWatcher added by AutoCompleteTextView.

public class DelayAutoCompleteTextView extends AutoCompleteTextView {           
    public DelayAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            DelayAutoCompleteTextView.super.performFiltering((CharSequence) msg.obj, msg.arg1);
        }
    };

    @Override
    protected void performFiltering(CharSequence text, int keyCode) {
        mHandler.removeMessages(0);
        mHandler.sendMessageDelayed(mHandler.obtainMessage(0, keyCode, 0, text), 750);
    }
}
like image 102
Jan Berkel Avatar answered Nov 18 '22 19:11

Jan Berkel


I have found a solution to the above problem which is working quite nicely. I have extended the AutoCompleteTextView in the following way. If anyone knows how to further improve this code please let me know.

public class MyAutoCompleteTextView extends AutoCompleteTextView {

// initialization
int threshold;
int delay = 750;
Handler handler = new Handler();
Runnable run;

// constructor
public MyAutoCompleteTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void performFiltering(final CharSequence text, final int keyCode) {
    // get threshold
    threshold = this.getThreshold();

    // perform filter on null to hide dropdown
    doFiltering(null, keyCode);

    // stop execution of previous handler
    handler.removeCallbacks(run);

    // creation of new runnable and prevent filtering of texts which length
    // does not meet threshold
    run = new Runnable() {
        public void run() {
            if (text.length() > threshold) {
                doFiltering(text, keyCode);
            }
        }
    };

    // restart handler
    handler.postDelayed(run, delay);
}

// starts the actual filtering
private void doFiltering(CharSequence text, int keyCode) {
    super.performFiltering(text, keyCode);
}

}
like image 4
hholtman Avatar answered Nov 18 '22 21:11

hholtman