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

StackOverflow https://stackoverflow.com/questions/14626228

  •  06-03-2022
  •  | 
  •  

문제

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

도움이 되었습니까?

해결책

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

다른 팁

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top