Asked  7 Months ago    Answers:  5   Viewed   26 times

In various bits of Android code I've seen:

 public class MyActivity extends Activity {
    public void method() {
       mContext = this;    // since Activity extends Context
       mContext = getApplicationContext();
       mContext = getBaseContext();

However I can't find any decent explanation of which is preferable, and under what circumstances which should be used.

Pointers to documentation on this, and guidance about what might break if the wrong one is chosen, would be much appreciated.



I agree that documentation is sparse when it comes to Contexts in Android, but you can piece together a few facts from various sources.

This blog post on the official Google Android developers blog was written mostly to help address memory leaks, but provides some good information about contexts as well:

In a regular Android application, you usually have two kinds of Context, Activity and Application.

Reading the article a little bit further tells about the difference between the two and when you might want to consider using the application Context (Activity.getApplicationContext()) rather than using the Activity context this). Basically the Application context is associated with the Application and will always be the same throughout the life cycle of your app, where as the Activity context is associated with the activity and could possibly be destroyed many times as the activity is destroyed during screen orientation changes and such.

I couldn't find really anything about when to use getBaseContext() other than a post from Dianne Hackborn, one of the Google engineers working on the Android SDK:

Don't use getBaseContext(), just use the Context you have.

That was from a post on the android-developers newsgroup, you may want to consider asking your question there as well, because a handful of the people working on Android actual monitor that newsgroup and answer questions.

So overall it seems preferable to use the global application context when possible.

Tuesday, June 1, 2021
answered 7 Months ago

Of course, never fails. Found the solution about a minute after posting the above question... solution for those that may have had the same issue:


Found here.

Tuesday, June 22, 2021
answered 6 Months ago

This is fine, and will not cause a memory leak.

As soon as onCreate finishes executing, h will be out of scope and become eligible for garbage collection. If h was static, then you would run into problems. Only when the reference to the context outlives the lifecycle of the context itself will a memory leak occur. A few helpful hints:

  • Use Context.getApplicationContext() when possible. This context will live as long as your application is alive.
  • Be careful when using static fields and inner classes.
  • Run your application through a profiler to check for leaks.
Tuesday, July 13, 2021
answered 5 Months ago

Well, there's essentially two questions here:

  1. What is the difference (in general) between one to one, many to many, and foreign key relations
  2. What are their differences specific to Django.

Both of these questions are quite easily answered through a simple Google search, but as I cannot find an exact dupe of this question on SO, I'll go ahead and answer.

Note that in Django, relationships should only be defined on one side of the relationship.


A foreign key relationship is generally known as a many-to-one relationship. Note that the reverse of this relationship is one-to-many (which Django provides tools to access). As the name implies, many objects may be related to one.

Person >--| Birthplace
   ^           ^
   |           |
  Many        One 

In this example, a person may only have one birthplace, but a birthplace may be related to many people. Let's look at this example in Django. Say these are our models:

class Birthplace(models.Model):
    city = models.CharField(max_length=75)
    state = models.CharField(max_length=25)

    def __unicode__(self):
        return "".join(, ", ", self.state)

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthplace = models.ForeignKey(Birthplace)

    def __unicode__(self):

You can see that no relations are defined within the Birthplace model, and a ForeignKey relationship is defined within the Person model. Say that we create the following instances of our models (obviously not in Python syntax):

  • Birthplace: Dallas, Texas
  • Birthplace: New York City, New York
  • Person: John Smith, Birthplace : (Dallas, Texas)
  • Person: Maria Lee, Birthplace : (Dallas, Texas)
  • Person: Daniel Lee, Birthplace : (New York City, New York)

Now we can see how Django lets us use these relations (note that ./ shell is your friend!):

>> from somewhere.models import Birthplace, Person
>> Person.objects.all()
[<Person: John Smith>, <Person: Maria Lee>, <Person: Daniel Lee>]
>> Birthplace.objects.all()
[<Birthplace: Dallas, Texas>, <Birthplace: New York City, New York>]

You can see the model instances we created. Now let's checkout someone's birthplace:

>> person = Person.object.get(name="John Smith")
>> person.birthplace
<Birthplace: Dallas, Texas>

Let's say you want to see all people with a given birthplace. As I said earlier, Django allows you to access reverse relations. By default, Django creates a manager (RelatedManager) on your model to handle this, named <model>_set, where <model> is your model name in lowercase.

>> place = Birthplace.objects.get(city="Dallas")
>> place.person_set.all()
[<Person: John Smith>, <Person: Maria Lee>]

Note that we can change the name of this manager by setting the related_name keyword argument in our model relation. So, we would change the birthplace field in the Person model to:

birthplace = models.ForeignKey(Birthplace, related_name="people")

Now, we can access that reverse relationship with a pretty name:

>> place.people.all()
[<Person: John Smith>, <Person: Maria Lee>]


A one-to-one relationship is quite similar to a many-to-one relationship, except that it restricts two objects to having a unique relationship. An example of this would be a User and a Profile (which stores information about the user). No two users share the same profile.

User |--| Profile
  ^          ^
  |          |
 One        One

Let's look at this in Django. I won't bother to define the user model, as Django defines it for us. Do note, however, that Django suggests using django.contrib.auth.get_user_model() to import the user, so that's what we'll do. The profile model may be defined as follows:

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL) # Note that Django suggests getting the User from the settings for relationship definitions
    fruit = models.CharField(max_length=50, help_text="Favorite Fruit")
    facebook = models.CharField(max_length=100, help_text="Facebook Username")

    def __unicode__(self):
        return "".join(self.fruit, " ", self.facebook)

