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."
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've been working on android for few months, during my spare time, so probably i'm going to ask stupid questions.
In a class, I create an object, for example a button, and I'd like to 'reach' it from others classes.
Of course i could do it this way:
public class CreateButton{
public void createButton(){
Button myButton = new Button(context);
//I can "pass" my object to another class this way
ManageButton manageButton = new ManageButton(myButton);
// or this way
manageButton.writeButtonTextMethod(myButton);
}
}
or this way
public class CreateButton{
public Button createButton(){
Button myButton = new Button(context);
return myButton;
}
}
public class ManageButton{
public void writeButtonTextMethod(){
CreateButton createButton = new CreateButton()
Button myButton = createButton.createButton();
myButton.setText("W");
}
}
I'm wondering if there's a way to 'reach' myButton, created in createButton.class directly from ManageButton.class (and other classes).
With the code above, I have to 'call' createButton.class from ManageButton.class or vice versa to be allowed to manage myButton.
I can do it making myButton static, but it's not correct make view static.
For example, i can easily reach variables created in a class that extends Application. Is there something similar for views?
Much people/guides/articles claim is possible and correct sharing objects (and fields) between activities by using Application, this way:
Such people are idiots, as myButton will introduce a memory leak unless this is done very carefully.
So, I'm still not sure how i should share objects (TextView, Button, ImgaeView etc.) among different activities.
You don't share widgets between activities. At most, you share model data between activities (or, better yet, pointers to centrally-stored model data).
In a Web app, you do not share DOM nodes between Web pages, as that is not possible. At most, you share data passed as GET parameters and the like between Web pages, or you store data in local central storage (cookies, local storage, IndexedDB, etc.). Android activities are like Web pages -- they are loosely coupled.
If you have pieces of your UI that are so tightly coupled that they absolutely need to share widgets, they should not be separate activities.
Views are not meant to be shared across Activities. Even if you do disregard this and share them, you're more than likely to run into a WindowManager$BadTokenException, which essentially means you can't alter Views outside of its parent Activity.
However, to answer your question in a more general way about sharing non-view objects, the Application class is the right way to go. However, making the objects static is not the right way to do. Instead, make them instance variables, and access them in in your various activities by using:
Application application:
//Below line is in onCreate()
application = this.getApplication();
After that, simple access it using
application.myObject; //Or you could use getters and setters. Your choice.
Not quite sure why would u like to share one button between two activities?!
It is either button in ActivityA or ActivityB? No need, or use to do it..You shouldn't do it.
EDIT: This is more Java Basics topic then Android.. And from what I understood, u call "class" something that IMHO is method (because u can't CALL the class and because what did you described).
Best advices I can give u here:
Study Java basics (methods, classes, objects, constructors, inheritance..),
Study Android basics (simple examples with 1 activity til u understand it good),
Make MyButton Class which will extend standard button,
Create button(s) and change their properties
This few tasks will make u busy for some time. Take it easy because it will be easier later with complicated apps. Hope I helped you. Cheers
EDIT2: In last example u wrote (in comments to this answer), nothing make sense because as we wrote u before u don't share button between two activities. Pause! Read it again: You should't share button between two Activies. Questions u asked are not clear because for A and Z u can't say just class and "share" button between them. Which class? no line of code written so it is really difficult to figure out what u want.. :s
LAST LAST EDIT: Man.. Please understand that u r missing basics of Java. No bad intentions here, just try to guide u and tell u exactly what u should study. Why? Because it doesn't surprise me that you are confused to explain what u mean when classes are with one method named exactly the same.. They are just objects "doing something", u want to "manage" them by adding variable in constructor which doesn't exist etc.. Learn, next time write immediately code to save time for all of us. Cheers and enjoy learning
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.
i am new in android and java ... i am reading from couples of day about android parceling tutorial for transfer data or variables values from one activity to other or one class to other ... but i am not so understood about that.
can u tell me that is it necessary to use Parcelable for this purpose because same task can also be perform using static key word for variables as string,int or array type then why parcelable pls explain in detail ..
thanks for explanation in advance please provide comparison with example
While technically both approaches will work, there are a couple of flaws.
The first is that the static variable is static. If you have two instances of the same activity, they will both reference the same static object. This is probably not what you want.
Secondly, it's considered bad practice to access global variables. It makes it difficult to see what is going on, is difficult to test and you someone (another class) can modify your data. This creates some horrendous bugs.
By passing the data via a Parcelable object it is very clear what you are doing and you avoid both of these problems.
Note that this advice is not specific to Android, rather to Java and programming in general.
Static references never get garbage collected so you end up creating something called a memory leak.
You are keeping an object in memory that you don't need and it can't be freed up.
If you instantiate enough objects like this you will get an out of memory (oom) exception which will cause the app to crash.