How to use Android getString () without violating the basic principles of OOD?

I need to use getString () from most modules in my application.

But for some strange reason, this is tied to the Application or the Context , so this means that I need to pass each class in my application a link to the application as a parameter.

This clearly violates one of the most basic principles of object-oriented design.

Is there any way around this?

+4
source share
3 answers

Yes, there is a workaround - if you (or you can) pass the View constructor (any derivative of the class) and assign it to a data member, you can access string resources from anywhere in your class:

String str_via_res = yourView.getContext().getString(R.string.str_via_res); 

Otherwise, you will have to pass the context to each class that needs access to these string resources.

+4
source

The β€œstrange reason” is that since string resources are tied to your application, there is no way to access them without any descriptor (context). If most of your non-action classes need access to string resources, you can rethink your design a bit. An easy way to not depend on Context is to load strings and pass them to classes in the constructor.

+6
source

you can extend the android.app.Application class to create a static method to pass context to all classes in your application.

Contact: PhoneApp.java

+2
source

All Articles