尝试调用虚拟方法';android.content.Context.getSharedReferences(java.lang.String,int)和#x27;关于空对象引用

尝试调用虚拟方法';android.content.Context.getSharedReferences(java.lang.String,int)和#x27;关于空对象引用,java,android,service,nullpointerexception,sharedpreferences,Java,Android,Service,Nullpointerexception,Sharedpreferences,大家好,我是新来的,我正在开发出租车应用程序,需要跟踪司机,即使应用程序在后台,所以我启动了一项服务,我尝试了这段代码,但当我启动服务时,出现了一个错误,应用程序崩溃 我无法理解为什么在启动服务时出现此错误: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedP

大家好,我是新来的,我正在开发出租车应用程序,需要跟踪司机,即使应用程序在后台,所以我启动了一项服务,我尝试了这段代码,但当我启动服务时,出现了一个错误,应用程序崩溃 我无法理解为什么在启动服务时出现此错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
        at com.raismedia.taxiclient.model.M.getUserCategorie(M.java:164)
        at com.raismedia.taxiclient.TrackingService.onCreate(TrackingService.java:120)
这些是台词

public static String getUserCategorie(Context mContext) {
     164 ---->   mSharedPreferences = mContext.getSharedPreferences(pref_name, 0);
        return mSharedPreferences.getString("user_cat", null);
    }
我的服务代码在这里

public class TrackingService extends Service implements  TaskLoadedCallback, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {
    private static final int LOCATION_REQUEST_CODE = 101;
    public static TextView user_name, user_phone,statut_conducteur, balance;
    private SwitchCompat switch_statut;




    private GoogleApiClient mGoogleAPIClient;
    private LocationRequest mLocationRequest;
    private FusedLocationProviderApi mLocationProvider;
    private Location currentLocation;
    private Context mContext;
    private Location Location;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mGoogleAPIClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        mLocationProvider = LocationServices.FusedLocationApi;

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(5000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        if(!M.getUserCategorie(mContext).equals("user_app")) {
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {

            }

            if(!isLocationEnabled(mContext))
                showMessageEnabledGPS();
        }


    }

    public void showMessageEnabledGPS(){
        final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage("Activez le service GPS pour partager votre position avec les clients. Activez le GPS maintenant ?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.cancel();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    }

    private boolean isLocationEnabled(Context context){
//        String locationProviders;
        boolean enabled = false;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            int mode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE,
                    Settings.Secure.LOCATION_MODE_OFF);
            enabled = (mode != Settings.Secure.LOCATION_MODE_OFF);
        }else{
            LocationManager service = (LocationManager) context.getSystemService(LOCATION_SERVICE);
            enabled =  service.isProviderEnabled(LocationManager.GPS_PROVIDER)||service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        }
        return enabled;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mGoogleAPIClient.connect();
        return START_STICKY;
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        RequestLocationUpdates();
    }

