I have a textbox and search button, now all I need is the code to implement searching an array. The array I have is called Facts_Array (consists of strings). Comment if you need any more information.
+1
A:
Something like this:
EditText searchField = (EditText) findViewById(R.id.searchfield);
Button searchButton = (Button) findViewById(R.id.searchbutton);
searchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
for (String s : Facts_Array) {
if (searchField.getText().toString().contains(s)) {
// Do stuff
}
}
}
};
Of course, you might want to refine the actual search bit some more (right now it's just using contains()
), at least by ignoring case.
Tyler
2010-10-17 02:18:46
Thanks, I had basically this same thing, just missing findViewById... Can't believe I had forgot to implement this.
Jack Love
2010-10-17 02:26:13
Looping linearly over the entire array is one way to do this, the slowest possible way, but it's a way. If you have a large array, you might want to check the Arrays class and look at the search methods there (much faster, more efficient). Also, if you don't want to "do stuff" multiple times, or keep searching the array after you find a match, make sure you break the loop.
Charlie Collins
2010-10-17 12:33:32
OK thanks. I might look into that. My array is quite large.
Jack Love
2010-10-17 15:33:34
I would indeed use a different method of searching the array, especially if it's large. I was just trying to demonstrate an elementary way of doing it. As Charlie suggested, you should take a look at the Java API perhaps for a more efficient method.
Tyler
2010-10-17 18:12:52