S
S
sitev_ru2015-10-11 08:52:24
Java
sitev_ru, 2015-10-11 08:52:24

How to get the object of a neighboring activity?

I create several activities, and store the objects on them in a class derived from the application class in the form of static variables:

public class AppGlobal extends Application {
    static LoginActivity loginActivity = null;
    static MainActivity mainActivity = null;
    static FuncActivity funcActivity = null;
}

Now I can, for example, access loginActivity from mainActivity like this:
AppGlobal.loginActivity
This approach was temporary while learning Android programming. And the question arises: is this the right approach? Surely, it is possible to work without such a global class and static variables?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Copperfield, 2015-10-11
@Copperfield

This is the worst thing that could have been done.

A
Andriy Biskup, 2015-10-11
@AndriyTheProgrammer

If you need to call methods from another Activity from one Activity, this is already a "smell" from the code. Ideally, an Activity should be responsible only for the visual representation of the application within itself and only itself, and not pull the rest of the Activity. At one point in time there is only one "live" Activity and somehow managing others is a very bad idea.
It is possible to create logic similar to the one you described above using fragments. In this case, there will be one Activity (analogous to your Application) that will contain fragments in the form of ordinary variables (not static!), That is, the methods of which you can call without any remorse.
Fragments are generally a very useful and powerful tool, it is unlikely that even a Junior will hire you if you do not know how to use them. You can consider this a kick in the direction where you need to google

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question