qwerty
qwerty

Reputation: 5246

Android/Java: Change view from another class?

There are two classes. MainActivity, in which i set the view, and ClassX from which i want to update a view in MainActivity. ClassX is an AsyncTask called from MainActivity, if that's relevant.

What i want to do is to change the text of a view called mainTextLog. I've declared a global TextView variable, and in the onCreate() method i set it to the view using findViewById().

private TextView logger;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    logger = (TextView) findViewById(R.id.mainTextLog);

}

By now i should be able to change the text from onCreate(), and i can. But since i want to change it from another class (ClassX) i need to create a method for it:

public void setLogText(String text) {
    logger.setText(text);
}

But it doesn't work. I've tried making logger and the setLogText() method static, but it still doesn't work. The app just crashes.

It's probably pretty easy, but i'm out of ideas.

Upvotes: 0

Views: 4530

Answers (3)

GHz
GHz

Reputation: 471

I've done this plenty in the app im working on, its sort of an MDI type app on the android tablet.

To do what you're asking....

in MainActivity have

public static void setText(String txt){
  ((TextView)findViewById(R.id.mainTextLog)).setText(txt);
}

then in the child (or calling class) call it like...

MainActivity.setText("myTextToShow");

That's it... im using android api level 12... If i remember correcty it worked in api level 7 as well though.

Hope this helps...

Upvotes: 1

reconditesea
reconditesea

Reputation: 146

One possibility is that: when you call setLogText in another Class X. The MainActivity may not be existing anymore, which makes the logger a null reference?

Upvotes: 0

Matt Wolfe
Matt Wolfe

Reputation: 9284

If you are using an AsyncTask you need to set the value in either onProgressUpdate or in onPostExecute.

You really should read the documentation for AsyncTasks

You CANNOT update the UI from the doInBackground method as it is not run in the UI thread and will give you an exception.

Also, you should post the exception you are getting when the application crashes so we have a better idea what the problem is. But I'd guess you are trying to update the text from the wrong thread.

Upvotes: 1

Related Questions