According to this answer or the android's documentation there is several ways to get the Context in an app and pass it to an other class/method/whateveruneed.
Let's say I'm in the Foo Activity and in need to pass the context to Bar's constructor.
Bar bar = new Bar(Foo.this);
Bar bar2 = new Bar(this); //same as first i guess
Bar bar3 = new Bar(getApplicationContext());
Bar bar4 = new Bar(getBaseContext());
Bar bar5 = new Bar(MyApp.getContext); // get context statically
Taking into account of memory leaks, speed , general performance , what will be the better way between all those possibilities ?
You should check out this question - which basicly covers the same as yours.
Also the Developer Docs on Avoiding memory leaks gives you a decent explanation of some situtations in which various of the methods are reasonable to use.
I think that this post will provide you enough information. Look at the first response.
Difference between Activity Context and Application Context
You would probably want to use this. It is the Context of your current Activity (Which is a context) and has shortest lifecycle. But be aware of the memory leak that could occur.
http://developer.android.com/resources/articles/avoiding-memory-leaks.html
I have not any direct answer to your question.But if you compare Foo.this and this then better to use first one as sometimes (in nested class case) second one will show error.
For more discussion on it go through that link
Using Application context everywhere?.
Hope it will help you
Android memory management. It covers all the aspects of Android memory management.
For context explanation this is a good answer.
Another good explanations of context.
Related
I need to use Toast.makeText(getApplicationContext()). The getApplicationContext() is what I am really after. I need a specific tutorial on passing Context around. Any sugestions? I see alot of developers answering questions with techo-speak like this and I would seriously like to advance to that stage. I have run into passing Context issues way too often and would like a deep understanding of this. Until I get this type of knowledge I will always consider myself a noob.
Thanks.
Do you have a problem with Activity being a Context ? (Activity.this)??
Android already does that for you so why do you want to bother your head.? When you create a View the Context is passed to the View eg; TextView textv = new TextView(Context); you can later retrieve that Context with View.getContext(). Honestly Context are everywhere so why do you really want to use the getApplicationContext(); why not getBaseContext()
Whenever we need a reference to the widget, we uses findByViewById.
When we are referring the widget lots of time in the code of the same Activity class, we can follow either of the approach:
Call findViewById every time in Activity lifecycle.
Get it first time, store the reference as a private instance variable of the Activity class.
Which approach is beter? What would be pros and cons of each approach in terms of performance and memory. Please help.
EDIT: If we move to new activity from A to B, we do not finish A as we want to open A on pressing back. In this scenario how to approach above problem? Please help.
Both approaches have their risks. In general, you should call findViewById() the less times you can, by the other hand, storing a reference on the Activity class may lead to memory leaks. It depends so much on what you want to do, how much times are you calling it and basing on it choose one of the approaches. For that, you'll need to analyze your code and if you're not clear about which is better, just try both and choose the "less bad", but generally the first approach is worse than the second one because you know you'll always have to find across ALL elements you've defined an id.
Most developers use method 2, mostly because its more effective. If your layout is complicated then findViewById must traverse its tree to find given widget which takes time. In list views you mostly use ViewHolder pattern which allows you to store references to list item widgets. Since lists are redrawn very ofthen this greatly speeds up its rendering.
Storing widgets in private references is quite safe, those references gets invalidated on configuration changes, but your activity is also destroyed then.
The second possibility is clearly the better.
findViewById iterates through the whole view hierachy, which of course costs much more time than a reference.
Dianne Hackborn (Android engineer) gave some details about the topic here: https://groups.google.com/forum/#!topic/android-developers/_22Z90dshoM
Accessing a member variable is always faster than any function call. The used space for that variable is insignificant.
By the way: The code looks much cleaner!
You should decide this according to your purpose. Holding an object for your views are faster than getting your view with an activity method. But this also means that you are using a memory for your reference and it can cause a memory leak.
I may be wrong since i am new to Android, but i prefer storing a a variable;
it's less coding to write.
for example: if you have to access an imageview that is nested in layouts how would you wish to access it and get its tag.
Access 1:
public Integer getTag(){
FrameLayout frame1 = (FrameLayout) findViewById(R.id.frame_1);
LinearLayout linear3 = (LinearLayout) frame1.findViewById(R.id.linear_3);
ImageView imgView = (ImageView) linear3.findViewById(R.id.myImg);
return Integer.valueOf( imgView.getTag().ToString());
}
Access 2:
private ImageView myImageView;
#Override
public void onCreate( Bundle savedInstanceState){
//set access to variable
}
public Integer getTag(){
//return Integer.valueOf( myImageView.getTag().ToString());
//can be written
Integer mTag = Integer.valueOf(myImageView.getTag().ToString());
return mTag;
}
I have been creating Spinner controls (Combo boxes/Drop downs) in one of my apps, and was surprised to find out how difficult it was to achieve all of the following features:
User facing Strings are externalized, taking advantage of strings.xml internationalisation (I18N) feature of Android.
Spinner selections operate using a System view, which facilitates not having to work with or map Strings to meaningful values (yuck).
User view to System view mapping should be easy, automated and minimal (i.e not hand rolled for every component).
Others have attempted solutions to this, but universally as far as I could see they suffer from one or many of the following problems:
UI code is creeping into their enum class which doesn’t belong there (messy), nearly all existing solutions suffered from this.
Hardcoded User facing Strings in their enum classes. Because these are not externalized you cannot do I18N using the stock Android features.
Authors typically make the Fragment or Activity an OnItemSelectedListener which perpetuates a common problem of inheritance for convenience, where composition is more appropriate.
I have developed my own solution which does this: http://www.androidanalyse.com/android-spinner-externalize-user-strings-mapped-to-system-enum/
My question is, have I missed something? This seems like something that should not have been this hard (which makes me feel like I'm possibly reinventing the wheel).
Below is some example code showing my solution in-use (which is available Apache 2 license from the link above).
String none = getString(R.string.none);
String light = getString(R.string.light);
String medium = getString(R.string.medium);
String strong = getString(R.string.strong);
SpinnerUtil.createNewSpinner(view, R.id.wind, Arrays.asList(none, light, medium, strong), WindLevel.values(),
new SpinnerItemSelectedListener<WindLevel>() {
public void onItemSelected(Spinner item, WindLevel value) {
// Take whatever action you wish to here.
}});
I would just use ArrayAdapter<WindLevel>. Yes, you created a custom typed listener, but the regular event listener gets the position and can call getItem() on the ArrayAdapter<WindLevel> to get a WindLevel properly typed.
IMHO, the vast majority of Spinner widgets will be populated with material read in from a database, the Internet, or some other dynamic data source, rather than populated by some sort of enum with display values coming from static strings that can be internationalized ahead of time.
This is not to say that your code is useless: if you find it useful, then it was worth writing. And I am sure that there are apps out there that contain your targeted pattern (i.e., a Spinner backed by an enum or equivalent where the display values are known in advance and can be internationalized) who might find your solution useful as well. Every developer who writes enough code cooks up these sorts of helper classes and the like that help map an OS or framework model into something that better fits the developer's own mental model. So long as you are not perceiving any performance issues, it's all good.
Also, note that OnItemSelectedListener is an interface; implementing that interface on an existing class is not inheritance.
I believe the reason nobody answered you is :
What problem are you trying to solve ? Spinners existed prior to your well designed attempt.
Why reinvent them in exactly the same way they exist in Android ?
http://developer.android.com/guide/topics/ui/controls/spinner.html
It is a beautiful wheel indeed you designed, but still, it is just a wheel :)
UPDATE :
I think I begin to understand what you did. This is interesting. I'm not sure why you did not go to the pattern implemented by the ListPreference with its entries and entryvalues.
In fact, I'm not sure I understand why the Android team did not go that route either.
In any case, it is worth proposing your idea to the Android framework. It is after all open source.
I want to load an asset and the only way I can see to do that is with
Context.Assets.Open();
I don't see a way to get access to Context without passing it around. I really don't want to pass it around
To answer my own question:
Application.Context.Assests.Open()
is what I was looking for. For some reason I just couldn't see it.
I have a class where I am getting context objects from more than 10 activities.
I want to know the context object of which activity is at the instant.
I have tried the following but no results.
context.equals(One.this);
context.equeals(One.class);
If any one having any idea please share with me!
I hope you aren't holding on to these Context references longer than necessary, I found out what a wonderful source of memory leaks this can be if not handled correctly!
If they are all Activity instances you can treat them as such and use:
if ( activity instanceof MyClassActivityOne ) {
// do something
}
Ten activities seems like a lot to have at once.
What are you trying to do by comparing context objects? Sometimes the answer to the question
"How do I do this?" is "Don't do this! Tell us what you want, and we'll suggest another
path to follow."