RAKH
RAKH

Reputation: 45

Android: sorting letters in EditText

[Here is a screenshot of my output][1]

I am trying to sort the elements of an array. I have stored the elements to the array from EditText1(ed) and I want to sort them and display them in EditText2. I am done with storing them and displaying them, i wanted to sort them using Collections.sort(array); but it shows me that there is something wrong.

This is my code so far:

public class MainActivity extends AppCompatActivity {
List<EditText> allEds = new ArrayList<EditText>();
 EditText ed,ed2;
RelativeLayout container;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     ed= (EditText)findViewById(R.id.editText);
    ed2=(EditText)findViewById(R.id.editText2);
    final Button b=(Button)findViewById(R.id.button);
    container = (RelativeLayout)findViewById(R.id.rl);


    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            allEds.add(ed);
            String[] strings = new String[allEds.size()];
            for(int i=0; i < allEds.size(); i++){
                strings[i] = allEds.get(i).getText().toString();
                Log.e("My data", strings[i]);
                ed2.setText(strings[i]);

            }


        }
    });

[1]: https://i.sstatic.net/dowdE.jpg

Upvotes: 0

Views: 206

Answers (2)

Berdimurat Masaliev
Berdimurat Masaliev

Reputation: 345

may be something like this?

public class MainActivity extends AppCompatActivity {
    List<String> allEds = new ArrayList<String>();
    EditText ed,ed2;
    RelativeLayout container;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      ed= (EditText)findViewById(R.id.editText);
      ed2=(EditText)findViewById(R.id.editText2);
      final Button b=(Button)findViewById(R.id.button);
      container = (RelativeLayout)findViewById(R.id.rl);

      b.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        String str = ed.getText().toString();
        String lines[] = str.split("\\r?\\n");
        Arrays.sort(lines);

        ed2.setText(TextUtils.join("\n", lines));
    }
});

Upvotes: 1

Dennis van Opstal
Dennis van Opstal

Reputation: 1338

I think this will probably work (replace the code in the onClick with this):

String[] strings = ed.getText().toString().split("\\r?\\n");
Arrays.sort(strings);
String output = TextUtils.join("\\n",strings);
ed2.setText(output);

Upvotes: 1

Related Questions