Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Context when you call a method in a different class?

So basically, I have a method that requires a Context in order to perform several tasks.

public void openDatePicker() { Context c; }

I want to know, how to define a context of the method caller so I don't have to insert it as a parameter each time I call the method.

like image 755
Achmad Naufal Syafiq Avatar asked Jul 17 '17 03:07

Achmad Naufal Syafiq


People also ask

What method do you call to create a context object?

A Context object is created by first calling the ORB method get_default_context and then calling the method create_child on the default context.

Can context be cast to activity?

The Best Answer is getApplicationContext(); Wherever you are passing it pass this or ActivityName. this instead. you get this exception because you can't cast the Application to Activity since Application is not a sub-class of Activity .

How do you call a method from another class in Android?

You should use the following code : Class2 cls2 = new Class2(); cls2. UpdateEmployee(); In case you don't want to create a new instance to call the method, you can decalre the method as static and then you can just call Class2.

How to call method in same class in Java?

This Java program is used to call method in same class. public class CallingMethodsInSameClass { // Method definition performing a Call to another Method public static void main(String[] args) { Method1(); // Method being called. Method2(); // Method being called.

How to access the method of another class from your class?

In this tutorial, I am gonna show you how to access the method of another class from your class or child class by using dot (.) operator. we can call the method of another class by using their class name and function with dot operator. class A: method_A (self): {} class B: method_B (self): A.method_A () (like this ....)

How do I get the context of an application in Java?

To get Context anywhere in your application, i.e. in any class of your project, you can call the function of this class, like this: This function will return a Context that you can use to carry out your tasks. So, coming to your question.

How to call a static method that returns some other static method?

Calling a static method that returns some other static method: Instance method (s) belong to the Object of the class, not to the class (i.e.) they can be called after creating the Object of the class. An instance method can also be called from another method. But, we need to know the address of the method which we are calling.


4 Answers

Lets have an basic understanding of Context.

Context allows access to application-specific resources and classes, as well as calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

A Context represents your environment. It represents the state surrounding where you are in your system.

An Android app has activities. Context is like a handle to the environment your application is currently running in. The activity object inherits the Context object.

So, how to access Context in your application ?

  • getContext(): Returns the context within the currently active Activity. You can also use this for inflating layouts and menus, register context menus, instantiating widgets, start other activities, create new Intent within an Activity etc.

Example: View.getContext() returns the Context the view is currently running in. Usually the currently active Activity.

View mView = this.getLayoutInflater().inflate(R.layout.myLayout, myViewGroup);

Or,

Intent mIntent = new Intent(this, MyActivity.class);
this.startActivity(mIntent);
  • getApplicationContext(): Returns the Context for the entire application, instead of the current Activity i.e. if you need a Context tied to the lifecycle of the entire application, not just the current Activity. This Context is widely used as it is safest to use as this Context exists for the lifespan of the application.

Example: Bind an application-wide class.

Intent mIntent = new Intent(this, MyPersistent.class);
MyServiceConnection mServiceConnection = new MyServiceConnection();
if (mServiceConnection != null) {
    getApplicationContext().bindService(mIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
}
  • getBaseContext(): Returns a Context from another context within application that you can access. This method has a limited usage.The method is relevant when you have a ContextWrapper.

ContextWrapper is, "Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context." (as per javadocs)..

Now, a question might arise ! How would one access the Context object inside of a class that does not extend Activity ? So, it can be achieved by :

  • Passing Context as an object to other class: For a class that does not have an access to any of the Context mentioned above. Context can be passed to such class through its constructor.

Example:

public class MyActivity extends Activity {
    private Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        
        context = getApplicationContext();
        new Helper(context);
    }
}

public class Helper {
    Context mContext;
    Helper(Context ctx){
        this.mContext= ctx;
    }
//Now you can use this mContext anywhere in your class.
}

And finally, to get Context anywhere in your application you can define a new class in your application :

public class MyContext extends Application {
    private static MyContext instance;

    @Override
    public void onCreate() {
        instance = this;
        super.onCreate();
    }

    public static Context getContext(){
        return instance;
        // or return instance.getApplicationContext();
    }
}

In your manifest you need to add this class to the "Name" field in the "Application" tab, like this:

<application
android:name="com.example.app.MyContext "
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
.......
<activity
......
</activity>

To get Context anywhere in your application, i.e. in any class of your project, you can call the function of this class, like this:

MyContext.getContext();

This function will return a Context that you can use to carry out your tasks.

So, coming to your question. I guess the last two methods can solve your problem i.e passing the Context object to the class and define a new class that extends Application.

That's all @Achmad Naufal Syafiq. This is my best effort to help you out.

like image 69
Androwed Avatar answered Nov 08 '22 08:11

Androwed


This can be done by two ways..

First

Make a class say Functions and make you public static method inside it.

public class Functions{

    public static void openDatePicker(Context c){ 
        // Do your work where you can use c as Context
    }

}

and call it Wherever you want like

Function.openDatePicker(MainActivity.this);

Second

as @UmarZaii Suggested You can define it once in the constructor.

public class CustomDatePicker {

    private Context context;

    public ClassLocationModel(Context context) {
         this.context = context;
    }

    public void openDatePicker() {
         // Do your work where you can use "context" as Context
    }
} 

and to you that you have to initialize this class once in your Activity

CustomDatePicker customDatePicker = new CustomDatePicker(MainActivity.this);

// to use its methods
customDatePicker.openDatePicker(); 

I hope it will Help.

like image 41
V-rund Puro-hit Avatar answered Nov 08 '22 08:11

V-rund Puro-hit


You can one of the many dependency injection libraries to inject not just context but any dependencies that you have in a particular file.

You can have a look at Dagger2 for example

This will help you exactly to create different contexts

like image 31
Arun Shankar Avatar answered Nov 08 '22 09:11

Arun Shankar


You can define it once in the constructor so that everytime you want to use the method, you don't have to define it in the parameter. Try this.

public class CustomDatePicker {

    private Context context;

    public ClassLocationModel(Context context) {
         this.context = context;
    }

    public void openDatePicker() {
         //Use context that has been passed through constructor here
    }
}

So, basically the trick is to pass context in the parameter of the contructor only ONCE and you can repetitively use openDatePicker method without passing any context inside the parameter.

like image 37
UmarZaii Avatar answered Nov 08 '22 09:11

UmarZaii