Search in sources :

Example 1 with InstancesDao

use of org.odk.collect.android.dao.InstancesDao in project collect by opendatakit.

the class InstanceUploader method onPostExecute.

@Override
protected void onPostExecute(Outcome outcome) {
    synchronized (this) {
        if (outcome != null && stateListener != null) {
            if (outcome.authRequestingServer != null) {
                stateListener.authRequest(outcome.authRequestingServer, outcome.messagesByInstanceId);
            } else {
                stateListener.uploadingComplete(outcome.messagesByInstanceId);
                Set<String> keys = outcome.messagesByInstanceId.keySet();
                Iterator<String> it = keys.iterator();
                int count = keys.size();
                while (count > 0) {
                    String[] selectionArgs;
                    if (count > ApplicationConstants.SQLITE_MAX_VARIABLE_NUMBER - 1) {
                        selectionArgs = new String[ApplicationConstants.SQLITE_MAX_VARIABLE_NUMBER];
                    } else {
                        selectionArgs = new String[count + 1];
                    }
                    StringBuilder selection = new StringBuilder();
                    selection.append(InstanceProviderAPI.InstanceColumns._ID + " IN (");
                    int i = 0;
                    while (it.hasNext() && i < selectionArgs.length - 1) {
                        selectionArgs[i] = it.next();
                        selection.append("?");
                        if (i != selectionArgs.length - 2) {
                            selection.append(",");
                        }
                        i++;
                    }
                    count -= selectionArgs.length - 1;
                    selection.append(") and status=?");
                    selectionArgs[i] = InstanceProviderAPI.STATUS_SUBMITTED;
                    Cursor results = null;
                    try {
                        results = new InstancesDao().getInstancesCursor(selection.toString(), selectionArgs);
                        if (results.getCount() > 0) {
                            List<Long> toDelete = new ArrayList<>();
                            results.moveToPosition(-1);
                            boolean isFormAutoDeleteOptionEnabled = (boolean) GeneralSharedPreferences.getInstance().get(PreferenceKeys.KEY_DELETE_AFTER_SEND);
                            String formId;
                            while (results.moveToNext()) {
                                formId = results.getString(results.getColumnIndex(InstanceProviderAPI.InstanceColumns.JR_FORM_ID));
                                if (isFormAutoDeleteEnabled(formId, isFormAutoDeleteOptionEnabled)) {
                                    toDelete.add(results.getLong(results.getColumnIndex(InstanceProviderAPI.InstanceColumns._ID)));
                                }
                            }
                            DeleteInstancesTask dit = new DeleteInstancesTask();
                            dit.setContentResolver(Collect.getInstance().getContentResolver());
                            dit.execute(toDelete.toArray(new Long[toDelete.size()]));
                        }
                    } catch (SQLException e) {
                        Timber.e(e);
                    } finally {
                        if (results != null) {
                            results.close();
                        }
                    }
                }
            }
        }
    }
}
Also used : SQLException(android.database.SQLException) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) InstancesDao(org.odk.collect.android.dao.InstancesDao)

Example 2 with InstancesDao

use of org.odk.collect.android.dao.InstancesDao in project collect by opendatakit.

the class SaveToDiskTask method updateInstanceDatabase.

