J
J
jonasas2015-03-13 10:37:56
Android
jonasas, 2015-03-13 10:37:56

Pattern for accessing the active instance of a class?

Please tell me some design pattern for accessing the active class instance. For example, in Android, you need to access some Activity or fragment from the service.
The only thing that comes to mind is a static field of the class, in which the reference to the object is written when it is created / active. But I think this is the wrong choice.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rishad Mustafaev, 2015-03-13
@TheRishka

I advise you to read about Dependency Injection. There are good tools for working with this:
Dagger - an article on Habré about it
RoboGuice - an article on Habré about it
Perhaps this is exactly what you are looking for. If you need a fragment context, you can get it from the activity context. Activities can be obtained using DependencyInjection. This is done differently depending on the instrument.

FragmentManager fm = myActivity.getFragmentManager();
Fragment f = fm.findFragmentByTag("MyFragment");
TextView textView = (TextView) f.getView().findViewById(R.id.myTextView);
textView.setText("bla-bla");

In general, describe in more detail: for what purposes do you want to do this? I must say right away that this is a very bad idea - to store links to Activity somewhere.

I
IceJOKER, 2015-03-13
@IceJOKER

As you wrote - we add a static field, i.e. pattern Singleton (Singleton)
in onCreate we assign instance = this;
and add the getInstance() method; which returns this field

C
Copperfield, 2015-03-13
@Copperfield

Use Binding to transfer from service to activity/fragments

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question