Attempt to invoke virtual method 'android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

huangapple go评论104阅读模式
英文:

Attempt to invoke virtual method 'android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

问题

抱歉,由于篇幅过长,我将只翻译主要部分。以下是您提供的代码的翻译:

  1. public static String getUserCategorie(Context mContext) {
  2. mSharedPreferences = mContext.getSharedPreferences(pref_name, 0);
  3. return mSharedPreferences.getString("user_cat", null);
  4. }
  5. @Override
  6. public void onCreate() {
  7. super.onCreate();
  8. mGoogleAPIClient = new GoogleApiClient.Builder(this)
  9. .addApi(LocationServices.API)
  10. .addConnectionCallbacks(this)
  11. .addOnConnectionFailedListener(this)
  12. .build();
  13. mLocationProvider = LocationServices.FusedLocationApi;
  14. mLocationRequest = new LocationRequest();
  15. mLocationRequest.setInterval(5000);
  16. mLocationRequest.setFastestInterval(1000);
  17. mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
  18. if (!M.getUserCategorie(mContext).equals("user_app")) {
  19. if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
  20. != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
  21. != PackageManager.PERMISSION_GRANTED) {
  22. }
  23. if (!isLocationEnabled(mContext))
  24. showMessageEnabledGPS();
  25. }
  26. }
  27. public class TrackingService extends Service implements TaskLoadedCallback, GoogleApiClient.ConnectionCallbacks,
  28. GoogleApiClient.OnConnectionFailedListener, LocationListener {
  29. @Override
  30. public void onCreate() {
  31. super.onCreate();
  32. mGoogleAPIClient = new GoogleApiClient.Builder(this)
  33. .addApi(LocationServices.API)
  34. .addConnectionCallbacks(this)
  35. .addOnConnectionFailedListener(this)
  36. .build();
  37. mLocationProvider = LocationServices.FusedLocationApi;
  38. mLocationRequest = new LocationRequest();
  39. mLocationRequest.setInterval(5000);
  40. mLocationRequest.setFastestInterval(1000);
  41. mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
  42. if (!M.getUserCategorie(mContext).equals("user_app")) {
  43. if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
  44. != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
  45. != PackageManager.PERMISSION_GRANTED) {
  46. }
  47. if (!isLocationEnabled(mContext))
  48. showMessageEnabledGPS();
  49. }
  50. }
  51. @Override
  52. public void onLocationChanged(Location location) {
  53. this.currentLocation = location;
  54. if (currentLocation != null) {
  55. if (!M.getUserCategorie(mContext).equals("user_app"))
  56. new MainActivity.setCurrentLocation().execute(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
  57. }
  58. }
  59. // Other parts of the code...
  60. }

由于篇幅限制,以上只是您提供代码的翻译摘要,如果您还需要其他部分的翻译,请继续提问。

英文:

hello everybody i m new here , im working on taxi app that need to keep tracking driver even the app is in background So i ceate a service and i tried this code but when i start the service i got an error and the app crash
i Can t figure out why i got this error when starting a Servie :

  1. 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
  2. at com.raismedia.taxiclient.model.M.getUserCategorie(M.java:164)
  3. at com.raismedia.taxiclient.TrackingService.onCreate(TrackingService.java:120)

these are the lines

  1. public static String getUserCategorie(Context mContext) {
  2. 164 ----> mSharedPreferences = mContext.getSharedPreferences(pref_name, 0);
  3. return mSharedPreferences.getString("user_cat", null);
  4. }
  1. @Override
  2. public void onCreate() {
  3. super.onCreate();
  4. mGoogleAPIClient = new GoogleApiClient.Builder(this)
  5. .addApi(LocationServices.API)
  6. .addConnectionCallbacks(this)
  7. .addOnConnectionFailedListener(this)
  8. .build();
  9. mLocationProvider = LocationServices.FusedLocationApi;
  10. mLocationRequest = new LocationRequest();
  11. mLocationRequest.setInterval(5000);
  12. mLocationRequest.setFastestInterval(1000);
  13. mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
  14. 120----> if(!M.getUserCategorie(mContext).equals("user_app")) {
  15. if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
  16. != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
  17. != PackageManager.PERMISSION_GRANTED) {
  18. }
  19. if(!isLocationEnabled(mContext))
  20. showMessageEnabledGPS();
  21. }
  22. }

