3

I have a TextView in MainActivity, I would like to change the TextView text within another class.

How can I access TextView in MainActivity from another class?

I tried the following

TextView textView = (TextView) findViewById(R.id.myTextView);

textView.setText("Text");

But the app crashes when calling setText()

jkigel
  • 1,592
  • 6
  • 28
  • 49
  • You can check this link. http://stackoverflow.com/questions/6605588/changing-text-from-another-activity?answertab=active#tab-top – Mohammad Ullah Apr 05 '13 at 08:46
  • see this question http://stackoverflow.com/questions/10996479/how-to-update-a-textview-of-an-activity-from-another-class – Irfan Ul Haq Jun 17 '16 at 13:02

3 Answers3

9

You have to use runOnUiThread(new Runnable()...

See following:

import android.content.Context;

private class AnotherClass {
        protected MainActivity context;

        public AnotherClass(Context context){
            this.context = (MainActivity) context;
        }

        public void updateTV(final String str1){
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    context.textView.setText(str1);    
                }
            });
        }
    }
Community
  • 1
  • 1
Chintan Raghwani
  • 3,370
  • 4
  • 22
  • 33
2

If you want to update the text of the TextView a possible way would be to edit the text in a common data model that is shared by your classes. If onResume from the activity is called later it can read the new value from the model and update the TextView.

micha
  • 47,774
  • 16
  • 73
  • 80
1

I would recommend to use a handler to update the content of that Activity. This is only one way, there is multiple ways to do this.

The entire purpose of a handle is to have some background process/thread passing information into the UI thread.

JoxTraex
  • 13,423
  • 6
  • 32
  • 45