private void updateInstanceDatabase(boolean incomplete, boolean canEditAfterCompleted) {
    FormController formController = Collect.getInstance().getFormController();
    // Update the instance database...
    ContentValues values = new ContentValues();
    if (instanceName != null) {
        values.put(InstanceColumns.DISPLAY_NAME, instanceName);
    }
    if (incomplete || !markCompleted) {
        values.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_INCOMPLETE);
    } else {
        values.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_COMPLETE);
    }
    // update this whether or not the status is complete...
    values.put(InstanceColumns.CAN_EDIT_WHEN_COMPLETE, Boolean.toString(canEditAfterCompleted));
    // If FormEntryActivity was started with an Instance, just update that instance
    if (Collect.getInstance().getContentResolver().getType(uri).equals(InstanceColumns.CONTENT_ITEM_TYPE)) {
        int updated = Collect.getInstance().getContentResolver().update(uri, values, null, null);
        if (updated > 1) {
            Timber.w("Updated more than one entry, that's not good: %s", uri.toString());
        } else if (updated == 1) {
            Timber.i("Instance successfully updated");
        } else {
            Timber.e("Instance doesn't exist but we have its Uri!! %s", uri.toString());
        }
    } else if (Collect.getInstance().getContentResolver().getType(uri).equals(FormsColumns.CONTENT_ITEM_TYPE)) {
        // If FormEntryActivity was started with a form, then it's likely the first time we're
        // saving.
        // However, it could be a not-first time saving if the user has been using the manual
        // 'save data' option from the menu. So try to update first, then make a new one if that
        // fails.
        String instancePath = formController.getInstanceFile().getAbsolutePath();
        String where = InstanceColumns.INSTANCE_FILE_PATH + "=?";
        String[] whereArgs = { instancePath };
        int updated = new InstancesDao().updateInstance(values, where, whereArgs);
        if (updated > 1) {
            Timber.w("Updated more than one entry, that's not good: %s", instancePath);
        } else if (updated == 1) {
            Timber.i("Instance found and successfully updated: %s", instancePath);
        // already existed and updated just fine
        } else {
            Timber.i("No instance found, creating");
            // Entry didn't exist, so create it.
            Cursor c = null;
            try {
                // retrieve the form definition...
                c = Collect.getInstance().getContentResolver().query(uri, null, null, null, null);
                c.moveToFirst();
                String formname = c.getString(c.getColumnIndex(FormsColumns.DISPLAY_NAME));
                String submissionUri = null;
                if (!c.isNull(c.getColumnIndex(FormsColumns.SUBMISSION_URI))) {
                    submissionUri = c.getString(c.getColumnIndex(FormsColumns.SUBMISSION_URI));
                }
                // add missing fields into values
                values.put(InstanceColumns.INSTANCE_FILE_PATH, instancePath);
                values.put(InstanceColumns.SUBMISSION_URI, submissionUri);
                if (instanceName != null) {
                    values.put(InstanceColumns.DISPLAY_NAME, instanceName);
                } else {
                    values.put(InstanceColumns.DISPLAY_NAME, formname);
                }
                String jrformid = c.getString(c.getColumnIndex(FormsColumns.JR_FORM_ID));
                String jrversion = c.getString(c.getColumnIndex(FormsColumns.JR_VERSION));
                values.put(InstanceColumns.JR_FORM_ID, jrformid);
                values.put(InstanceColumns.JR_VERSION, jrversion);
            } finally {
                if (c != null) {
                    c.close();
                }
            }
            uri = new InstancesDao().saveInstance(values);
        }
    }
}
Also used : FormController(org.odk.collect.android.logic.FormController) ContentValues(android.content.ContentValues) InstancesDao(org.odk.collect.android.dao.InstancesDao) Cursor(android.database.Cursor)

Example 3 with InstancesDao

use of org.odk.collect.android.dao.InstancesDao in project collect by opendatakit.

the class NetworkReceiver method uploadForms.

/**
 * @param isFormAutoSendOptionEnabled represents whether the auto-send option is enabled at the app level
 */
