Below code is part of search box in my android app. LoadCatalog is a async task for the api call, problem is whenever it is being called the editText stops taking new character for a fraction of second(skips a character in middle).
for ex- if the user want to enter "The book of leaves"... it only sometimes take "The boo of " or "The bookof "
It skips the character, pls suggest what's wrong in my code.
private TextWatcher productEntered = new TextWatcher() {
long lastChange = 0;
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence enteredSequence, int start, int before, int count) {
searchbarActionClear.setVisibility(View.VISIBLE);
enteredText = enteredSequence;
if (CommonUtils.isConnectingToInternet(DashboardActivity.this)) {
if (enteredText.length() > 3) {
new Handler().postDelayed(new Runnable() {
public void run() {
if (System.currentTimeMillis() - lastChange >= 600) {
resetList();
toolbarSuggestionEditText.setTag(toolbarSuggestionEditText.getKeyListener());
toolbarSuggestionEditText.setKeyListener(null);
new LoadCatalog().execute(String.valueOf(enteredText));
}
}
}, 600);
lastChange = System.currentTimeMillis();
}
}
}
public void afterTextChanged(Editable s) {
}
};
private class LoadCatalog extends AsyncTask<String, Void, CustomResponse> {
@Override
protected CustomResponse doInBackground(String... params) {
String url;
if (categoryItem != null) {
url = String.format(AppConstants.URLs.SEARCH_WITH_CATEGORY, params[0], categoryItem);
} else {
url = String.format(AppConstants.URLs.SEARCH, params[0]);
}
CustomResponse response = HttpRequest.GET_REQUEST(url, DashboardActivity.this);
return response;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(CustomResponse result) {
try {
if (result.getResponseCode() == 200) {
JSONArray jsonArray = null;
jsonArray = new JSONArray(result.getResponseBody());
Suggestion suggestion = null;
if (jsonArray.length() > 0) {
suggestionList.clear();
suggestionList.add(new Suggestion(null, Suggestion.TYPE_SUGGESTION_HEADER));
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
suggestion = new Suggestion(jsonObject.getString("name"),
jsonObject.getString("category"),
Suggestion.TYPE_SUGGESTION);
suggestionList.add(suggestion);
suggestionAdapter.notifyDataSetChanged();
}
toolbarSuggestionEditText.setKeyListener((KeyListener) toolbarSuggestionEditText.getTag());
} else {
toolbarSuggestionEditText.setKeyListener((KeyListener) toolbarSuggestionEditText.getTag());
Toast.makeText(DashboardActivity.this, "No item match with your search", Toast.LENGTH_SHORT).show();
suggestionList.clear();
}
} else {
toolbarSuggestionEditText.setKeyListener((KeyListener) toolbarSuggestionEditText.getTag());
}
} catch (JSONException e) {
toolbarSuggestionEditText.setKeyListener((KeyListener) toolbarSuggestionEditText.getTag());
e.printStackTrace();
}
}
}