views:

43

answers:

5

Hi Everybody!

I have a little idea of the Utility Classes with a slight doubt on demand.

If I use a Utility class in my Application than to use that class in my main Activity do I have to create the object of that class or I can directly Import that class in my main activity?

I am Sorry if I am not making a clear sense.

In the nutshell, all I want to be clear about is that basically how can I use the utility class in my Main Activity?

Thanks, david

A: 

If your utility class is created in your Application then you can refer to it by first creating a getMethod in the application class, then going

Application mc = (Application) context.getApplicationContext();

mc.getUtilityClass().SomeMethod()

Faisal Abid
A: 

If the methods in your utility class are static then you can call them from your main activity. eg:

int i = Utility.RandInt();

If they are not static then you have to create an object:

Utility u = new Utility();
int i = u.randInt();
skorulis
A: 

It mainly depends on what your utility class does. But, most of the time, if you create an Utility class, you will want to create static methods and invoke them without creating an instance:

class MyUtilities{
    public static String foo(String bar){
        return bar.toUppercase;
    }
}

Then, on your activity:

MyUtilities.foo("baz");

Of course, there are cases where you will want to create instance of a Utility class. For instance, if you have created a global Adapter which will be used by all your ListViews.

Cristian
A: 

I dont know what yiur exact question is. But here is a code where I used Utility class in my activity. AnimationUtil is used to load animation onto a ImageView.

    ImageView waitImg   = (ImageView) findViewById(R.id.ImageView02);

    Animation waitAnim  = AnimationUtils.loadAnimation(this, R.anim.wait_rotate);

    waitImg.startAnimation(waitAnim); 
    waitAnim.cancel();
    waitAnim.reset();
kiki
A: 

It heavily depends on what kind of utility you're referring to. There are

1) utility classes that implement static methods. In that case you just call them directly using class name

2) utility classes methods that are not static - requires creating and possibly initializing an instance of that class. Then the instance is used to call those methods.

3) utility classes that can be accessed thru Context. then you can call getApplicationContext() and then you can get access to the utility classes

Asahi