Search code examples
javaandroidarraysautocompletetextview

Android AutoCompleteTextView how can I ignore extra spaces


I have been wrestling with this issue all day. I have a simple AutoCompleteTextview and one of it's suggestions is the city of Los Angeles . If a user types in Los Angeles with 1 space in between the 2 words it works but if they type in 2 spaces or more in between the suggestions stop. This is my code

    AutoCompleteTextView location= (AutoCompleteTextView)findViewById(R.id.location);
    String[] arrays= {"Los Angeles"};
// Los Angeles: this works
// Los   Angeles: this does not work notice the extra space in between
// I want to treat extra spaces as just 1 space
    location.setThreshold(2);
    ArrayAdapter<String> adapter=  new ArrayAdapter<>(Purpose.this, android.R.layout.simple_selectable_list_item,arrays);
   location.setAdapter(adapter);

I have also tried this

    String[] arrays= {"Los Angeles".replaceAll("  "," ")};
 // I can not obviously use trim because it merges everything

I have many groups of data but this is the fundamental issue, if I can fix this part then it solves the issue for the other group of data.


Solution

  • I don't know of anything out there that does this, personally I would just write a separate method that cleans your String. Something involving StringBuilder

    for(int x = 0; x < YourString.length(); x++) {
        if(YourString[x].equals(" ") && YourString[x-1].equals(" ") {
            (StringBuilder.removeCharAt(x-1));
        }
    }
    

    Crude code I just typed, but just to give you some inspiration.