What exactly does using the Application Context mean? - android

I'm new to this and I'm sorry if this is a really dumb question. I'm just trying to clarify things. My book says I can retrieve application context for process by using the getApplicationContext() method. I just really don't know where to type this or what to do with any of it. I can go to the hierarchy but what do I do with all the script there. Also where would I write Activity Callbacks, in the main.xml? An exercise wants me to add a logging tag to my project but I'm not sure how to do this. The exact text says:
"Within the onCreate() callback method, add an informational logging message, using the Log.i() method."
and another exercise says to:
"Implement some of the Activity callback methods in addition to onCreate(), such as onStart(). Add a log message to each callback method and then run the application normally".
As these seem like basic questions, can someone please help me.
I am using the Android SDK, and Eclipse. I have made the Hello World application, but I have no idea what to do with Context or Retrieving resources. Please help!

The first rule I would give you: if you don't know why you need it, you probably don't need it. Use your activity object as the Context when you need a context.
The callbacks you talk about are on the Activity class. The Application Fundamentals describes what an Activity is: http://developer.android.com/guide/topics/fundamentals.html#Components
The only time you want to use getApplicationContext() is when you need a Context that exists outside of the lifecycle of an Activity class (or other component). You'll want to find documentation on specific cases where this is desired, there is a lot floating around. For example this one is part of the Android documentation: http://android-developers.blogspot.de/2009/01/avoiding-memory-leaks.html

For the tasks you're working with here, you'll be using the Java code that defines the behavior of the application, not the XML files that define resources and layouts or the AndroidManifest.xml file that declares basic application properties.
If you're working with Hour 3 of the Sam's Teach Yourself... book, then you need to open the src\com.androidbook.droid1\DroidActivity.java file. In general, you would need src\<package-name>\<class-name>.java. When you open that file, you'll see a class (in this case, DroidActivity) that extends Activity and already has the onCreate() callback method. Anything that you want to happen during onCreate() goes inside that method. Other callback methods can be added inside the activity class. To see an example that has all the lifecycle callbacks (but doesn't do anything in them), look here.
A logging tag is just a string. You can declare it, for example, as a private static final String inside the activity class.
If there's confusion about where methods belong, where and how to define variables or constants, how to call methods, how to use classes, and so forth, then it might be best to go through an introductory Java text before starting with Android. There are plenty of free resources available for that.

Related

Android calling a method from another acitivt6 from a class

I have an activity named Create and a class names Begin .I would like to access the methods in activity using the class begin.
Hello #Ehtizad Zashkiyor ,
You can't really access another activity method, and the way that it is possible are not reccomanded.
it's better for you to try to make a java class with the methods you want and let both your activity get the methods form there.
from a quick search in google I found few questions that will help you:
how to call a method in another Activity from Activity
Call a public method in the Activity class from another class?
How to call another activity method in android studio? (this one is straight to the answer of it)
plus, it wont hurt you to read this: "Application Fundamentals" which is from the android developer website.
I hope this answers to your question, if you'll have any further concerns, don't be shy and ask.

android globally object reference for all activities

May be its simple question, may be its repeated question, this question s not for upvote and all.
I just want to pass my object from one activity to second and second to third activity. I know there are a lot of ways using shared preferences, Intent bundle from one to another activity.
The reason I want to know that why I can't use an object globally for all my activities and if I can how it is possible?
Thanks
There is a handful of ways in which you can achieve this.
Using a bus/listener:
https://github.com/greenrobot/EventBus
https://square.github.io/otto/
Using the application class (ready the first answer carefully, there are caveats):
How to declare global variables in Android?
And using utility classes with static methods.
Also, if you are have more than one fragment running at the same time, you can create your own interfaces and implement them where you need to receive the information.

How many types of context in android and what is better to use

I just wanted to know how many ways to get the context, which method used in which situation.
Which one better to use, and what is the main and key deference between them.
For Your better understands you should read android official blog. an also look at HackBod Answer.
There are some references URL which help you more about the context
What exactly does using the Application Context mean?
Difference between Activity Context and Application Context
http://android-developers.blogspot.de/2009/01/avoiding-memory-leaks.html
Thanks
Context class represents the local environment of an App, It encapsulates all the services and resources available to the app. There is a base class ApplicationContext, and sub classes for components: Activity, Service etc.
Always prefer using ApplicationContext because it is global and doesn't cause serious issues if its leaked, that is: an unused reference of it stays and is not garbage collected.
Sometimes you have to use sub components like Activity or Service as context. Use this when creating Intents, or creating UI Elements, or showing a toast etc. That is: functions that are specifically bound to these component's identity, its UI or its display window.

Where to insert code for application startup?

