Is this a strange way to create an Intent? - android

I have a Library Project and a project each for the free and paid versions for one of my apps. In the Library project I have a 'Base Activity'. This 'Base Activity' must start child activities depending on whether it's the free or paid version.
What I did was just before I fire the intent with startActivity() I call a method in 'Base Activity' which must return the intent. I override this method in my 'Base Activity' subclasses (the paid and free versions) and create the intents like this:
return new Intent(subClassOfBaseActivity.this, ChildClassA.class);
and:
return new Intent(subClassOfBaseActivity.this, ChildClassB.class);
Now, my question is, it is ok to create the intent by passing it subClassofBaseActivity.this instead of BaseActivity.this ?
Is this method ok overall?

When you create a new Intent you need to pass the Context and the Activity.
Now the context is an interface which allows the application to access some resources.
Basically in your case , you're passing a context and activity as it supposed to, but you ask if you need to pass the baseActivity as the context.
So basically I think that because of this line in android developer:
Interface to global information about an application environment you need to pass the base activity as the context..
on the other side, the subClasses are probably inherit from the baseClass so the context should be the same, but it will be more readable and clear when you passing the baseClass as the context.
for more information about Context
http://developer.android.com/reference/android/content/Context.html

Yes, it is ok. This constructor take a first parameter Context which Activity extends. So basically you are passing argument as Context not as an Activity.

Thats fine.
Java will cast the first argument into Context (Activity extends Context) so it doesnt matter. You can also put getBaseContext() insteat of Activity.this there..

Related

how does startActivity(this, OtherActivity.class) use Context object to start an activity?

I started reading about Context And I am a bit confused.
I found the following definition.
The Context class is an “Interface to global information about an application environment.”
here I am not understanding what android application environment is?
we can use 1. getAssets() 2. getResources() 3. getPackageManager() 4. getString() 5. getSharedPrefsFile() methods ,we can also start an activity ,broadcast an Intent using Context.
I think,The above methods(bolded) provide app's global data to the app,
Are these Resources known as App global data?
So for starting activity ,what global information is used by Android
System?
How does a View use Context (what information it gets from Context)?
I am so much confused about the concept of Context class and how all these things are related.
Please provide any help.
Please go through Context details. I think these things can help you understand the idea of context.
View.getContext():
Returns the context the view is currently running in. Usually the currently active Activity.
Activity.getApplicationContext():
Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.
ContextWrapper.getBaseContext():
If you need access to a Context from within another context, you use a ContextWrapper. The Context referred to from inside that ContextWrapper is accessed via getBaseContext().

does it guarantee to give same result in getDefaultSharedPreferences within Context?

I read this discussion but still have a question.
If I use getDefaultSharedPreferences(getApplicationContext()) and getDefaultSharedPreferences(SomeActivity.this), does it gurantee to give same result (same xml preference file access)?
yes it does. The context parameter is used to get the package name, that will be used as name for the xml file in which android stores your values. You can see the androis's source code here
Wishing you a happy new year-2014
Both will behave same !!
View.getContext(): Returns the context the view is currently running in. Usually the currently active Activity.
Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.
ContextWrapper.getBaseContext(): If you need access to a Context from within another context, you use a ContextWrapper. The Context referred to from inside that ContextWrapper is accessed via getBaseContext().
Please Note that behind the scenes
getDefaultSharedPreferences(context)
calls
getSharedPreferences(context.getPackageName(), MODE_PRIVATE)
as far as I understand: Context is the Base Object. So every Activity same as Application derives from Context. This means that every Activity and every Application IS a Context;
Hope now you understand the things so we can say that they will produce same behave.
Please refer http://developer.android.com/reference/android/app/Activity.html
and
http://developer.android.com/reference/android/content/Context.html

Is it safe to use reference to the Application where Context is required?

As it stands we need to pass a Context in many places within Android application. I'm wondering how safe it is to use a static variable which refers to the Application class instance in such places? For example, I have a static method in one of my Activities and I can't use this (as Activity) or something because the method is static, so I'm guessing to use the Application.instance reference which is initialized on each application start. Is it ok you think? Thanks a lot.
It depends on your method and what you are trying to do with the Context. If you want to get resources like a String or Drawable from your app, then it is save to use the Application Context. But if you want to display a Dialog, then you definitely should use the Activity Context.
As far as I know, for a Toast you can use the Application Context as well.

