Tamilselvan
Tamilselvan

Reputation: 3

How to Sort array values based on Edit Text input characters?

I am having an array of String which is being used to show in a spinner. Now my need is

When the user giving their input in the edit text have to sort the array based on the edit text values ans have to show it in the spinner. I cannot get the logic fully.

I have tried like this.,

String[] a1 = { "Android", "Apple", "Andrew", "Ball" }, a2 = null;
EditText mn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mn = (EditText) findViewById(R.id.plus);

            a2 = a1;
    mn.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
                            Arrays.sort(a1);
            doCall();
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {

        }

        @Override
        public void afterTextChanged(Editable arg0) {

        }
    });

}

protected void doCall() {

    for (int i = 0; i < a1.length; i++) {
        String s = a1[i];
        for (int j = 0; j < mn.getText().toString().length(); j++) {

            if (Character.toLowerCase(s.charAt(j)) == Character
                    .toLowerCase(mn.getText().toString().charAt(j))) {
                if (j == mn.getText().toString().length() - 1) {
                    String temp = a1[0];
                    a1[0] = a2[i];
                    a1[i] = temp;

                } else {
                    continue;
                }
            } else {
                break;
            }
        }
    }
}

IF i am giving "a" means i am getting "Andrew,Ball,Apple,Android" but What i need to be shown is "Andrew,Android,Apple,Ball" How can i achieve this. thanks in advance,

Upvotes: 0

Views: 347

Answers (2)

amalBit
amalBit

Reputation: 12181

## AutoComplete ##

Try using the autoComplete functionality:

 public class CountriesActivity extends Activity {
 protected void onCreate(Bundle icicle) {
     super.onCreate(icicle);
     setContentView(R.layout.countries);

     ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
             android.R.layout.simple_dropdown_item_1line, COUNTRIES);
     AutoCompleteTextView textView = (AutoCompleteTextView)
             findViewById(R.id.countries_list);
     textView.setAdapter(adapter);
 }

 private static final String[] COUNTRIES = new String[] {
     "Android", "Apple", "Andrew", "Ball"
 };
}

Upvotes: 0

ArturSkowronski
ArturSkowronski

Reputation: 1792

You could try call Arrays.sort(names) before end of doCall() and then notify yours Spinner Adapter.

Upvotes: 1

Related Questions