private void uploadForms(Context context, boolean isFormAutoSendOptionEnabled) {
    if (!running) {
        running = true;
        ArrayList<Long> toUpload = new ArrayList<>();
        Cursor c = new InstancesDao().getFinalizedInstancesCursor();
        try {
            if (c != null && c.getCount() > 0) {
                c.move(-1);
                String formId;
                while (c.moveToNext()) {
                    formId = c.getString(c.getColumnIndex(InstanceColumns.JR_FORM_ID));
                    if (isFormAutoSendEnabled(formId, isFormAutoSendOptionEnabled)) {
                        Long l = c.getLong(c.getColumnIndex(InstanceColumns._ID));
                        toUpload.add(l);
                    }
                }
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }
        if (toUpload.size() < 1) {
            running = false;
            return;
        }
        Long[] toSendArray = new Long[toUpload.size()];
        toUpload.toArray(toSendArray);
        GeneralSharedPreferences settings = GeneralSharedPreferences.getInstance();
        String protocol = (String) settings.get(PreferenceKeys.KEY_PROTOCOL);
        if (protocol.equals(context.getString(R.string.protocol_google_sheets))) {
            String googleUsername = (String) settings.get(PreferenceKeys.KEY_SELECTED_GOOGLE_ACCOUNT);
            if (googleUsername == null || googleUsername.isEmpty()) {
                // just quit if there's no username
                running = false;
                return;
            }
            GoogleAccountsManager accountsManager = new GoogleAccountsManager(Collect.getInstance());
            accountsManager.getCredential().setSelectedAccountName(googleUsername);
            instanceGoogleSheetsUploader = new InstanceGoogleSheetsUploader(accountsManager);
            instanceGoogleSheetsUploader.setUploaderListener(this);
            instanceGoogleSheetsUploader.execute(toSendArray);
        } else {
            // get the username, password, and server from preferences
            String storedUsername = (String) settings.get(PreferenceKeys.KEY_USERNAME);
            String storedPassword = (String) settings.get(PreferenceKeys.KEY_PASSWORD);
            String server = (String) settings.get(PreferenceKeys.KEY_SERVER_URL);
            String url = server + settings.get(PreferenceKeys.KEY_FORMLIST_URL);
            Uri u = Uri.parse(url);
            WebUtils.addCredentials(storedUsername, storedPassword, u.getHost());
            instanceServerUploader = new InstanceServerUploader();
            instanceServerUploader.setUploaderListener(this);
            instanceServerUploader.execute(toSendArray);
        }
    }
}
Also used : InstanceServerUploader(org.odk.collect.android.tasks.InstanceServerUploader) GoogleAccountsManager(org.odk.collect.android.utilities.gdrive.GoogleAccountsManager) InstancesDao(org.odk.collect.android.dao.InstancesDao) ArrayList(java.util.ArrayList) GeneralSharedPreferences(org.odk.collect.android.preferences.GeneralSharedPreferences) Cursor(android.database.Cursor) InstanceGoogleSheetsUploader(org.odk.collect.android.tasks.InstanceGoogleSheetsUploader) Uri(android.net.Uri)

Example 4 with InstancesDao

use of org.odk.collect.android.dao.InstancesDao in project collect by opendatakit.

the class NetworkReceiver method uploadingComplete.

@Override
public void uploadingComplete(HashMap<String, String> result) {
    // task is done
    if (instanceServerUploader != null) {
        instanceServerUploader.setUploaderListener(null);
    }
    if (instanceGoogleSheetsUploader != null) {
        instanceGoogleSheetsUploader.setUploaderListener(null);
    }
    running = false;
    StringBuilder message = new StringBuilder();
    message.append(Collect.getInstance().getString(R.string.odk_auto_note)).append(" :: \n\n");
    if (result == null) {
        message.append(Collect.getInstance().getString(R.string.odk_auth_auth_fail));
    } else {
        StringBuilder selection = new StringBuilder();
        Set<String> keys = result.keySet();
        Iterator<String> it = keys.iterator();
        String[] selectionArgs = new String[keys.size()];
        int i = 0;
        while (it.hasNext()) {
            String id = it.next();
            selection.append(InstanceColumns._ID + "=?");
            selectionArgs[i++] = id;
            if (i != keys.size()) {
                selection.append(" or ");
            }
        }
        Cursor results = null;
        try {
            results = new InstancesDao().getInstancesCursor(selection.toString(), selectionArgs);
            if (results.getCount() > 0) {
                results.moveToPosition(-1);
                while (results.moveToNext()) {
                    String name = results.getString(results.getColumnIndex(InstanceColumns.DISPLAY_NAME));
                    String id = results.getString(results.getColumnIndex(InstanceColumns._ID));
                    message.append(name).append(" - ").append(result.get(id)).append("\n\n");
                }
            }
        } finally {
            if (results != null) {
                results.close();
            }
        }
    }
    Intent notifyIntent = new Intent(Collect.getInstance(), NotificationActivity.class);
    notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    notifyIntent.putExtra(NotificationActivity.NOTIFICATION_KEY, message.toString().trim());
    PendingIntent pendingNotify = PendingIntent.getActivity(Collect.getInstance(), 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(Collect.getInstance()).setSmallIcon(R.drawable.notes).setContentTitle(Collect.getInstance().getString(R.string.odk_auto_note)).setContentIntent(pendingNotify).setContentText(message.toString().trim()).setAutoCancel(true).setLargeIcon(BitmapFactory.decodeResource(Collect.getInstance().getResources(), android.R.drawable.ic_dialog_info));
    NotificationManager notificationManager = (NotificationManager) Collect.getInstance().getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(1328974928, builder.build());
}
Also used : NotificationManager(android.app.NotificationManager) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) Cursor(android.database.Cursor) InstancesDao(org.odk.collect.android.dao.InstancesDao) NotificationCompat(android.support.v4.app.NotificationCompat) PendingIntent(android.app.PendingIntent)

Example 5 with InstancesDao

use of org.odk.collect.android.dao.InstancesDao in project collect by opendatakit.

the class InstanceGoogleSheetsUploader method uploadInstances.

private Map<String, String> uploadInstances(String selection, String[] selectionArgs, int low, int instanceCount) {
    final Map<String, String> messagesByInstanceId = new HashMap<>();
    try (Cursor cursor = new InstancesDao().getInstancesCursor(selection, selectionArgs)) {
        if (cursor.getCount() > 0) {
            cursor.moveToPosition(-1);
            while (cursor.moveToNext()) {
                if (isCancelled()) {
                    return messagesByInstanceId;
                }
                final String id = cursor.getString(cursor.getColumnIndex(InstanceColumns._ID));
                jrFormId = cursor.getString(cursor.getColumnIndex(InstanceColumns.JR_FORM_ID));
                Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id);
                ContentValues cv = new ContentValues();
                Cursor formCursor = new FormsDao().getFormsCursorForFormId(jrFormId);
                String md5 = null;
                String formFilePath = null;
                if (formCursor.getCount() > 0) {
                    formCursor.moveToFirst();
                    md5 = formCursor.getString(formCursor.getColumnIndex(FormsColumns.MD5_HASH));
                    formFilePath = formCursor.getString(formCursor.getColumnIndex(FormsColumns.FORM_FILE_PATH));
                }
                if (md5 == null) {
                    // fail and exit
                    Timber.e("no md5");
                    return messagesByInstanceId;
                }
                publishProgress(cursor.getPosition() + 1 + low, instanceCount);
                String instance = cursor.getString(cursor.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
                try {
                    uploadOneInstance(new File(instance), formFilePath, getGoogleSheetsUrl(cursor));
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
                    Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    messagesByInstanceId.put(id, Collect.getInstance().getString(R.string.success));
                } catch (UploadException e) {
                    Timber.e(e);
                    messagesByInstanceId.put(id, e.getMessage() != null ? e.getMessage() : e.getCause().getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                }
            }
        }
    }
    return messagesByInstanceId;
}
Also used : ContentValues(android.content.ContentValues) FormsDao(org.odk.collect.android.dao.FormsDao) InstancesDao(org.odk.collect.android.dao.InstancesDao) HashMap(java.util.HashMap) Cursor(android.database.Cursor) Uri(android.net.Uri) File(java.io.File)

Aggregations

InstancesDao (org.odk.collect.android.dao.InstancesDao)15 Cursor (android.database.Cursor)12 ContentValues (android.content.ContentValues)3 Uri (android.net.Uri)3 File (java.io.File)3 ArrayList (java.util.ArrayList)3 Intent (android.content.Intent)2 SQLException (android.database.SQLException)2 View (android.view.View)2 OnClickListener (android.view.View.OnClickListener)2 TextView (android.widget.TextView)2 HashMap (java.util.HashMap)2 FormController (org.odk.collect.android.logic.FormController)2 NotificationManager (android.app.NotificationManager)1 PendingIntent (android.app.PendingIntent)1 SharedPreferences (android.content.SharedPreferences)1 ConnectivityManager (android.net.ConnectivityManager)1 NetworkInfo (android.net.NetworkInfo)1 NotificationCompat (android.support.v4.app.NotificationCompat)1 AdapterView (android.widget.AdapterView)1