Issue
I have a function written in OntextChangedListner that takes input from edittext and use it to call an API everytime you type something in edittext i.e.(if I am writing something with the string length of 10 it is calling the API 10 times).
I want that it should not call API everytime I write some thing in edittext, Whenever i stop writing then should hit API, so i tried to give a post delay so that whenever i stop writing then it will call for the API, but it is not working as i expected(if my string length is 10 then it is calling for api 10 time after some delay)
Here is My Code
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
val runnable = Runnable {
val lengthoftext = searchCompany.text.length
mycompanies.clear()
callforapi(s.toString())
}
val handler = Handler(Looper.getMainLooper())
handler.postDelayed({ runnable.run() }, 500)
}
fun callforapi(tempchar: String){
val queue = Volley.newRequestQueue(this)
val url = "SomeAPI" + tempchar
val jsonObjectRequest = JsonObjectRequest(
Request.Method.GET, url, null,
{ response ->
var tempcomparray = response.getJSONArray("companies")
var objlength = tempcomparray.length()
adapter?.clear()
for (i in 0 until objlength)
{
var tempcompobj = tempcomparray.getJSONObject(i)
mycompanies.add(tempcompobj.getString("name"))
}
Log.d("checktheobj", mycompanies.toString())
},
{ error ->
Log.d("check", "Something is Wrong ")
}
)
queue.add(jsonObjectRequest)
return
}
I am using volly library to call an API.
Please guide me how to do so.
Thankyou in Advance..
Solution
Best way to use coroutines for such a case in kotlin. If you don't know coroutines or don't want to use it. Then you can use Timer.
private Timer timer = new Timer();
private final long DELAY = 500; // Milliseconds
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int){
timer.cancel();
timer = new Timer();
timer.schedule(
new TimerTask() {
@Override
public void run() {
// TODO: Do what you need here.
val lengthoftext = searchCompany.text.length
mycompanies.clear()
callforapi(s.toString())
}
},
DELAY
);
}
}
}
Answered By - Dnyaneshwar Patil
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.