WHAT IS CONTEXT IN ANDROID?

Samuel Fernandes

Total Post:159

Points:1117
Posted by  Samuel Fernandes
 862  View(s)
Ratings:
Rate this:
In Android programming, what exactly is a Context class and what is it used for? I read about it on the developer site, but I am unable to understand it clearly.
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: What is Context in Android?

    Concept:
    • It's like access of android-activity to app's resource

    • It's similar to a when you visit a hotel, you want breakfast, lunch & dinner in suitable timings right ?

    • There are many other things you like during the time of stay. How you get these things?

    • You ask the room-service person to bring the things for you

    • Here room-service person is the context considering you are the single activity and the hotel to be your app, finally the breakfast, lunch & dinner to be the resources

    As the name suggests, its the context of current state of the application/object. It lets newly created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity, package/application)

    You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in the activity class).

    Typical uses of context:

    Creating New objects: Creating new views, adapters, listeners:
    TextView tv = new TextView(getContext());
    ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);
    Accessing Standard Common Resources: Services like LAYOUT_INFLATER_SERVICE, SharedPreferences:
    context.getSystemService(LAYOUT_INFLATER_SERVICE)   
    getApplicationContext().getSharedPreferences(*name*, *mode*);
    Accessing Components Implicitly: Regarding content providers, broadcasts, intent
    getApplicationContext().getContentResolver().query(uri, ...);

      Modified On May-20-2015 07:18:23 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!