Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I get why Android requires you to pass a Context object when trying to get a view for example, show a Toast, etc.
However, I don't really get the point for requiring it to access resources that could be shared by different Contexts in your application.
I several times found myself trying to access a resource from a utility class using a static method or something along those lines, and find it pretty annoying to require a passing of a Context param.
I fail to see where something could go south with this.
From the official documentation :
Interface to global information about an application environment. This
is an abstract class whose implementation is provided by the Android
system. It allows access to application-specific resources and
classes, as well as up-calls for application-level operations such as
launching activities, broadcasting and receiving intents, etc.
In clear, the context is the middleman between the telephone resource, and your code. And it seems logical, that you cannot access to this from everywhere.
The reason you can only access to Context in Activity and Application classes, is because both derives from Context :
java.lang.Object
↳ android.content.Context
↳ android.content.ContextWrapper
↳ android.view.ContextThemeWrapper
↳ android.app.Activity
Extend Application class by your own public class MyApp extends Application and register MyApp in your manifest and have MyApp something like this:
class MyApp extends Application {
...
private static ApplicationContext context;
#Override
public static void onCreate() {
super.onCreate();
context = this;
}
public static String string(int resId) {
return context.getString(resId);
}
}
Then you can do MyApp.string(R.id.mystring) from everywhere. You can do the same for other resource types.
You can also do (MyApp)getApplication() if you prefer so.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 months ago.
Improve this question
I was always facing this memory leak warning without paying much attention to it, but now I'm looking into how to deal with it and, as I know I shouldn't use WeakReference and that sort of "tricks" to avoid it, come to what I think could be a possible and simple solution.
My idea is as follows:
I have a singleton class (object) which holds all my app configuration, where I initialize a context from the Application class like this:
object AppSettings {
lateinit var context: Context
fun init(appContext: Context){
this.context = appContext
}
/* OTHER STUFF */
}
typealias aw = AppSettings
#HiltAndroidApp
class AWApplication : MultiDexApplication() {
override fun onCreate() {
super.onCreate()
AppSettings.init(this)
}
/* OTHER STUFF */
}
I initialize that context not only in ApplicationClass, but in every activity OnCreate (which inherits from BaseActivity):
#AndroidEntryPoint
open class BaseActivity {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppSettings.init(this)
}
}
And finally, I can access context wherever it is needed as follows:
object RandomObject {
fun DoWhatever() {
PlayAFreddieMercurySong(aw.context,)
}
}
Well, this is my possible solution and I would like to know Android gurus from SO opinion about it.
Maybe I'm leaking memory in my App Settings -where I had initially store context-, but Android Studio is not complaining about it, so I am not sure.
In the end, I'm trying to avoid passing context as a method parameter in every place it is needed for code simplicity.
"other stuff" are common between all activities and they need just ApplicationContext, then why you don't use application context in AppSettings. and thats it. BTW your solution will not leak, if and only if you call your AppSettings.init(this) in all activities.
and you don't guarantee that .
in other words "the code doesn't leak now but may be in the future" - vulnerable
if you have functions thats related to activities, fragments or any
class you want, you can use extension functions for that
you should create a kotlin file with name for ex ActivityExt. and write all of your cases that you need for activities . if you need functions for fragments you should also create another kotlin file with name FragmentExt..etc
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I have a repository called LocationRepository the code of LocationRepository is
class LocationRepository(
private val context: Context
private val api: AppApi,
private val db:AppDatabase
) : SafeApiRequest() {
}
here you can see that I am passing a context inside through the primary constructor need for that is I have to convert a bitmap to base64 from its Uri you can see the suspended fun below
suspend fun submitLocation(location: Location,employee: Employee) : LocationUpdateResponse{
}
you can see here I am passing location which contains the Uri of the image I have to convert the Uri to base64 before API call, is this best practice or bad?
It's neither a best practice nor bad. Having context there is necessary some times especially when you need it for accessing your database, your shared preferences or getting some resources.
If you need the context to live in your repository, you need to be sure you are using the application context. If you are using an activity's context, then you would leak your activities when the activities go away but the repository is not.
Both Activity and Application context are very similar as to what they are providing. The difference is that Activity context is tied to the activity's lifecycle where the application context is tied to the application lifecycle.
Now, since the application will live as long as your repository then it's fine to use application context in your repository.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Even though I create a static class to hold the database helper instance, I'm confused as to where do I instantiate the class. And how do I ensure that only one instance of the class is available?
What I meant to say is, I'm confused in which activity and how should I be instatiating the class for it to remain one instance?
Not sure why the downvotes.
Initially, I had a
public class DbStaticClass {
public static LinkDataHandler sqlDataHandler = null;
}
Which I intialized at Splashscreen as that's the entrant activity. But it always caused multiple instances of Sqllite db. Hence, I'm confused where do I do it?
But it always caused multiple instances of Sqllite db.
You can't have a Singleton class in Android, because the life cycle of Android Activity class (and even the Process) is not tied to the life cycle of the Application, Android can instantiate and destroy your Activity at any time. Instead of Singleton, you want write a Borg instead; instead of relying on there being exactly one instance of the class, multiple Borg instances should behave with a hive mind.
How do I ensure that only one instance of the class is available?
It seems you are defining singleton in a wrong way. Singleton itself ensures that only one instance of the class is available. The right way to do is:
public class SQLiteBaseClass extends SQLiteOpenHelper {
private static SQLiteBaseClass mInstance;
private SQLiteBaseClass(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static SQLiteBaseClass getInstance(Context c) {
if (mInstance == null) {
mInstance = new SQLiteBaseClass(c);
}
return mInstance;
}
}
Now, wherever you need to do database operations simply call SqliteBaseClass.getnstance()
For detailed desription you can read my blog entry here
This question already has an answer here:
No enclosing instance of type ... is accessible
(1 answer)
Closed 9 years ago.
I am trying to implement the solution for a previous question that was proposed by user
Kevin Galligan. However, I keep getting the error "No enclosing instance of type LolCat is accessible. Must qualify the allocation with an enclosing instance of type LolCat (e.g. x.new A() where x is an instance of LolCat)" when creating the new instances of LolCat and LogcatOut inside my OnCreate.
Sorry for creating a new question for this but I don't have the required reputation to add comments to the older post.
I don't see a reason, why the inner class LogcatOut would need access to the enclosing instance. So you could try to make it static:
public static abstract class LogcatOut {
...
}
and the error should go away.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the meaning of “this” in Java?
I'm still very new to learning Android programming, and I noticed that "this" was used often in parameters for method calls in the language. I'm following The New Boston tutorials through YouTube, but he never really explains quite detailed enough what the 'this' statement means. Can somebody please explain it to me? Maybe dumb it down a bit?
this refers to the instance of the class you are currently coding within.
You cannot use it in a static context because in this situation you are not within any object context. Therefore this doesn't exist.
public class MyClass {
public void myMethod(){
this.otherMethod(); // Here you don't need to use 'this' but it shows the concept
}
private void otherMethod(){
}
public static void myStaticMethod(){
// here you cant use 'this' as static methods don't have an instance of a class to refer to
}
}
In android class.this is used to pass context around.
Formal definition of context: It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities.
That means if you need to access resources (including R and user interface) you will have to use context.
In java this means the instance of the class that you are in. For example MainActivity.this points to the current instance of the MainActivity. So by using MainActivity.this.foo you are accessing the foo field of MainActivity class.
public class YourClass {
private int YourInt;
public setTheInt(int YourInt) {
this.YourInt = YourInt;
}
}
"this" is used to see whether an attribute or function belongs to the class we're working on, clearer.
Also, you see that setTheInt operation gets an integer named as the same as your attribute. In that function's namespace, YourInt is not this class's YourInt, but a reflection of the integer coming from setTheInt's calls. "this" helps here to divide the outer and the inner "YourInt"s.