MyService code here

  1. public class TrackingService extends Service implements TaskLoadedCallback, GoogleApiClient.ConnectionCallbacks,
  2. GoogleApiClient.OnConnectionFailedListener, LocationListener {
  3. private static final int LOCATION_REQUEST_CODE = 101;
  4. public static TextView user_name, user_phone,statut_conducteur, balance;
  5. private SwitchCompat switch_statut;
  6. private GoogleApiClient mGoogleAPIClient;
  7. private LocationRequest mLocationRequest;
  8. private FusedLocationProviderApi mLocationProvider;
  9. private Location currentLocation;
  10. private Context mContext;
  11. private Location Location;
  12. @Nullable
  13. @Override
  14. public IBinder onBind(Intent intent) {
  15. return null;
  16. }
  17. @Override
  18. public void onCreate() {
  19. super.onCreate();
  20. mGoogleAPIClient = new GoogleApiClient.Builder(this)
  21. .addApi(LocationServices.API)
  22. .addConnectionCallbacks(this)
  23. .addOnConnectionFailedListener(this)
  24. .build();
  25. mLocationProvider = LocationServices.FusedLocationApi;
  26. mLocationRequest = new LocationRequest();
  27. mLocationRequest.setInterval(5000);
  28. mLocationRequest.setFastestInterval(1000);
  29. mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
  30. if(!M.getUserCategorie(mContext).equals("user_app")) {
  31. if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
  32. != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
  33. != PackageManager.PERMISSION_GRANTED) {
  34. }
  35. if(!isLocationEnabled(mContext))
  36. showMessageEnabledGPS();
  37. }
  38. }
  39. public void showMessageEnabledGPS(){
  40. final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
  41. builder.setMessage("Activez le service GPS pour partager votre position avec les clients. Activez le GPS maintenant ?")
  42. .setCancelable(false)
  43. .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
  44. @Override
  45. public void onClick(DialogInterface dialogInterface, int i) {
  46. startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
  47. }
  48. })
  49. .setNegativeButton("No", new DialogInterface.OnClickListener() {
  50. @Override
  51. public void onClick(DialogInterface dialogInterface, int i) {
  52. dialogInterface.cancel();
  53. }
  54. });
  55. final AlertDialog alert = builder.create();
  56. alert.show();
  57. }
  58. private boolean isLocationEnabled(Context context){
  59. // String locationProviders;
  60. boolean enabled = false;
  61. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
  62. int mode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE,
  63. Settings.Secure.LOCATION_MODE_OFF);
  64. enabled = (mode != Settings.Secure.LOCATION_MODE_OFF);
  65. }else{
  66. LocationManager service = (LocationManager) context.getSystemService(LOCATION_SERVICE);
  67. enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER)||service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
  68. }
  69. return enabled;
  70. }
  71. @Override
  72. public int onStartCommand(Intent intent, int flags, int startId) {
  73. mGoogleAPIClient.connect();
  74. return START_STICKY;
  75. }
  76. @Override
  77. public void onConnected(@Nullable Bundle bundle) {
  78. RequestLocationUpdates();
  79. }
  80. private void RequestLocationUpdates() {
  81. if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
  82. != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
  83. != PackageManager.PERMISSION_GRANTED) {
  84. }
  85. LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleAPIClient, mLocationRequest, this); //getting error here..for casting..!
  86. }
  87. @Override
  88. public void onConnectionSuspended(int i) {
  89. }
  90. @Override
  91. public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
  92. }
  93. private Boolean verif = false;
  94. public static GoogleMap mMap;
  95. public static Marker currentMarker = null, destinationMarker = null;
  96. @Override
  97. public void onLocationChanged(Location location) {
  98. this.currentLocation = location;
  99. // Toast.makeText(context, "Ok", Toast.LENGTH_SHORT).show();
  100. if (currentLocation != null) {
  101. if(!M.getUserCategorie(mContext).equals("user_app"))
  102. new MainActivity.setCurrentLocation().execute(String.valueOf(location.getLatitude()),String.valueOf(location.getLongitude()));
  103. }
  104. }
  105. /**driver position Update **/
  106. public static class setCurrentLocation extends AsyncTask<String, Void, String> {
  107. private Context context;
  108. @Override
  109. protected String doInBackground(String... params) {
  110. String url = AppConst.Server_url+"set_position.php";
  111. final String latitude = params[0];
  112. final String longitude = params[1];
  113. StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
  114. url,
  115. new Response.Listener<String>() {
  116. @Override
  117. public void onResponse(String response) {
  118. }
  119. }, new Response.ErrorListener() {
  120. @Override
  121. public void onErrorResponse(VolleyError error) {
  122. }
  123. }) {
  124. @Override
  125. protected Map<String, String> getParams() {
  126. Map<String, String> params = new HashMap<String, String>();
  127. params.put("id_user", M.getID(context));
  128. params.put("user_cat", M.getUserCategorie(context));
  129. params.put("latitude", latitude);
  130. params.put("longitude", longitude);
  131. return params;
  132. }
  133. };
  134. AppController.getInstance().addToRequestQueue(jsonObjReq);
  135. jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
  136. 10000,
  137. DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
  138. DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
  139. return null;
  140. }
  141. @Override
  142. protected void onPostExecute(String result) {
  143. //to add spacing between cards
  144. if (this != null) {
  145. }
  146. }
  147. @Override
  148. protected void onPreExecute() {
  149. }
  150. }
  151. private class changerStatut extends AsyncTask<String, Void, String> {
  152. @Override
  153. protected String doInBackground(String... params) {
  154. String url = AppConst.Server_url+"change_statut.php";
  155. final String online = params[0];
  156. StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
  157. url,
  158. new Response.Listener<String>() {
  159. @Override
  160. public void onResponse(String response) {
  161. try {
  162. M.hideLoadingDialog();
  163. JSONObject json = new JSONObject(response);
  164. JSONObject msg = json.getJSONObject("msg");
  165. String etat = msg.getString("etat");
  166. String online = msg.getString("online");
  167. if(etat.equals("1")){
  168. if(online.equals("yes")) {
  169. switch_statut.setChecked(true);
  170. statut_conducteur.setText("enabled");
  171. M.setStatutConducteur(online,mContext);
  172. }else {
  173. switch_statut.setChecked(false);
  174. statut_conducteur.setText("disabled");
  175. M.setStatutConducteur(online,mContext);
  176. }
  177. }
  178. } catch (JSONException e) {
  179. e.printStackTrace();
  180. }
  181. }
  182. }, new Response.ErrorListener() {
  183. @Override
  184. public void onErrorResponse(VolleyError error) {
  185. M.hideLoadingDialog();
  186. if(switch_statut.isChecked())
  187. switch_statut.setChecked(false);
  188. else
  189. switch_statut.setChecked(true);
  190. }
  191. }) {
  192. @Override
  193. protected Map<String, String> getParams() {
  194. Map<String, String> params = new HashMap<String, String>();
  195. params.put("id_driver", M.getID(mContext));
  196. params.put("online", online);
  197. return params;
  198. }
  199. };
  200. AppController.getInstance().addToRequestQueue(jsonObjReq);
  201. jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
  202. 10000,
  203. DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
  204. DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
  205. return null;
  206. }
  207. @Override
  208. protected void onPostExecute(String result) {
  209. //to add spacing between cards
  210. if (this != null) {
  211. }
  212. }
  213. @Override
  214. protected void onPreExecute() {
  215. }
  216. }
  217. @Override
  218. public void onConnected() {
  219. RequestLocationUpdates();
  220. }
  221. @Override
  222. public void onTaskDone(Object... values) {
  223. }
  224. }

答案1

得分: 0

你还没有初始化你的 mContext 变量。所以在 onCreate 中,在 super.onCreate() 调用之后进行初始化:

  1. @Override
  2. public void onCreate() {
  3. super.onCreate();
  4. mContext = this;
  5. // 你的其他代码
  6. }
英文:

You haven't initialised your mContext variable. So intialise it in the onCreate just after the super.onCreate() call:

  1. @Override
  2. public void onCreate() {
  3. super.onCreate();
  4. mContext = this;
  5. //rest of your code
  6. }

huangapple
  • 本文由 发表于 2020年8月27日 23:12:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63619045.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定