Question

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String test =  Util.imei();
}


import android.content.Context;
import android.telephony.TelephonyManager;

public class Util{
    Context context;

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

    public String imei() {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getDeviceId();
    }
}

Getting error "Cannot make a static reference to the non-static method imei() from the type Util". If I change the line to:

public static String imei() {
    ...
    static Context context;

I get an error and crash app.("E/AndroidRuntime(629): Caused by:java.lang.NullPointerException")

Was it helpful?

Solution

two ways to write it:

1st non static

public class Util {
    Context context;

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

    public String imei() {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getDeviceId();
    }
}

and then in onCreate method

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Util u = new Util(this);
    String test =  u.imei();
}

2nd static

public class Util {
    public static String imei(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getDeviceId();
    }
}

and then in onCreate method

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String test =  Util.imei(this);
}

OTHER TIPS

You are trying to access a method inside a class without creating an object for it. Only for static method we can call like that. In your case, create an object for Util and call imei() using that object.

Like,

Util utilObj = new Util();
String imei = utilObj.imei();

Hope this helps.

Create a reference of the Util class first before accessing its methods.

Util util = new Util();
String _imei = util.imei();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top