13

What i want to do is create a java file that has various functions and I would like to use it across the whole project. For example check Internet Connection. Then I would like to call that function on each activity. Does anyone know how to do that?

1
  • you can try with the solution posted with example. Commented Jan 23, 2013 at 17:07

6 Answers 6

25

Create Class like this and add your functions here :

package com.mytest;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class MyGlobals{
    Context mContext;

    // constructor
    public MyGlobals(Context context){
        this.mContext = context;
    }

    public String getUserName(){
        return "test";
    }

    public boolean isNetworkConnected() {
          ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
          NetworkInfo ni = cm.getActiveNetworkInfo();
          if (ni == null) {
           // There are no active networks.
           return false;
          } else
           return true;
    }
}

Then declare instance in your activity :

MyGlobals myGlog;

Then initialize and use methods from that global class :

myGlog = new MyGlobals(getApplicationContext());
String username = myGlog.getUserName();

boolean inConnected = myGlog.isNetworkConnected();

Permission required in your Manifest file :

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Thanks.

Sign up to request clarification or add additional context in comments.

4 Comments

this is what i need but for checking internet connection im running a boolean that uses connectivity mananger but its not letting me access getSystemService do i need to extend my class with Activity
@LukeBatley no need to extend with activity. see my edit for it.
@LukeBatley use mContext.getSystemService for it.
Additionally, I make such a utility class as 'final'.
3

Create Utility class like this:

public final class AppUtils {

    private AppUtils() {
    }

@SuppressLint("NewApi")
    public static void setTabColor(TabHost tabHost) {
        int max = tabHost.getTabWidget().getChildCount();
        for (int i = 0; i < max; i++) {
            View view = tabHost.getTabWidget().getChildAt(i);
                    TextView tv = (TextView) view.findViewById(android.R.id.title);
                    tv.setTextColor(view.isSelected() ? Color.parseColor("#ED8800") : Color.GRAY);
                    view.setBackgroundResource(R.color.black);
            }
        }

}

Now, from any class of Android application, you can function of Apputils like this:

AppUtils.setTabColor(tabHost);

Comments

1

This may not be the best way to do this and there would be others who might suggest some better alternatives, but this is how I would do.

Create a class with all the functions and save it as maybe Utility.java.

Use an object of the Utility class throughout the code where ever you need to call any of the functions.

Utility myUtilObj = new Utility();
myUtilObj.checkInternet();

Or maybe make the functions static and you can simply use Utility.checkInternet() where ever you need to call it.

6 Comments

hi thanks for your advice im not sure how what you mean by use an object of this class although what you said seems to be spot on
What he means is the "object of the utility class"
I have updated my answer with the code to make myself more clear. Create an object of Utility and then use it to call the functions. But yeah, making the functions static is a cleaner option.
thank you this is what i was looking for only issue i'm having is if i detect that there is no internetconnection how do i tell the function which activity im on in order to send an intent to another for example if im on home page and run the function from utilities how do i tell that function im on home page and need to go to another page that says no internet connection
It would probably need to have a constructor for the context as many things, such as checking internet requires the activities context to be able to execute android API functions, so calling the function may be Utility myUtil = new Utility(context);. Then in the utility in the structor set context to the top of the class so is accessible through and the context variable can be used
|
1

Just create public class with static methods, something like this ...

package com.example.test1;

public class GlobalMethod {

    public static String getHelloWorld() {
        return "Hello, World!";
    }

    public static int getAppleCount() {
        return 45;
    }
}

Now from anywhere you can call the methods ...

GlobalMethod.getHelloWorld();
GlobalMethod.getAppleCount();

There are many ways to do though, check it out other answers. Hope this is helpful.

Comments

0

You can create a utility class, which has a set of static methods (given that such a class doesn't hold any real state of its own). Now these static methods can be called from different parts of the application.

Comments

0

I am describing below how I achieved it. First, I created the following class in app/src/main/java/com/[my folder]/MyGlobals.java:

package [My package];

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class MyGlobals {
    Context mContext;
    // Constructor
    public MyGlobals(Context context){
        this.mContext = context;
    }
    public boolean checkInternetConnection() {
        ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if ((cm != null) && (netInfo != null)) {
            if (netInfo.isConnected()) {
                return true;
            }
        }
        return false;
    }
}

Then in the classes where I needed to use the global functions, I declared these member variables:

MyGlobals myGlobals;
boolean checkInternetConnection;

In the portions of code where I needed to test internet connectivity, I used this:

myGlobals = new MyGlobals(getApplicationContext());
checkInternetConnection = myGlobals.checkInternetConnection();
if(checkInternetConnection == false){
    Util.showToast([Name of my activity].this, getString(R.string.nointernet), getString(R.string.error), true, false);
    return;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.