I have seen in many places android context is initialized twice ? Why is it required ?
For Example :
Context context;
context = null;
again they will initialize it to some values in onCreate, onReceive or in some other Method
context = myContext;
If anyway we have to initialize it to value, why then initializing it to null ?
Anything specific to Android ?
Thanks
compiler never assigns a default value to an uninitialized local variable.
If you cannot initialize your local variable where it is declared, make sure to assign it
a value before you attempt to use it. Accessing an uninitialized local variable will result
in a compile-time error.
Example:
someMethod(Context myContext){
Context context;
context = null; //Have to be done to avoid compile-time error
context = myContext;
}
Example 2:
private Context context;
someMethod(Context myContext){
context = myContext; //No initialization required, because context variable is not local
}
To Answer your question:
We are initializing variable to null to keep consistency intact
No, this is not Android specific, but rather Java specific
I would guess this is done of old habits only. Java should by default set field object references to null. I doubt Android handle this differently.
Setting them to null might even result in duplicate operations on byte code level. For further information refer to this page.
Related
I have an activity where i have to trigger from place to place a custom pop-up dialog which is also a singleton
From my activity i open the pop-up :
ScheduleDialog.getInstance().refreshContent(new WeakReference<Context>(this), new WeakReference<ScheduleDialog.interface>(this));
What is best ?
1) create 2 local references ( in ScheduleDialog ) like :
Context mContext = nContext.get();
2) keep both like weak reference and only when i need them use :
nContext.get();
This is related about leaks error/warnings
Thanks
If I see your code you create strong reference again after get weak reference value in Context nContext variable. So need to follow below process if you want to implement weak reference concept :-
define global class variable :-
private final WeakReference< Context > nContext;
set value in global variable through passing from another area
nContext = new WeakReference<Context>(nContext);
and then
if (nContext.get() != null)
// code
}
https://medium.com/google-developer-experts/weakreference-in-android-dd1e66b9be9d
You have to keep them as WeakReferences, otherwise the Garbage Collector will see there are strong references to the object and won't collect them, leading to the leak you mentioned.
Why do I get the error message The method getResources() is undefined for the type ColorObjectManager?
I use this line to load a Bitmap image:
orange = BitmapFactory.decodeResource(getResources(), R.drawable.pearl_orange);
It's working fine if I'm doing this in another class that I call GameLoop which I make an object of inside the MainActivity class. But it's not working when I trying to do this in the class ColorObjectManager which I make an object of inside the GameLoop class. Do you follow?
Why am I limited to just use this loading part in the GameLoop class and not in the ColorObjectManager class? I thought it would help if I passed the Context to the constructor of ColorObjectManager, but it didn't! I guess I'm missing some knowledge here where I can create objects and not. Can I get some help to sort this out? Thanks!
getResource needs a Context object. If you pass the context to ColorObjectManager you can retrieve resources with context.getResources()
I agree with the answer posted by blackbelt. Pass the activity context to the constructor of ColorObjectManager from your activity class.
new ColorObjectManger(ActivityName.this);
Constructor
Context mContext;
public ColorObjectManager(Context context)
{
this.mContext= context;
}
Then use the context to get resources.
Edit:
If you want to use the context only in your load method
public ColorObjectManager(Context context)
{
load(context);
}
To get access getResources() , Activity context is required. Your ColorObjectManager is not an Activity. So you need to pass the Activity context to this class.
Let's use custom or extending View as an example.
Is it more effective to save Context parameter from constructor as a field, than calling getContext() everywhere (supposing there are, let's say, 10 or more places where it is needed)?
Instead of using getContext() every where, it is better to pass current context as argument in constructor where you wanna to use.
View#getContext() is
class View {
protected Context mContext;
public final Context getContext() {
return mContext;
}
}
and a locally cached implementation:
class X {
private final Context mLocalContext;
public X(Context ctx) {
mLocalContext = ctx;
}
}
Now there is a very small difference when you use mLocalContext instead of getContext(). The JVM can get to the required reference of the context object without having to execute the method (which takes a tiny bit of extra time). That call can't be optimized away since View#mContext is mutable (can change). In the local example it can assume that mLocalContext can't change and optimize the code a little better. [Note: I am not 100% sure about what optimizations are / can be done]
The difference might be measurable if you use the context a lot but in this case it does not matter much. It's still a good idea to cache Objects locally if you need them often. Especially when their (re)construction takes time (e.g. when getContext() would create a new Context() or so).
It looks like, from the source code, the View's constructor stores the context parameter and that's what getContext() returns:
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/view/View.java#View.getContext%28%29
So, my instinct would be that storing the parameter yourself would be redundant, since the super class is already doing it for you.
I can't figure out why the context is getting passed in to this method: http://code.google.com/p/cloud-tasks-io/source/browse/trunk/CloudTasks-Android/src/com/cloudtasks/Util.java#119
The keys of the URL_MAP are the Contexts. So you need the context to get the base url.
I'm trying to declare some final Strings for using as keys later, but I keep getting a null pointer exception.
private final String KEY = getString(R.string.key);
This is declared at the top of my activity, before onCreate(). Does the problem stem from referring to R in the class?
The problem is, that you cannot access the getString(..) there.
Why dont you just save the int value?
private static final int KEY = R.string.key
and than where you need it call the yourContext.getString(KEY);
:)
These initializers will be called when the object is constructed, which may be before it has a valid context.
Don't call getString() before onCreate(). You won't be able to have the strings final, though.