Vincent
Vincent

Reputation: 6188

Access Activity in a static way

I have an activity which has a static method for updating a textfield. This way I can update this view from another activity.

But now I'm trying to get a Context variable in this static method which is not possible. I've tried declaring a Context variable and initialising it in onCreate ( context = getApplicationContext();)

But still I can't access context in this static method. How is this normally done?

edit: a little bit more information about my situation. I'm starting a countdowntimer in an activity(a) which updates another activity's(b) ``textfield every second. And it does this by accessing b's setTextField in a static way..

Upvotes: 0

Views: 1207

Answers (6)

ddewaele
ddewaele

Reputation: 22603

Whenever you're busy with Activity A, there's no point in updating something on Activity B as it is simply not shown to the user at that point in time.

Seems to me you need to have some kind of global variable here that can be picked up in the onResume of Activity B.

Checkout this question : How to declare global variables in Android?

It shows you how to use the Application class to maintain global application state, accessable from all activities when needed.

Upvotes: 0

Priyank
Priyank

Reputation: 10623

Can you do something like this?

something like this <viewobj>.getContext()

Ref: How can I start an Activity from a non-Activity class?

Upvotes: 0

senola
senola

Reputation: 782

I would suggest the LocalBinder pattern to update the other Activity: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html

Upvotes: 0

Erich Douglass
Erich Douglass

Reputation: 52002

How is this normally done?

Accessing a TextView via a static method is not the best way to update the field from another activity. If you want to pass a value to the activity when it starts, you can send data via the intent (i.e. intent.getExtras). If you want to pass data back from a sub-activity, you can use startActivityForResult.

Upvotes: 3

Nanne
Nanne

Reputation: 64399

You might want to check some documentation on OO and using static functions. It is not considered a very good approach.

But as we are not talking about a better complete sollution: you can add a parameter with a context to the function, and just give it when you call the function :)

Upvotes: 0

Olegas
Olegas

Reputation: 10507

The way you are going is very strange. Why are you trying to change one activity content from another? May be you need to use startActivityForResult to strat a new activity and then return result from it and change views depending on it?

Upvotes: 1

Related Questions