mardi 29 décembre 2015

Android Service can't open database, because (activity / context /this) is null

I need from MyService (extends Service) start new AsyncLoadJSONDoc(this).execute(), but problem is "this" can't be there. If im working from Activity there is no problem, i just have to create constructor for taking activity in asynctask. The main problem is i need OPEN my database below in asynctask from service (null pointer exception) Service is checking cloud for new information and saving in the android database. (every minute)

public class AsyncLoadJSONDoc extends AsyncTask<URL, Integer, ArrayList<Storage.JSONDocument>> {
private static final String TAG = "AsyncLoadJSONDoc";
Activity mActivity;`
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss.SSS'Z'");
Date date = new Date();

private static final String TAG = "AsyncLoadJSONDoc";
Activity mActivity;    

public AsyncLoadJSONDoc(Activity activity){
    mActivity = activity;
}

@Override
protected ArrayList<Storage.JSONDocument> doInBackground(URL... params) {
    StorageService storageService = App42API.buildStorageService();
    Storage storage = storageService.findAllDocuments(
            Constants.CLOUD_DB_NAME, Constants.COLLECTION_NAME);
    ArrayList<Storage.JSONDocument> jsonDocList = storage.getJsonDocList();
    Log.i(TAG, "Velikost databaze> " + jsonDocList.size());
    return jsonDocList;
}


protected void onPostExecute(ArrayList<Storage.JSONDocument> jsonDocList) {
    saveToDatabase(jsonDocList);
}

private void saveToDatabase(ArrayList<Storage.JSONDocument> jsonDocs) {
    Log.i(TAG, "saveToDatabase");
    Log.i(TAG + " Start>", df.format(date));

    SQLiteDatabase db = (new DatabaseHelper(mActivity)).getWritableDatabase(); // <---There is null exception
    ContentValues cv=new ContentValues();

    DatabaseHelper dq = new DatabaseHelper(mActivity);
    dq.onUpgrade(db, 1, 2);

    for(Storage.JSONDocument oneJsonDoc : jsonDocs) {
        cv.put(Constants.UPDATED_AT, oneJsonDoc.getUpdatedAt());
        cv.put(Constants.CREATED_AT, oneJsonDoc.getCreatedAt());
        cv.put(Constants.DOC_ID, oneJsonDoc.getDocId());
        cv.put(Constants.JSON, oneJsonDoc.getJsonDoc());
        if (oneJsonDoc.getLocation() == null) {
            Log.i(TAG, "Location NULL");
            cv.put(Constants.LATITUDE, (byte[]) null);
            cv.put(Constants.LONGITUDE, (byte[]) null);
        } else {
            cv.put(Constants.LATITUDE, oneJsonDoc.getLocation().getLat().floatValue());
            cv.put(Constants.LONGITUDE, oneJsonDoc.getLocation().getLng().floatValue());
        }
        db.insert(Constants.TABLE_NAME, Constants.JSON, cv);
        Log.i(TAG, "insert");
    }
    db.close();
    Log.i(TAG + " End>", df.format(date));
}

}

Aucun commentaire:

Enregistrer un commentaire