I am developing a youtube app. The app allows user to search for music videos on youtube. Youtube has an auto complete feature and I wish to provide that feature in my app as well.
1)I have a text field. I have added a dataChangeListener to it. Whenever the text in the textfield is changed, an event is fired.
2)When the event is fired, I capture the text from the textfield, and pass it to the google API to get autocomplete suggestions. I use a connection request for this.
3)Whenever, I get new text from the text field, I try to kill the previous connection request object. Because the response for the previous text is not important.
4)Now, it works fine when I type slowly. But when I make several modifications to the text in the text field, I get a null pointer exception. I don't know why .
5)I have boldened the comments below. Also, is this the right way to do it? Is there a better way?
public void autoSuggest(String queryTerm) {
//gets XML response from Server and then returns a vector of strings
queryTerm = Util.encodeUrl(queryTerm.trim());
String queryForServer = AutoSuggestQueryString + "q=" + queryTerm + "&client=toolbar&ds=yt";
// queryForServer=Util.encodeUrl(queryForServer);
if (c != null) {
c.kill();
}
c = new ConnectionRequest() {
protected void readResponse(InputStream input) throws IOException {
ByteArrayOutputStream bs = new ByteArrayOutputStream();
int ch;
if(input==null)
{
return;
}
while ((ch = input.read()) != -1) {
bs.write(ch);
}
serverOutput = new String(bs.toByteArray());
// System.out.println(serverOutput);
bs.close();
InputStream is = new ByteArrayInputStream(serverOutput.getBytes());
InputStreamReader isr = new InputStreamReader(is);
XMLParser xml_parser = new XMLParser();
Element elem;
elem = xml_parser.parse(isr);
Vector<String> autoSuggestResult = new Vector<String>();
int no_of_children = elem.getChildrenByTagName("completesuggestion").size();
for (int i = 0; i < no_of_children; i++) {
String str = elem.getChildAt(i).getChildAt(0).getAttribute("data");
autoSuggestResult.add(str);
}
displayAutoSuggestResults(autoSuggestResult); // another method to display contents of the vector
}
protected void handleErrorResponseCode(int code, String message) {
// System.out.println(code+" "+message);
// Dialog.setCommandsAsButtons(true);
Dialog.show("Error", message, "OK", null);
// System.out.println("The server is acting stubborn");
}
protected void handleException(Exception err) {
// Dialog.setCommandsAsButtons(true);
Dialog.show("Error", err.toString(), "OK", null); //I get null pointer exception here
// System.out.println("The server is acting stubborn");
}
};
c.setUrl(queryForServer);
c.setHttpMethod("GET");
c.setContentType("xml");
NetworkManager.getInstance().shutdown(); //to refresh the NetworkManager...remove previoud connection requests
NetworkManager.getInstance().start();
NetworkManager.getInstance().addToQueueAndWait(c);
// System.out.println(serverOutput);
}