3

Lets take this for example...

entryText.addTextChangedListener(new TextWatcher() {
 TextView wordCount = (TextView) findViewById(R.id.wordCount);
 TextView charCount = (TextView) findViewById(R.id.charCount);
 @Override
 public synchronized void afterTextChanged(Editable s) {
 wordCount.setText("W: " + String.valueOf(ChosenFile.countWords(entryText.getText().toString())));
 charCount.setText("C: " + Integer.toString(entryText.getText().length()));
 }
 @Override
 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
 // TODO Auto-generated method stub
 }
 @Override
 public void onTextChanged(CharSequence s, int start, int before, int count) {
 // TODO Auto-generated method stub
 }
});

Are new instances of textviews wordCount and CharCount created each time the listener is invoked? Would it be better to make them global?

How is memory handled? Lets say new instances are created, how does that affect memory?

asked Jan 10, 2016 at 23:43
5
  • 1
    Do the answers to Is repeatedly instantiating an anonymous class wasteful? on SO answer your question? Commented Jan 11, 2016 at 0:05
  • 3
    Without knowing the implementation of findViewById() we cannot say for sure. Commented Jan 11, 2016 at 1:18
  • by "each time the listener is invoked", Do you mean when addTextChangedListener is called? Or when afterTextChanged is called? Commented Jan 11, 2016 at 2:21
  • @Caleb For argument, lets say both. Commented Jan 11, 2016 at 3:42
  • For afterTextChanged context, @FlorianF answer bellow is correct. For addTextChangedListener context, @Snowman context is correct. It depends on if the findViewById creates a new instance or not. Commented Jan 11, 2016 at 22:04

1 Answer 1

3

The variables wordCount and charCount are created and initialized only when the TextWatcher object is created and added as a listener. No new instance is created every time the text changes.

answered Jan 11, 2016 at 2:39
1
  • This answer is correct. I wonder why it got downvoted. Commented Jan 11, 2016 at 9:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.