All we need is one user with a profile to test this out in the shell:

  • User: johndt6
  • Profile: user : johndt6, "Kiwi", "blah_blah"

Now you may easily access the user's profile from the User model:

>> user = User.objects.all()[0]
>> user.username
>> user.profile
<Profile: Kiwi blah_blah>
>> user.profile.fruit
>> profile = Profile.objects.get(user=user)
>> profile.user
<User: johndt6>

Of course, you may customize the name of the reverse relation using the related_name argument as above.


Many-to-many relationships can be a bit tricky. Let me start by saying that many-to-many fields are messy, and should be avoided when possible. Given that, there are plenty of situations where a many-to-many relationship makes sense.

A many-to-many relationship between two models defines that zero, one or more objects of the first model may be related to zero, one or more objects of the second model. As an example, let's envision a company that defines their workflow through projects. A project may be related to no orders, only one order, or many orders. An order may be related to no projects, one project, or many.

Order >--< Project
  ^           ^
  |           |
 Many        Many

Let's define our models as so:

class Order(models.Model):
    product = models.CharField(max_length=150)  # Note that in reality, this would probably be better served by a Product model
    customer = models.CharField(max_length=150)  # The same may be said for customers

    def __unicode__(self):
        return "".join(self.product, " for ", self.customer)

class Project(models.Model):
    orders = models.ManyToManyField(Order)

    def __unicode__(self):
        return "".join("Project ", str(

Note that Django will create a RelatedManager for the orders field to access the many-to-many relationship.

Let's create the following instances of our models (in my inconsistent syntax!):

  • Order: "Spaceship", "NASA"
  • Order: "Submarine", "US Navy"
  • Order: "Race car", "NASCAR"
  • Project: orders: []
  • Project: orders: [(Order: "Spaceship", "NASA")]
  • Project: orders: [(Order: "Spaceship", "NASA"), (Order: "Race car", "NASCAR")]

We can access these relationships as follows:

>> Project.objects.all()
[<Project: Project 0>, <Project: Project 1>, <Project: Project 2>]
>> for proj in Project.objects.all():
..     print(proj)
..     proj.orders.all()  # Note that we must access the `orders`
..                        # field through its manager
..     print("")
Project 0

Project 1
[<Order: Spaceship for NASA>]

Project 2
[<Order: Spaceship for NASA>, <Order: Race car for NASCAR>]

Note that the NASA order is related to 2 projects, and the US Navy order is related to none. Also note that one project has no orders, and one has multiple.

We may also access the relationship in reverse in the same way we have before:

>> order = Order.objects.filter(customer="NASA")[0]
>> order.project_set.all()
[<Project: Project 0>, <Project: Project 2>]

ASCII Cardinality Guide

In the likely case that my ASCII diagrams are a bit confusing, the following explanations might be helpful:

  • > or < means "to many"
  • | means "to one"

So... A --| B means an instance of A can be related to only ONE instance of B.

And A --< B means an instance of A can be related to MANY instances of B.

A >--< B is equivalent to....

A --< B
A >-- B

Thus, each "side" or direction of the relationship can be read separately. It's just convenient to squish them together.

Expanding one of these relationships might make more sense:

               +---- John Smith
 Dallas|-------+---- Jane Doe
               +---- Joe Smoe


Good explanation of db relationships provided by @MarcB

Wikipedia page on Cardinality

Django Docs:




One-to-one Relationships

Many-to-many Relationships

Tuesday, July 27, 2021
answered 5 Months ago

There isn't much difference unless you are using very old browsers (netscape 4.x and ie 3.x). You can read a complete lowdown on what each means here.

From a standards viewpoint, there is no difference between linking to an external style sheet or importing it. Either way is correct, and either way will work equally well (in most cases).

Sunday, September 19, 2021
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :