Search in sources :

Example 6 with InstancesDao

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

the class InstancesDaoHelper method getLastInstanceUri.

public static Uri getLastInstanceUri(String path) {
    try (Cursor c = new InstancesDao().getInstancesCursorForFilePath(path)) {
        if (c != null && c.getCount() > 0) {
            // should only be one...
            c.moveToFirst();
            String id = c.getString(c.getColumnIndex(InstanceProviderAPI.InstanceColumns._ID));
            return Uri.withAppendedPath(InstanceProviderAPI.InstanceColumns.CONTENT_URI, id);
        }
    }
    return null;
}
Also used : InstancesDao(org.odk.collect.android.dao.InstancesDao) Cursor(android.database.Cursor)

Example 7 with InstancesDao

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

the class GoogleSheetsUploaderActivity method uploadingComplete.

@Override
public void uploadingComplete(HashMap<String, String> result) {
    try {
        dismissDialog(PROGRESS_DIALOG);
    } catch (Exception e) {
    // tried to close a dialog not open. don't care.
    }
    if (result == null) {
        // probably got an auth request, so ignore
        return;
    }
    Timber.i("uploadingComplete: Processing results ( %d ) from upload of %d instances!", result.size(), instancesToSend.length);
    StringBuilder selection = new StringBuilder();
    Set<String> keys = result.keySet();
    StringBuilder message = new StringBuilder();
    if (keys.size() == 0) {
        if (instanceGoogleSheetsUploader.isAuthFailed()) {
            message.append(getString(R.string.google_auth_io_exception_msg));
            instanceGoogleSheetsUploader.setAuthFailedToFalse();
        } else {
            message.append(getString(R.string.no_forms_uploaded));
        }
    } else {
        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");
                }
            } else {
                if (instanceGoogleSheetsUploader.isAuthFailed()) {
                    message.append(getString(R.string.google_auth_io_exception_msg));
                    instanceGoogleSheetsUploader.setAuthFailedToFalse();
                } else {
                    message.append(getString(R.string.no_forms_uploaded));
                }
            }
        } finally {
            if (results != null) {
                results.close();
            }
        }
    }
    createAlertDialog(message.toString().trim());
}
Also used : InstancesDao(org.odk.collect.android.dao.InstancesDao) Cursor(android.database.Cursor)

Example 8 with InstancesDao

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

the class MainMenuActivity method onCreate.

