首页 > 解决方案 > Android:由于 NULL POINTER EXCEPTION 而无法启动服务

问题描述

我正在我的主要活动的 onCreate 中创建一个服务,但我得到 java.lang.RuntimeException: Unable to instantiate service com.ram.courier.service.CheckTimeService: java.lang.NullPointerException: Attempt to invoke virtual method 'android. content.Context android.content.Context.getApplicationContext()' 在空对象引用上

这是我开始服务的主要活动:

if(isServiceRunning(getApplicationContext() ,CheckTimeService.class)){
    Log.d("APP","RUNNING SERVICE");
}
else{
    Intent myServiceIntent = new Intent(SplashScreen.this, CheckTimeService.class);
    startService(myServiceIntent);
}

}

以下是我的服务类:

   public class CheckTimeService extends Service  {

    final Handler handler = new Handler();
    Runnable run;
    DatabaseAccess databaseAccess;
    ApiCall apiCall;
    final String startTime = "15:00:00";
    final String endTime = "18:30:00";
//    Context context = this.getApplicationContext();
    Calendar now = Calendar.getInstance();
    int hour = now.get(Calendar.HOUR_OF_DAY); //24 hour format
    int minute = now.get(Calendar.MINUTE);
    Date date = parseDate(hour + ":" + minute); //current time


    //function for parsing the time
    private Date parseDate(String date) {
        final String inputFormat = "HH:mm";
        SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
        try{
            return inputParser.parse(date);
        }catch (java.text.ParseException e){
            return new Date(0);
        }
    }
    Context context = this.getApplicationContext();
    DatabaseOpenHelper myDB =  new DatabaseOpenHelper(getApplicationContext());
    SQLiteDatabase db = myDB.getReadableDatabase();
    Cursor sessID = db.rawQuery(" SELECT * FROM " + DataConstants.TABLE_SESSION + " ORDER BY SessionID DESC LIMIT 1", null);
    String sessionID = sessID.toString();//convert cursor result to string
    Cursor DelVehDepID = db.rawQuery(" SELECT * FROM " + DataConstants.TABLE_DEL_VEH_DEP + " ORDER BY " + DataConstants.COLUMN_VEH_DEP_ID + "DESC LIMIT 1", null);
   // JSONObject jsonObjectDelVehDepID = new JSONObject(String.valueOf(DelVehDepID));//convert string to json object
  //  String delvehdepid = jsonObjectDelVehDepID.toString();//convert cursor to string
    String delvehdepid = DelVehDepID.toString();

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        run = new Runnable() {
            @Override
            public void run() {
            Date compareTimeOne = parseDate(startTime);
            Date compareTimeTwo = parseDate(endTime);
            if (compareTimeOne.before(date) && compareTimeTwo.after(date)) {
                Log.d("test", " Time is between " + startTime + " and " + endTime);
                //call to API
                apiCall = new ApiCall(getApplicationContext(), AppConstants.TASK_API_CHECK_IS_CLOSED_SESSION, delvehdepid,
                        AppConstants.API_CHECK_IS_CLOSED_SESSION + sessionID, new SyncServiceListener() {
                    @Override
                    public void onSuccess(int taskID, String Response) {
                        try {
                            JSONObject json = new JSONObject(Response);
                            Log.d("onSuccess",json.toString());
                            CommonCalls.getInstance().trackSyncRequestService(getApplicationContext(), AppConstants.TASK_API_CHECK_IS_CLOSED_SESSION+sessionID,json.toString());

                            JSONObject result = json.getJSONObject("Result");
                            if(result!=null && result.getString("Result")!=null){
                                if(result.getString("Result")=="true"){
                                    //clear session data and logout drivers and crew members
                                    PreferenceHandler.writeBoolean(CheckTimeService.this, "missing_pod", false);
                                    PreferenceHandler.writeBoolean(CheckTimeService.this, "new_session", true);
                                    PreferenceHandler.writeString(CheckTimeService.this, "activity", "");
                                    PreferenceHandler.writeString(CheckTimeService.this, "session_id", "");
                                    PreferenceHandler.writeString(CheckTimeService.this, "POD_bag", "");
                                    DatabaseAccess.getInstance(CheckTimeService.this).open();
                                    DatabaseAccess.getInstance(CheckTimeService.this).clearSheetsData();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(int taskID, String Response) {
                        Log.d("ERROR","ERROR...NO RESPONSE" + Response);

                    }
                });
            }
            else
            {
                Log.d("test", "Time is not in between" + startTime + "and" + endTime);
            }
                handler.postDelayed(this,1000);
            }
        };
                handler.post(run);
                return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(run);
    }

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

标签: androidservicenullpointerexception

解决方案


推荐阅读