0

The app I've created just shows what users have typed in the EditText.

This is the onCreate method of its MainActivity:

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

    final EditText input = (EditText) findViewById(R.id.input);
    final TextView output = (TextView) findViewById(R.id.output);

    final Editable input_editable = (Editable) input.getText();

    final Button show = (Button) findViewById(R.id.show);
    final Button reset = (Button) findViewById(R.id.reset);


    show.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String text = input_editable.toString();
            output.setText(text);
        }
    });


    reset.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            input_editable.clear();
        }
    });
   }       

The problem is this:

When i run the app, everything works fine:

  • I type for eg "foo" and click "show" button, it shows "foo",
  • When I click "reset" everything is resetted,
  • Retype "bar", then it shows "bar". Nice!

But, when I just change the line

input_editable.clear();

to this

input.setText("");

then this happens after starting the app:

  • I type for eg "foo" and click "show" button, it shows "foo",
  • When I click "reset" everything seems to be resetted,
  • Retype "bar", then "foo" is still there after clicking "show"

Why?

Thanks

Muhammadjon
  • 1,476
  • 2
  • 14
  • 35

1 Answers1

0

input_editable holds the text until it clear. It can't override text and keep the latest text always. if you take new reference every time then you will get your expected value.

just try this:

show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String text = input.getEditableText().toString();
                textView.setText(text);
            }
        });

every time initialize the reference here so you will get the expected output when you apply it :

input.setText("");
Sultan Mahmud
  • 1,245
  • 8
  • 18
  • If input_editable holds the reference to the text attribute, why does its value do not change after input.setText("")? – H. Riantsoa Nov 13 '18 at 12:39
  • So... when I use input.setText( text ), what really happens? why do I have to take a new reference every time? – H. Riantsoa Nov 13 '18 at 14:24