// private static boolean DO_NOT_EXIT = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_menu);
    initToolbar();
    // enter data button. expects a result.
    enterDataButton = findViewById(R.id.enter_data);
    enterDataButton.setText(getString(R.string.enter_data_button));
    enterDataButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (Collect.allowClick()) {
                Collect.getInstance().getActivityLogger().logAction(this, "fillBlankForm", "click");
                Intent i = new Intent(getApplicationContext(), FormChooserList.class);
                startActivity(i);
            }
        }
    });
    // review data button. expects a result.
    reviewDataButton = findViewById(R.id.review_data);
    reviewDataButton.setText(getString(R.string.review_data_button));
    reviewDataButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (Collect.allowClick()) {
                Collect.getInstance().getActivityLogger().logAction(this, ApplicationConstants.FormModes.EDIT_SAVED, "click");
                Intent i = new Intent(getApplicationContext(), InstanceChooserList.class);
                i.putExtra(ApplicationConstants.BundleKeys.FORM_MODE, ApplicationConstants.FormModes.EDIT_SAVED);
                startActivity(i);
            }
        }
    });
    // send data button. expects a result.
    sendDataButton = findViewById(R.id.send_data);
    sendDataButton.setText(getString(R.string.send_data_button));
    sendDataButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (Collect.allowClick()) {
                Collect.getInstance().getActivityLogger().logAction(this, "uploadForms", "click");
                Intent i = new Intent(getApplicationContext(), InstanceUploaderList.class);
                startActivity(i);
            }
        }
    });
    // View sent forms
    viewSentFormsButton = findViewById(R.id.view_sent_forms);
    viewSentFormsButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (Collect.allowClick()) {
                Collect.getInstance().getActivityLogger().logAction(this, ApplicationConstants.FormModes.VIEW_SENT, "click");
                Intent i = new Intent(getApplicationContext(), InstanceChooserList.class);
                i.putExtra(ApplicationConstants.BundleKeys.FORM_MODE, ApplicationConstants.FormModes.VIEW_SENT);
                startActivity(i);
            }
        }
    });
    // manage forms button. no result expected.
    getFormsButton = findViewById(R.id.get_forms);
    getFormsButton.setText(getString(R.string.get_forms));
    getFormsButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (Collect.allowClick()) {
                Collect.getInstance().getActivityLogger().logAction(this, "downloadBlankForms", "click");
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainMenuActivity.this);
                String protocol = sharedPreferences.getString(PreferenceKeys.KEY_PROTOCOL, getString(R.string.protocol_odk_default));
                Intent i = null;
                if (protocol.equalsIgnoreCase(getString(R.string.protocol_google_sheets))) {
                    if (PlayServicesUtil.isGooglePlayServicesAvailable(MainMenuActivity.this)) {
                        i = new Intent(getApplicationContext(), GoogleDriveActivity.class);
                    } else {
                        PlayServicesUtil.showGooglePlayServicesAvailabilityErrorDialog(MainMenuActivity.this);
                        return;
                    }
                } else {
                    i = new Intent(getApplicationContext(), FormDownloadList.class);
                }
                startActivity(i);
            }
        }
    });
    // manage forms button. no result expected.
    manageFilesButton = findViewById(R.id.manage_forms);
    manageFilesButton.setText(getString(R.string.manage_files));
    manageFilesButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (Collect.allowClick()) {
                Collect.getInstance().getActivityLogger().logAction(this, "deleteSavedForms", "click");
                Intent i = new Intent(getApplicationContext(), FileManagerTabs.class);
                startActivity(i);
            }
        }
    });
    // must be at the beginning of any activity that can be called from an
    // external intent
    Timber.i("Starting up, creating directories");
    try {
        Collect.createODKDirs();
    } catch (RuntimeException e) {
        createErrorDialog(e.getMessage(), EXIT);
        return;
    }
    {
        // dynamically construct the "ODK Collect vA.B" string
        TextView mainMenuMessageLabel = findViewById(R.id.main_menu_header);
        mainMenuMessageLabel.setText(Collect.getInstance().getVersionedAppName());
    }
    File f = new File(Collect.ODK_ROOT + "/collect.settings");
    File j = new File(Collect.ODK_ROOT + "/collect.settings.json");
    // Give JSON file preference
    if (j.exists()) {
        boolean success = SharedPreferencesUtils.loadSharedPreferencesFromJSONFile(j);
        if (success) {
            ToastUtils.showLongToast(R.string.settings_successfully_loaded_file_notification);
            j.delete();
            // Delete settings file to prevent overwrite of settings from JSON file on next startup
            if (f.exists()) {
                f.delete();
            }
        } else {
            ToastUtils.showLongToast(R.string.corrupt_settings_file_notification);
        }
    } else if (f.exists()) {
        boolean success = loadSharedPreferencesFromFile(f);
        if (success) {
            ToastUtils.showLongToast(R.string.settings_successfully_loaded_file_notification);
            f.delete();
        } else {
            ToastUtils.showLongToast(R.string.corrupt_settings_file_notification);
        }
    }
    reviewSpacer = findViewById(R.id.review_spacer);
    getFormsSpacer = findViewById(R.id.get_forms_spacer);
    adminPreferences = this.getSharedPreferences(AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
    InstancesDao instancesDao = new InstancesDao();
    // count for finalized instances
    try {
        finalizedCursor = instancesDao.getFinalizedInstancesCursor();
    } catch (Exception e) {
        createErrorDialog(e.getMessage(), EXIT);
        return;
    }
    if (finalizedCursor != null) {
        startManagingCursor(finalizedCursor);
    }
    completedCount = finalizedCursor != null ? finalizedCursor.getCount() : 0;
    getContentResolver().registerContentObserver(InstanceColumns.CONTENT_URI, true, contentObserver);
    // count for saved instances
    try {
        savedCursor = instancesDao.getUnsentInstancesCursor();
    } catch (Exception e) {
        createErrorDialog(e.getMessage(), EXIT);
        return;
    }
    if (savedCursor != null) {
        startManagingCursor(savedCursor);
    }
    savedCount = savedCursor != null ? savedCursor.getCount() : 0;
    // count for view sent form
    try {
        viewSentCursor = instancesDao.getSentInstancesCursor();
    } catch (Exception e) {
        createErrorDialog(e.getMessage(), EXIT);
        return;
    }
    if (viewSentCursor != null) {
        startManagingCursor(viewSentCursor);
    }
    viewSentCount = viewSentCursor != null ? viewSentCursor.getCount() : 0;
    updateButtons();
    setupGoogleAnalytics();
}
Also used : SharedPreferences(android.content.SharedPreferences) Intent(android.content.Intent) View(android.view.View) TextView(android.widget.TextView) IOException(java.io.IOException) InstancesDao(org.odk.collect.android.dao.InstancesDao) OnClickListener(android.view.View.OnClickListener) TextView(android.widget.TextView) File(java.io.File)