    private void RequestLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleAPIClient, mLocationRequest, this); //getting error here..for casting..!

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
    private Boolean verif = false;
    public static GoogleMap mMap;
    public static Marker currentMarker = null, destinationMarker = null;




    @Override
    public void onLocationChanged(Location location) {
        this.currentLocation = location;
//        Toast.makeText(context, "Ok", Toast.LENGTH_SHORT).show();

        if (currentLocation != null) {
            if(!M.getUserCategorie(mContext).equals("user_app"))
                new MainActivity.setCurrentLocation().execute(String.valueOf(location.getLatitude()),String.valueOf(location.getLongitude()));
        }
    }
    /**driver position Update **/
    public static class setCurrentLocation extends AsyncTask<String, Void, String> {


        private Context context;

        @Override
        protected String doInBackground(String... params) {
            String url = AppConst.Server_url+"set_position.php";
            final String latitude = params[0];
            final String longitude = params[1];
            StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
                    url,
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {

                        }
                    }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {

                }

            }) {

                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("id_user", M.getID(context));
                    params.put("user_cat", M.getUserCategorie(context));
                    params.put("latitude", latitude);
                    params.put("longitude", longitude);
                    return params;
                }

            };
            AppController.getInstance().addToRequestQueue(jsonObjReq);
            jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
                    10000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            //to add spacing between cards
            if (this != null) {

            }

        }

        @Override
        protected void onPreExecute() {

        }
    }
    private class changerStatut extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String url = AppConst.Server_url+"change_statut.php";
            final String online = params[0];
            StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
                    url,
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {
                            try {
                                M.hideLoadingDialog();
                                JSONObject json = new JSONObject(response);
                                JSONObject msg = json.getJSONObject("msg");
                                String etat = msg.getString("etat");
                                String online = msg.getString("online");
                                if(etat.equals("1")){
                                    if(online.equals("yes")) {
                                        switch_statut.setChecked(true);
                                        statut_conducteur.setText("enabled");
                                        M.setStatutConducteur(online,mContext);
                                    }else {
                                        switch_statut.setChecked(false);
                                        statut_conducteur.setText("disabled");
                                        M.setStatutConducteur(online,mContext);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    M.hideLoadingDialog();
                    if(switch_statut.isChecked())
                        switch_statut.setChecked(false);
                    else
                        switch_statut.setChecked(true);
                }
            }) {

                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("id_driver", M.getID(mContext));
                    params.put("online", online);
                    return params;
                }

            };
            AppController.getInstance().addToRequestQueue(jsonObjReq);
            jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
                    10000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            //to add spacing between cards
            if (this != null) {

            }

        }

        @Override
        protected void onPreExecute() {

        }
    }


    @Override
    public void onConnected() {
        RequestLocationUpdates();


    }

    @Override
    public void onTaskDone(Object... values) {

    }
}
公共类TrackingService扩展服务实现TaskLoadedCallback、GoogleAppClient.ConnectionCallbacks、,
GoogleAppClient.OnConnectionFailedListener,LocationListener{
私有静态最终整数位置\请求\代码=101;
公共静态文本查看用户名、用户电话、状态导体、余额;
专用交换机兼容交换机状态;
私人GoogleapClient MGoogleapClient;
私人位置请求mLocationRequest;
私有FusedLocationProviderApi mLocationProvider;
私人位置;
私有上下文;
私人位置;
@可空
@凌驾
公共IBinder onBind(意向){
返回null;
}
@凌驾
public void onCreate(){
super.onCreate();
mgoogleapclient=新的Googleapclient.Builder(此)
.addApi(LocationServices.API)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.build();
mLocationProvider=LocationServices.FusedLocationApi;
mlLocationRequest=新位置请求();
mLocationRequest.setInterval(5000);
mlLocationRequest.setFastTestInterval(1000);
mLocationRequest.setPriority(位置请求、优先级、平衡、功率、精度);
如果(!M.getUserCategorie(mContext).equals(“用户应用程序”)){
if(ActivityCompat.checkSelfPermission(这个,android.Manifest.permission.ACCESS\u FINE\u位置)
!=PackageManager.PERMISSION\u已授予和&ActivityCompat.checkSelfPermission(此,android.Manifest.PERMISSION.ACCESS\u位置)
!=PackageManager.权限(已授予){
}
如果(!isLocationEnabled(mContext))
showMessageEnabledGPS();
}
}
public void showMessageEnabledGPS(){
final AlertDialog.Builder=新建AlertDialog.Builder(mContext);
builder.setMessage(“Activez le服务GPS浇注零件votre位置avec les客户端。Activez le GPS主租户?”)
.setCancelable(错误)
.setPositiveButton(“是”,新的DialogInterface.OnClickListener(){
@凌驾
公共void onClick(DialogInterface,inti){
startActivity(新意图(设置、动作、位置、来源、设置));
}
})
.setNegativeButton(“否”,新的DialogInterface.OnClickListener(){
@凌驾
公共void onClick(DialogInterface,inti){
dialogInterface.cancel();
}
});
final AlertDialog alert=builder.create();
alert.show();
}
私有布尔isLocationEnabled(上下文){
//字符串位置提供者;
布尔启用=假;
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.KITKAT){
int mode=Settings.Secure.getInt(context.getContentResolver(),Settings.Secure.LOCATION\u mode,
设置。安全。位置(模式(关闭);
已启用=(模式!=设置。安全。位置\u模式\u关闭);
}否则{
LocationManager服务=(LocationManager)context.getSystemService(LOCATION\u服务);
enabled=服务.isProviderEnabled(LocationManager.GPS|u提供程序)|服务.isProviderEnabled(LocationManager.NETWORK|u提供程序);
}
返回启用;
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
mGoogleAPIClient.connect();
返回开始时间;
}
@凌驾
未连接的公共无效(@Nullable Bundle){
RequestLocationUpdates();
}
私有void RequestLocationUpdates(){
if(ActivityCompat.checkSelfPermission(这个,android.Manifest.permission.ACCESS\u FINE\u位置)
!=PackageManager.PERMISSION\u已授予和&ActivityCompat.checkSelfPermission(此,android.Manifest.PERMISSION.ACCESS\u位置)
!=PackageManager.权限(已授予){
}
LocationServices.FusedLocationApi.requestLocationUpdates(mgoogleapClient,mlLocationRequest,this);//此处获取错误..用于强制转换。。!
}
@凌驾
公共空间连接暂停(int i){
}
@凌驾
public void onconnection失败(@NonNull ConnectionResult ConnectionResult){
}
私有布尔verif=false;
公共静态谷歌地图;
公共静态标记currentMarker=null,destinationMarker=null;
@凌驾
已更改位置上的公共无效(位置){
this.currentLocation=位置;
//Toast.makeText(上下文“Ok”,Toast.LENGTH_SHORT).show();
if(currentLocation!=null){
如果(!M.getUserCategorie(mContext).equals(“用户应用程序”))
新建MainActivity.setCurrentLocation().execute(String.valueOf(location.getLatitude()),String.valueOf(location.getLatitude());
}
}
/**驾驶员位置更新**/
公共静态类setCurrentLocation扩展了异步任务{
私人语境;
@凌驾
受保护的字符串doInBackground(字符串…参数){
字符串url=AppConst.Server\uURL+“set\u position.php”;
最终字符串纬度=参数[0];
最终字符串经度=参数[1];
StringRequest JSONOBJEQ=新的StringRequest(Request.Method.POST,
网址,
public class TrackingService extends Service implements  TaskLoadedCallback, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {
    private static final int LOCATION_REQUEST_CODE = 101;
    public static TextView user_name, user_phone,statut_conducteur, balance;
    private SwitchCompat switch_statut;




    private GoogleApiClient mGoogleAPIClient;
    private LocationRequest mLocationRequest;
    private FusedLocationProviderApi mLocationProvider;
    private Location currentLocation;
    private Context mContext;
    private Location Location;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mGoogleAPIClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        mLocationProvider = LocationServices.FusedLocationApi;

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(5000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        if(!M.getUserCategorie(mContext).equals("user_app")) {
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {

            }

            if(!isLocationEnabled(mContext))
                showMessageEnabledGPS();
        }


    }

    public void showMessageEnabledGPS(){
        final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage("Activez le service GPS pour partager votre position avec les clients. Activez le GPS maintenant ?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.cancel();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    }

    private boolean isLocationEnabled(Context context){
//        String locationProviders;
        boolean enabled = false;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            int mode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE,
                    Settings.Secure.LOCATION_MODE_OFF);
            enabled = (mode != Settings.Secure.LOCATION_MODE_OFF);
        }else{
            LocationManager service = (LocationManager) context.getSystemService(LOCATION_SERVICE);
            enabled =  service.isProviderEnabled(LocationManager.GPS_PROVIDER)||service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        }
        return enabled;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mGoogleAPIClient.connect();
        return START_STICKY;
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        RequestLocationUpdates();
    }

    private void RequestLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleAPIClient, mLocationRequest, this); //getting error here..for casting..!

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
    private Boolean verif = false;
    public static GoogleMap mMap;
    public static Marker currentMarker = null, destinationMarker = null;




    @Override
    public void onLocationChanged(Location location) {
        this.currentLocation = location;
//        Toast.makeText(context, "Ok", Toast.LENGTH_SHORT).show();

        if (currentLocation != null) {
            if(!M.getUserCategorie(mContext).equals("user_app"))
                new MainActivity.setCurrentLocation().execute(String.valueOf(location.getLatitude()),String.valueOf(location.getLongitude()));
        }
    }
    /**driver position Update **/
    public static class setCurrentLocation extends AsyncTask<String, Void, String> {


        private Context context;

        @Override
        protected String doInBackground(String... params) {
            String url = AppConst.Server_url+"set_position.php";
            final String latitude = params[0];
            final String longitude = params[1];
            StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
                    url,
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {

                        }
                    }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {

                }

            }) {

                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("id_user", M.getID(context));
                    params.put("user_cat", M.getUserCategorie(context));
                    params.put("latitude", latitude);
                    params.put("longitude", longitude);
                    return params;
                }

            };
            AppController.getInstance().addToRequestQueue(jsonObjReq);
            jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
                    10000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            //to add spacing between cards
            if (this != null) {

            }

        }

        @Override
        protected void onPreExecute() {

        }
    }
    private class changerStatut extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String url = AppConst.Server_url+"change_statut.php";
            final String online = params[0];
            StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
                    url,
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {
                            try {
                                M.hideLoadingDialog();
                                JSONObject json = new JSONObject(response);
                                JSONObject msg = json.getJSONObject("msg");
                                String etat = msg.getString("etat");
                                String online = msg.getString("online");
                                if(etat.equals("1")){
                                    if(online.equals("yes")) {
                                        switch_statut.setChecked(true);
                                        statut_conducteur.setText("enabled");
                                        M.setStatutConducteur(online,mContext);
                                    }else {
                                        switch_statut.setChecked(false);
                                        statut_conducteur.setText("disabled");
                                        M.setStatutConducteur(online,mContext);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    M.hideLoadingDialog();
                    if(switch_statut.isChecked())
                        switch_statut.setChecked(false);
                    else
                        switch_statut.setChecked(true);
                }
            }) {

                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("id_driver", M.getID(mContext));
                    params.put("online", online);
                    return params;
                }

            };
            AppController.getInstance().addToRequestQueue(jsonObjReq);
            jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
                    10000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            //to add spacing between cards
            if (this != null) {

            }

        }

        @Override
        protected void onPreExecute() {

        }
    }


    @Override
    public void onConnected() {
        RequestLocationUpdates();


    }

    @Override
    public void onTaskDone(Object... values) {

    }
}
@Override
public void onCreate() {
    super.onCreate();
    mContext = this;

    //rest of your code

}