Android newbee here, I have some code that I want to run when my android app first starts up. It checks the version of the local database and downloads a new version if the current version is out of date. I have been sticking it in the oncreate of my first activity, pretty sure there has to be a better place to put this. Any recommendations of somewhere I can put it where it will get called once on startup?
You can write a custom Application class (extend from android.app.Application). Override onCreate to specify what happens when the application is started:
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
// Do something here.
}
}
You'll then need to register your custom class in the manifest file:
<application ... android:name="fully.qualified.MyApplication">
Edit:
In response to David Cesarino, I disagree with the purpose of the Application class. If you rely on the Activity's onCreate, then what's to stop it from becoming the same huge class of miscellaneous purposes... if you need something to happen when the application starts, you have to write that code somewhere; and the Activity would probably become more cluttered because you have to perform Activity specific logic in it as well. If you're worried about clutter, then separate the logic into other classes and call them from the Application. Using the SharedPreferences to determine whether or not the logic should execute seems like more of a work-around to a problem that's already been solved.
Dianne Hackborn seems to be referring to data, not logic, in which I totally agree. Static variables are much better than Application level variables... better scoping and type safety make maintainability/readability much easier.
First, look at the Activity lifecycle.
Answering your question, you could put code in any of those "start-up" methods, depending on what you want to do and, mostly important, when you want to trigger that. For what you asked, onCreate is the reasonable place.
I have been sticking it in the oncreate of my first activity, pretty sure there has to be a better place to put this.
And why is that? Any code has an entry point, right? In Android Activities it just happens to be onCreate (again, see above link for the full details). Besides event handling, which are responses to events happening outside the main sequence of calls, you put stuff in onCreate.
If you're concerned about the method becoming huge, then that's another problem. Abstract your code better, I say. For checking preliminary stuff, people generally provide a "Loading" activity, before starting the main activity of the app.
edited:
This is a follow up to what drumboog proposed, since my comment started to grow in complexity to be "just a comment".
Personally, I'd avoid extending the Application class for the sole reason of executing code early on, more so a code that is not that sensible in priority (versioning databases). The Application class is mostly used as an easy way to persist state between Activity'ies, not as a way to "do everything". In short, I feel the Application class is commonly abused.
For what you want, you could perfectly achieve that calling code in Activity onCreate. That reduces complexity, because I've seen people stuffing Application until it becomes a huge class of miscellaneous code purposes. And that's a no-no for maintenance, with logic problems of its own.
Besides, if you truly want another solution, completely disassociated with the UI, you should think about implementing a Service instead (but I don't think it's necessary for just that).
Both of those concerns were previously addressed by Dianne Hackborn (or what I got from her message).

Last shot at undestanding what context is in Android

This will be my last try to understand what context means in Android, otherwise I will leave Android development because I don't understand why nobody can give a good answer to this. I do NOT WANT a copy paste from the Android docs that tell me that it is a interface for accessing resources. Either will I accept links to other questions because I have read them all, otherwise I wouldn't have asked.
As the documentation states it is a interface to the resources.
1st question
What is context? What does it mean that it is a interface to the resources?
2nd question
Why do we then pass this around all the time, would not every activity etc. have access to the same resources?
3rd question
Why is context needed in every friggin scenario? Such as Button myButton = new Button(this);
4th question
Yet another question about why context is passed to e.g. listadapters?
Thank you for your time:)
Would it help you to visualise a Context as a pointer to your parent object?
So, this is why in your example you create a Button with
Button myButton = new Button ( this );
The button (and Android) needs to know with which Activity it is to be associated in order to properly manage resources (as you yourself has said - don't forget, it's for Android just as much as for you or your user) and to know for example, when to trigger your onClick(). Without knowing in which Context your button exists, how does Android know whether to show it or not? How does Android know whether to send onClick() events or not? It's because it knows the context of the button.
If your buttons context is the same as the active Activity, then it's visible to the user and needs to be managed differently to an object that is not visible - for instance, the visible Activity and it's resources will be the last objects to be killed in an out-of-memory situation.
This is no different really to other operating systems and graphical toolkits, it's just different terminology.
A Context is an interface to resources, but the touchscreen is a resource, memory is a resource, the CPU is a resource - you are thinking too narrowly about what constitutes a resource (and again, it's really just semantics); resources aren't just sound files, or icons, or layouts - there are resources that Android manages too, and it needs to know the Context of your objects in order to manage those external resources properly.
Context is a means to register your objects with the system so that whenever system wants to respond to your object, it could be identified uniquely.
If you do not register your button with the system then the listener will not get the correct event and hence it will create mess and make your system crash/slow.
The concept of context is deep rooted in android. In simple terms here is my explanation:
Android is a multi-threaded platform.
There in one UI thread where everything the user sees is drawn and in the background there can be 'n' worker threads.
Every activity/service runs on its own thread.
Every activity has a local set of layouts/images/mp3's etc.
Every activity is identified in runtime by its 'Context'. Think of it as an identifier. Thus anything you might want to do within that activity you should do it with a reference of the context.
Hope this is a favorable answer for questions 1,2,3,4
1st question What is context? What
does it mean that it is a interface to
the resources?
Hmm.. Context I believe you understand that it tells you where exactly you are. As you know the concept of this pointer in Java it is same as that. The system provides each application a context. The resources needs to be mentioned that it has to be used in this context. And all these because Android is multi-threaded. It is not that you enter inside an activity and you will be dealing with just one thread.
2nd question Why do we then pass this
around all the time, would not every
activity etc. have access to the same
resources?
Well when we have one class and an inner class then if you use "this" inside the inner class then your components will take the inner class context and not the outer class context even if you meant the outer class. Here you will have to specify by saying your outer class name.this i.e you are specifying clearly that you want to use the outer class context.
Why is context needed in every friggin
scenario? Such as Button myButton = new
Button(this);
Now Button and any other widget needs to be known on which view they need to be. So by telling the context you make it clear to the widget. Say I have two classes inside a java file and now you use a button widget. How will the widget know exactly where it has to go.
I hope the answer for your forth question is also the same.

Categories

Resources