Example 9 with InstancesDao

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

the class InstanceServerUploaderTest method setUp.

@Before
public void setUp() throws Exception {
    resetInstancesContentProvider();
    dao = new InstancesDao();
}
Also used : InstancesDao(org.odk.collect.android.dao.InstancesDao) Before(org.junit.Before)

Example 10 with InstancesDao

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

the class InstanceServerUploader method processChunk.

private boolean processChunk(int low, int high, Outcome outcome, Long... values) {
    if (values == null) {
        // don't try anything if values is null
        return false;
    }
    StringBuilder selectionBuf = new StringBuilder(InstanceColumns._ID + " IN (");
    String[] selectionArgs = new String[high - low];
    for (int i = 0; i < (high - low); i++) {
        if (i > 0) {
            selectionBuf.append(",");
        }
        selectionBuf.append("?");
        selectionArgs[i] = values[i + low].toString();
    }
    selectionBuf.append(")");
    String selection = selectionBuf.toString();
    String deviceId = new PropertyManager(Collect.getInstance().getApplicationContext()).getSingularProperty(PropertyManager.withUri(PropertyManager.PROPMGR_DEVICE_ID));
    // get shared HttpContext so that authentication and cookies are retained.
    HttpContext localContext = Collect.getInstance().getHttpContext();
    Map<Uri, Uri> uriRemap = new HashMap<Uri, Uri>();
    Cursor c = null;
    try {
        c = new InstancesDao().getInstancesCursor(selection, selectionArgs);
        if (c != null && c.getCount() > 0) {
            c.moveToPosition(-1);
            while (c.moveToNext()) {
                if (isCancelled()) {
                    return false;
                }
                publishProgress(c.getPosition() + 1 + low, values.length);
                String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
                String id = c.getString(c.getColumnIndex(InstanceColumns._ID));
                Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id);
                // Use the app's configured URL unless the form included a submission URL
                int subIdx = c.getColumnIndex(InstanceColumns.SUBMISSION_URI);
                String urlString = c.isNull(subIdx) ? getServerSubmissionURL() : c.getString(subIdx).trim();
                // add the deviceID to the request...
                try {
                    urlString += "?deviceID=" + URLEncoder.encode(deviceId, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    // unreachable...
                    Timber.i(e, "Error encoding URL for device id : %s", deviceId);
                }
                if (!uploadOneSubmission(urlString, id, instance, toUpdate, localContext, uriRemap, outcome)) {
                    // get credentials...
                    return false;
                }
            }
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return true;
}
Also used : InstancesDao(org.odk.collect.android.dao.InstancesDao) HashMap(java.util.HashMap) PropertyManager(org.odk.collect.android.logic.PropertyManager) HttpContext(org.opendatakit.httpclientandroidlib.protocol.HttpContext) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Cursor(android.database.Cursor) Uri(android.net.Uri)

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