Search code examples
androidexceptionimei

Cannot make a static reference to the non-static method getIMEI() from the type Util


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")


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);
    }