how can i learn which context is best to use for each situation in android?

There are mainly two type of context in android & both of them are provided to you as a ContextWrapper class object.

  1. Application Context

This context is basically provided/used when you need to do some work that doesn’t involves any view/UI operation (where you don’t need to refer to/rely on any UI code).

This is mostly helpful when you’re doing operations directly via your process that doesn’t need any UI interactions like for an example, getting list of contacts via content provider.

So, you can consider this as parent of all other context you can have in your application and apparently this is consistent for your given process.

This context is retrieved via Application class of your app, or via any other activity by requesting like (activity.applicationContext).

  1. Activity Context

This context is basically bounded/limited to given activity you’re in right now. This is helpful to mainly do UI operations because, your context is part of the same UI you are in right now.

So, yes you can consider this a child context that can changes as per your activity changes. For most of the cases, it is not preferred to store & share this context across UI/Activities as it can lead to memory leaks.

This context can be retrieved once you’re on any activity class via (Activity.this, this, context in fragments & custom views)

I agree personally that context has been confusing topic on Android since the beginning, but if you know C/C++ then I can relate this to ‘pointers’ (conceptually). Context are pointers for given activity/application class.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top