大家好,我是新来的,我正在开发出租车应用程序,即使该应用程序在后台,也需要跟踪司机。所以我停止了一项服务,并尝试了此代码,但当我启动该服务时,我遇到了一个错误,应用程序崩溃了我不明白为什么我在启动Servie:时出现这个错误
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);
}
@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);
120----> 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 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) {
}
}
您尚未初始化mContext
变量。因此,在super.onCreate()
调用后立即在onCreate
中初始化它:
@Override
public void onCreate() {
super.onCreate();
mContext = this;
//rest of your code
}