show I require Context instead of Activity as in-parameter? - android

I am working a android sdk. I ask user input activity as a parameter, although I think "Context" is enough for my case, also from sdk's user's view, "Context" will be easer for coding. But I see some other sdk ask user pass the "Activity" as in-parameter, Is there any specific reason for "Activity"?

Context is base class of all Application, services and Activities , three main components of Android application. Most of work can be done via Context object. So if your sdk is OK with context, it is better to use Context. For ,more details check this thread. Passing Activity or Context to other instance

You should ask for a Context unless there's some function on Activity that you absolutely need to call (for example a permissions check). This will allow your library to be used in a Service or BroadcastReceiver as well.

Related

What's the recommended way of using global data on Android?

Let's say we develop an app with web authorisation. We need some "global" service to determine whether the user is logged. If user is logged, the service must provide some data (such as cookies, auth token, etc) to identity user, otherwise the service must have a way to set this data.
There are couple of ways of doing it. We can use static context (singleton or just static fields) to store this data. We also may create some Service to get all this data from.
But what way is recommended by Google? What way is ideologically correct? Perhaps there are other ways to implement that?
Don't know what's recommended by Google but if you need an object that lives as long as your application lives then it would be the Application object.
So subclass your own MyApplication extends Application, define whatever fields you need in there and then declare MyApplication in manifest and access by (MyApplication)getApplication()
Create manager (singleton pattern) that describes your app model. Yes, make sure also that it does not hold context of Activity, Service and etc. If need context, make sure to call getApplicationContext().
Singelton is the simplest way doing it (+design pattern)
But from time to time, there may be problems using singeltons: if the application process is killed, which will happen almost undoubtedly if you leave the app in the background too long, your singleton will be recreated, and so your private int data will be reset to a default value.
Maybe if you don't want to use too much shared data you can use sharedpreferences to avoid this.
Else you could try Extending the Application class.
Hope helps

Android: What happens when variables passed using intent

I want know i pass a variable via Intent to another activity and that activity changes that variable, will it reflect in original activity without passing back the intent.
If answer is no then is it better to use global variable using application then passing intent and getting back data. in my program, i am having round 5+ activities and all of them need to access a list of class objects.
any recommendations apart from above
Create your own extension of Application to store the state of your app and share data between the different activities that make up your app. The Application acts as the context for your whole app and Android guarantees there will always only be one instance across your app. Hence it works similar to defining your own Singleton, but using Application will allow Android to take control of the life cycle of your shared data and basically do the memory management for you.
To summarize:
Create your own subclass of Application.
Specify that class in the application tag in your manifest.
After this you will be able to safely cast the result of all call to getApplication() (from an Activity instance) and getApplicationContext() (from any Context instance) to the subclass you defined in step #1. This means you can use any getter/setter method defined in your application extension to store/retrieve data.
Have a read here for more details.

Android - Best way to use contexts

I've got a quick question on the best way to handle Android contexts. A lot of things (e.g. Service) require that you pass a context as a parameter. At the present time, I have a public static variable that is set to point to getApplication() and I just refer to this throughout my application where a context is required.
Is this ok to do? Or is there a better method to handle this? A lot of my classes don't extend Activity or service and as such, don't have access to this.getApplication().
Everything seems to work ok when I just pass in my static variable.
Is this ok to do?
The Application object, in some cases, will fail to work. For example, it sucks for UI-related stuff.
Dianne Hackborn, a leading Android engineer, has stated her regret at Application existing in the first place.
My general advice is to use Application only when you know specifically why it is superior to using your Activity, Service, etc. There are cases when it is the better answer (e.g., binding to services).
A lot of my classes don't extend Activity or service and as such, dont have access to this.getApplication().
Pass a suitable Context as a parameter, as the Android SDK does.
At the present time, I have a public static variable that is set to
point to getApplication() and I just refer to this throughout my
application where a context is required.
Is this ok to do?
No.
A context applies to the context in which it was obtained. That is, an activity has context for that activity, a service has context for the service, and so on. Now, a lot of folks do what you are doing, and as you observe, it seems to work. That doesn't mean it will continue to work or that it's good design. If that was the proper pattern, Android would have been designed with Context.INSTANCE that is available statically.
An activity, service, and application are contexts (isA). Receivers are passed a context to their onHandlerIntent() method. For all other classes you write, just get used to constructing them with a context. Out of habit, whenever I create a new class, I automatically add a constructor that accepts a context and add a private field to hold it.
When you need a context in a static method, you should pass it in directly as a parameter.

Should I use getApplicationContext or Activity.this in a long running AsyncTask

I have a long running Async Task that sends some data to my server and then stops. The whole process may involve a few requests and response. I have to read data from database, send it and handle the response and update my database accordingly. I am using content providers to read and update data from database.
Now to use the Content Provider, I have to call the getContentResolver() method on context. So I am wondering whether I have to use getApplicationContext or just pass the Activity.this to my methods.
I saw a few posts like this explaining the difference between the two and in most of them they advice us to not use getApplicationContext if possible. Although I do not want my AsyncTask to lose the context from Activity.this when the Activity is destroyed or when orientation changes. So I am wondering if I can use getApplicationContext in my case or will using Activity.this fit my requirement.
There is a reason to use each of the options.
When you are using the context in order to modify the UI, you should use the Activity context, since in some cases using the application context might cause an exception (as described here and here). Such as in the following case:
TextView senderNameTextView = new TextView(getApplicationContext());
When you are using the context in cross-activity usage, you should not bind the Activity context to the action, since then even if the activity is destroyed, it will not be garbage-collected, as it is still referenced from the running task. In those cases, you should use the Application context. See the article in Android Developer's site (written by Romain Guy) for even more details.
If you are only using the context to call getContentResolver, you should use the Application context.

What is Context in Android

I have a question regarding the term 'context' in Android. I see that the context provides information about the environment the application runs in, however what is the difference between Application Context and Activity Context?
AND why do I do things like this:
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
Why do I pass the context into the constructor? Can anyone provide please help me understand what a context is, and what the context object is?
I do not want copy/paste from android Reference since I already have read it.....too many times without understanding.
They are both instances of Context, but the application instance is tied to the lifecycle of the application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to different information about the application environment.
If you read the docs at getApplicationContext it notes that you should only use this if you need a context whose lifecycle is separate from the current context. This doesn't apply in either of your examples.
The Activity context presumably has some information about the current activity that is necessary to complete those calls. If you show the exact error message, might be able to point to what exactly it needs.
But in general, use the activity context unless you have a good reason not to.
In simple word ill try to explain. Lets take your example
If you are using AlertDialog Builder how will that AlertDialog will understand where he will get displayed??? (If you are not in that activity)
Here context comes in picture. We pass Activity Context to the AlertDialog.In short AlertDialog will will appear in provided context.
This is what my understanding is correct me if I am wrong.
Class Overview
Interface to global information about an application environment. This
is an abstract class whose implementation is provided by the Android
system. It allows access to application-specific resources and
classes, as well as up-calls for application-level operations such as
launching activities, broadcasting and receiving intents, etc.
anddev website said it very clearly .
you must pass it to some other class so they can access global
information among other things.

Categories

Resources