Static Utility class with Context/Activity - Android

Over the development of an Android app I've come to a collection of utility-type methods that I have put into a static class. All these methods are used across multiple Activities and most of them do not require any information from the calling Activity.
However, I now have some methods that require the Context of the Activity and one that requires the Activity itself. Let me exemplify some of them:
getDeviceNaturalOrientation() - Uses an Activity's
getWindow().getWindowManager().getDefaultDisplay() to access the
displays rotation, width, and height to determine the device's
natural orientation.
getDeviceOrientation() - Similar to the above but to get the current
orientation
createFile() - Uses the Context to to access some resources (strings) and to
create and show some Toasts
Now, my big questions regarding this Utils class are:
So far, each function takes a Context parameter which I pass from whatever Activity I'm on, but would it be OK to create a static Context or Activity variable in the Utils class and set it at the beginning of each Activity (like in onCreate)? This variable would be used in whatever functions require a Context or Activity instance.
Assuming the above is not recommended, is it OK to pass an Activity parameter to a method or is there a reason to only pass an Activity as Context? The methods I use for the device orientation functions above are specific to Activity objects, not Context, so either I pass as Activity or pass as Context and cast into Activity (the latter sounding like a terrible idea).
Also, I am very open to the idea that this Util class may not be the way to go for these methods that require Context/Activity, so I would welcome alternatives that would still prevent having copies of these methods in each activity class that uses them.
1)A static link to a context is likely to cause a memory leak. It means that a reference to the Activity will be kept around in the static variable even after its destroyed, so all of the memory of the activity and all its views will remain valid and not be cleaned by gc. You can do this, but you have to be careful to null out the variable when done. Its better just to avoid it.
2)Its a little bit awkward to pass the activity as an Activity, but no technical reason not to. At that point we're arguing over code cleanliness/maintainability. And there are times where the non-clean solution is just easier. Of course in the cases above I'd rather pass the orientation/display/Resources objects to the function than pass the entire context or make special accessors.
I think following design should be fine when you call from Activity
MyUtility utility=new MyUtility();
utility.getDeviceNaturalOrientation(this);
utility.getFile(this);
And you can define these function like
public int getDeviceNaturalOrientation(Activity activity){
//code
return some_oreientation
}
and like this
public File getFile(Context context){
//code
//return file handler
}
Activity is the subclass of Context so you can even change the design to following
MyUtility utility=new MyUtility(this); //this refer to Activity
utility.getDeviceNaturalOrientation();
utility.getFile();
As long as you pass activity you are fine but if you do following from your activity you will get error from first method call
MyUtility utility=new MyUtility(getApplicationContext());
utility.getDeviceNaturalOrientation(); //will throw exception
utility.getFile();
And, yes first idea is not a recommended way.
I would suggest you to send a WeakReference of your Activity or getApplicationContext() (for those works which can work using it) and don't use static method because it cause memory leaks. Read Developer blog also

Pattern for access to conttext from java class (that it isn't activities)

In my android project I have some activity classes, and also simples java classes. There are some of them are independent of contextes and views totally, but in others duly I need it for to access a particular method of context.
I have read about it, and some people says they pass the context of some activity to every class that need its methods; others that pass a view and then get the context or that this classes have to extend of Activity... ¬¬
But for example, I have a class where it only calls once a method of context like:
getSharedPreferences(configNameFile, 0);
getString(R.string.text);
...
Therefore I would like to know what pattern do you use to do this always.
My personal favorite ways to do this is:
Dependency injection
using RoboGuice
or
Make sure you don't need the context
If possible, try to avoid using the context in other files then your activity. If it is really needed, I write a wrapper most of the time. E.g. for Settings, I write a Settings interface that is able to do it with shared preferences. Whenever you want to change your settings implementation later, it is easily done by swapping the implementation of your interface. If you really need it, I'd prefer using a static Application context
Also, you could make that method accept a Context paramerter, for example:
public void getPrefs(Context context){
context.getSharedPreferences(configNameFile, 0);
context.getString(R.string.text);
}
Then in your Activity pass the current context to it:
public void getPrefs(this);

Categories

Resources