List of usage examples for android.database Cursor isClosed
boolean isClosed();
From source file:org.opendatakit.services.legacy.tasks.InstanceUploaderTask.java
@Override protected InstanceUploadOutcome doInBackground(String... toUpload) { mOutcome = new InstanceUploadOutcome(); mOutcome.mResults = new HashMap<String, String>(); mOutcome.mAuthRequestingServer = null; PropertiesSingleton props = CommonToolProperties.get(appContext, appName); String urlString = null;// www . j av a2 s. co m urlString = props.getProperty(CommonToolProperties.KEY_SYNC_SERVER_URL); urlString = urlString + "/submission"; URI u = null; try { URL url = new URL(URLDecoder.decode(urlString, CharEncoding.UTF_8)); u = url.toURI(); } catch (MalformedURLException e) { WebLogger.getLogger(appName).printStackTrace(e); mOutcome.mResults.put("unknown", fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); return mOutcome; } catch (URISyntaxException e) { WebLogger.getLogger(appName).printStackTrace(e); mOutcome.mResults.put("unknown", fail + "invalid uri: " + urlString + " :: details: " + e.getMessage()); return mOutcome; } catch (UnsupportedEncodingException e) { WebLogger.getLogger(appName).printStackTrace(e); mOutcome.mResults.put("unknown", fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); return mOutcome; } CredentialsProvider credsProvider = new BasicCredentialsProvider(); CookieStore cookieStore = new BasicCookieStore(); String authType = props.getProperty(CommonToolProperties.KEY_AUTHENTICATION_TYPE); if (authType.equals(appContext.getString(R.string.credential_type_username_password))) { String username = props.getProperty(CommonToolProperties.KEY_USERNAME); String password = props.getProperty(CommonToolProperties.KEY_PASSWORD); registerUsernamePassword(credsProvider, username, password, u.getHost()); } else if (authType.equals(appContext.getString(R.string.credential_type_google_account))) { throw new IllegalStateException("legacy doesn't support Google Authentication"); } // context holds authentication state machine, so it cannot be // shared across independent activities. HttpClientContext localContext = HttpClientContext.create(); localContext.setCookieStore(cookieStore); localContext.setCredentialsProvider(credsProvider); CloseableHttpClient httpclient = WebUtils.createHttpClient(WebUtils.CONNECTION_TIMEOUT); Map<URI, URI> uriRemap = new HashMap<URI, URI>(); for (int i = 0; i < toUpload.length; ++i) { if (isCancelled()) { return mOutcome; } publishProgress(i + 1, toUpload.length); Uri toUpdate = Uri.withAppendedPath(InstanceProviderAPI.CONTENT_URI, appName + "/" + uploadTableId + "/" + StringEscapeUtils.escapeHtml4(toUpload[i])); Cursor c = null; try { c = appContext.getContentResolver().query(toUpdate, null, null, null, null); if (c.getCount() == 1 && c.moveToFirst()) { String id = CursorUtils.getIndexAsString(c, c.getColumnIndex(InstanceColumns._ID)); String dataTableInstanceId = CursorUtils.getIndexAsString(c, c.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID)); String lastOutcome = CursorUtils.getIndexAsString(c, c.getColumnIndex(InstanceColumns.XML_PUBLISH_STATUS)); String submissionInstanceId = LocalizationUtils.genUUID(); // submissions always get a new legacy instance id UNLESS the last // submission failed, // in which case we retry the submission using the legacy instance id // associated with // that failure. This supports resumption of sends of forms with many // attachments. if (lastOutcome != null && lastOutcome.equals(InstanceColumns.STATUS_SUBMISSION_FAILED)) { String lastId = CursorUtils.getIndexAsString(c, c.getColumnIndex(InstanceColumns.SUBMISSION_INSTANCE_ID)); if (lastId != null) { submissionInstanceId = lastId; } } c.close(); FileSet instanceFiles; try { instanceFiles = constructSubmissionFiles(dataTableInstanceId, submissionInstanceId); // NOTE: /submission must not be translated! It is // the well-known path on the server. if (!uploadOneSubmission(urlString, toUpdate, id, submissionInstanceId, instanceFiles, httpclient, localContext, uriRemap)) { return mOutcome; // get credentials... } } catch (JsonParseException e) { WebLogger.getLogger(appName).printStackTrace(e); mOutcome.mResults.put(id, fail + "unable to obtain manifest: " + dataTableInstanceId + " :: details: " + e.toString()); } catch (JsonMappingException e) { WebLogger.getLogger(appName).printStackTrace(e); mOutcome.mResults.put(id, fail + "unable to obtain manifest: " + dataTableInstanceId + " :: details: " + e.toString()); } catch (IOException e) { WebLogger.getLogger(appName).printStackTrace(e); mOutcome.mResults.put(id, fail + "unable to obtain manifest: " + dataTableInstanceId + " :: details: " + e.toString()); } } else { mOutcome.mResults.put("unknown", fail + "unable to retrieve instance information via: " + toUpdate.toString()); } } finally { if (c != null && !c.isClosed()) { c.close(); } } } return mOutcome; }
From source file:org.opendatakit.services.forms.provider.FormsProvider.java
/** * This method removes the entry from the content provider, and also removes * any associated files. files: form.xml, [formmd5].formdef, formname * {directory}//from ww w .j a v a 2 s. c om */ @Override public synchronized int delete(@NonNull Uri uri, String where, String[] whereArgs) { possiblyWaitForContentProviderDebugger(); List<String> segments = uri.getPathSegments(); PatchedFilter pf = extractUriFeatures(uri, segments, where, whereArgs); WebLoggerIf logger = WebLogger.getLogger(pf.appName); String[] projection = { FormsColumns._ID, FormsColumns.TABLE_ID, FormsColumns.FORM_ID }; HashMap<String, FormSpec> directories = new HashMap<String, FormSpec>(); DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .generateInternalUseDbHandle(); OdkConnectionInterface db = null; Cursor c = null; Integer idValue = null; String tableIdValue = null; String formIdValue = null; try { // Get the database and run the query // +1 referenceCount if db is returned (non-null) db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(pf.appName, dbHandleName); db.beginTransactionNonExclusive(); c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, pf.whereId, pf.whereIdArgs, null, null, null, null); if (c == null) { throw new SQLException("FAILED Delete into " + uri + " -- unable to query for existing records"); } int idxId = c.getColumnIndex(FormsColumns._ID); int idxTableId = c.getColumnIndex(FormsColumns.TABLE_ID); int idxFormId = c.getColumnIndex(FormsColumns.FORM_ID); if (c.moveToFirst()) { do { idValue = CursorUtils.getIndexAsType(c, Integer.class, idxId); tableIdValue = CursorUtils.getIndexAsString(c, idxTableId); formIdValue = CursorUtils.getIndexAsString(c, idxFormId); FormSpec formSpec = new FormSpec(); formSpec.tableId = tableIdValue; formSpec.formId = formIdValue; formSpec.success = false; directories.put(idValue.toString(), formSpec); } while (c.moveToNext()); } c.close(); c = null; // and now go through this list moving the directories // into the pending-deletion location and deleting them. for (Entry<String, FormSpec> de : directories.entrySet()) { String id = de.getKey(); FormSpec fs = de.getValue(); File srcDir = new File(ODKFileUtils.getFormFolder(pf.appName, fs.tableId, fs.formId)); File destDir = new File(ODKFileUtils.getPendingDeletionTablesFolder(pf.appName), fs.tableId + "." + fs.formId + "." + System.currentTimeMillis()); try { FileUtils.moveDirectory(srcDir, destDir); if (db.delete(DatabaseConstants.FORMS_TABLE_NAME, FormsColumns._ID + "=?", new String[] { id }) > 0) { fs.success = true; } } catch (IOException e) { logger.e(t, "Unable to move directory prior to deleting it: " + e.toString()); logger.printStackTrace(e); } } // commit the transaction... db.setTransactionSuccessful(); } catch (Exception e) { logger.w(t, "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString()); if (e instanceof SQLException) { throw (SQLException) e; } else { throw new SQLException( "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString()); } } finally { if (db != null) { try { try { if (c != null && !c.isClosed()) { c.close(); } } finally { if (db.inTransaction()) { db.endTransaction(); } } } finally { try { db.releaseReference(); } finally { // this closes the connection OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .removeConnection(pf.appName, dbHandleName); } } } } // and now, go through all the files in the pending-deletion // directory and try to release them. File destFolder = new File(ODKFileUtils.getPendingDeletionTablesFolder(pf.appName)); File[] delDirs = destFolder.listFiles(); for (File formIdDir : delDirs) { try { FileUtils.deleteDirectory(formIdDir); } catch (IOException e) { logger.e(t, "Unable to remove directory " + e.toString()); logger.printStackTrace(e); } } int failureCount = 0; for (Entry<String, FormSpec> e : directories.entrySet()) { String id = e.getKey(); FormSpec fs = e.getValue(); if (fs.success) { Uri formUri = Uri .withAppendedPath( Uri.withAppendedPath(Uri.withAppendedPath( Uri.parse("content://" + getFormsAuthority()), pf.appName), fs.tableId), fs.formId); getContext().getContentResolver().notifyChange(formUri, null); Uri idUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), pf.appName), id); getContext().getContentResolver().notifyChange(idUri, null); } else { ++failureCount; } } getContext().getContentResolver().notifyChange(uri, null); int count = directories.size(); if (failureCount != 0) { throw new SQLiteException( "Unable to delete all forms (" + (count - failureCount) + " of " + count + " deleted)"); } return count; }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Filters results by all non-null field values. * /*from w w w .j a v a 2 s . c om*/ * @param db * @param tableId * @param partition * @param aspect * @param key * @return */ public ArrayList<KeyValueStoreEntry> getDBTableMetadata(SQLiteDatabase db, String tableId, String partition, String aspect, String key) { ArrayList<KeyValueStoreEntry> entries = new ArrayList<KeyValueStoreEntry>(); Cursor c = null; try { StringBuilder b = new StringBuilder(); ArrayList<String> selArgs = new ArrayList<String>(); if (tableId != null) { b.append(KeyValueStoreColumns.TABLE_ID).append("=?"); selArgs.add(tableId); } if (partition != null) { if (b.length() != 0) { b.append(" AND "); } b.append(KeyValueStoreColumns.PARTITION).append("=?"); selArgs.add(partition); } if (aspect != null) { if (b.length() != 0) { b.append(" AND "); } b.append(KeyValueStoreColumns.ASPECT).append("=?"); selArgs.add(aspect); } if (key != null) { if (b.length() != 0) { b.append(" AND "); } b.append(KeyValueStoreColumns.KEY).append("=?"); selArgs.add(key); } c = db.query(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, null, b.toString(), selArgs.toArray(new String[selArgs.size()]), null, null, null); if (c.moveToFirst()) { int idxPartition = c.getColumnIndex(KeyValueStoreColumns.PARTITION); int idxAspect = c.getColumnIndex(KeyValueStoreColumns.ASPECT); int idxKey = c.getColumnIndex(KeyValueStoreColumns.KEY); int idxType = c.getColumnIndex(KeyValueStoreColumns.VALUE_TYPE); int idxValue = c.getColumnIndex(KeyValueStoreColumns.VALUE); do { KeyValueStoreEntry e = new KeyValueStoreEntry(); e.partition = c.getString(idxPartition); e.aspect = c.getString(idxAspect); e.key = c.getString(idxKey); e.type = c.getString(idxType); e.value = c.getString(idxValue); entries.add(e); } while (c.moveToNext()); } } finally { if (c != null && !c.isClosed()) { c.close(); } } return entries; }
From source file:org.opendatakit.services.forms.provider.FormsProvider.java
@Override public synchronized int update(@NonNull Uri uri, ContentValues values, String where, String[] whereArgs) { possiblyWaitForContentProviderDebugger(); List<String> segments = uri.getPathSegments(); PatchedFilter pf = extractUriFeatures(uri, segments, where, whereArgs); WebLoggerIf logger = WebLogger.getLogger(pf.appName); /*/*from w w w .j av a2s . c om*/ * First, find out what records match this query. Replicate the * ContentValues if there are multiple tableIds/formIds involved * and the contentValues do not have formId and tableId specified. * * Otherwise, it is an error to specify the tableId or formId in * the ContentValues and have those not match the where results. * */ String contentTableId = (values != null && values.containsKey(FormsColumns.TABLE_ID)) ? values.getAsString(FormsColumns.TABLE_ID) : null; String contentFormId = (values != null && values.containsKey(FormsColumns.FORM_ID)) ? values.getAsString(FormsColumns.FORM_ID) : null; HashMap<FormSpec, HashMap<String, Object>> matchedValues = new HashMap<FormSpec, HashMap<String, Object>>(); DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .generateInternalUseDbHandle(); OdkConnectionInterface db = null; try { // +1 referenceCount if db is returned (non-null) db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(pf.appName, dbHandleName); db.beginTransactionNonExclusive(); Cursor c = null; try { c = db.query(DatabaseConstants.FORMS_TABLE_NAME, null, pf.whereId, pf.whereIdArgs, null, null, null, null); if (c == null) { throw new SQLException( "FAILED Update of " + uri + " -- query for existing row did not return a cursor"); } if (c.moveToFirst()) { int idxId = c.getColumnIndex(FormsColumns._ID); int idxTableId = c.getColumnIndex(FormsColumns.TABLE_ID); int idxFormId = c.getColumnIndex(FormsColumns.FORM_ID); Integer idValue = null; String tableIdValue = null; String formIdValue = null; do { idValue = CursorUtils.getIndexAsType(c, Integer.class, idxId); tableIdValue = CursorUtils.getIndexAsString(c, idxTableId); formIdValue = CursorUtils.getIndexAsString(c, idxFormId); if (contentTableId != null && !contentTableId.equals(tableIdValue)) { throw new SQLException("Modification of tableId for an existing form is prohibited"); } if (contentFormId != null && !contentFormId.equals(formIdValue)) { throw new SQLException("Modification of formId for an existing form is prohibited"); } HashMap<String, Object> cv = new HashMap<String, Object>(); if (values != null) { for (String key : values.keySet()) { cv.put(key, values.get(key)); } } cv.put(FormsColumns.TABLE_ID, tableIdValue); cv.put(FormsColumns.FORM_ID, formIdValue); for (int idx = 0; idx < c.getColumnCount(); ++idx) { String colName = c.getColumnName(idx); if (colName.equals(FormsColumns._ID)) { // don't insert the PK continue; } if (c.isNull(idx)) { cv.put(colName, null); } else { // everything else, we control... Class<?> dataType = CursorUtils.getIndexDataType(c, idx); if (dataType == String.class) { cv.put(colName, CursorUtils.getIndexAsString(c, idx)); } else if (dataType == Long.class) { cv.put(colName, CursorUtils.getIndexAsType(c, Long.class, idx)); } else if (dataType == Double.class) { cv.put(colName, CursorUtils.getIndexAsType(c, Double.class, idx)); } } } FormSpec formSpec = patchUpValues(pf.appName, cv); formSpec._id = idValue.toString(); formSpec.success = false; matchedValues.put(formSpec, cv); } while (c.moveToNext()); } else { // no match on where clause... return 0; } } finally { if (c != null && !c.isClosed()) { c.close(); } } // go through the entries and update the database with these patched-up values... for (Entry<FormSpec, HashMap<String, Object>> e : matchedValues.entrySet()) { FormSpec fs = e.getKey(); HashMap<String, Object> cv = e.getValue(); if (db.update(DatabaseConstants.FORMS_TABLE_NAME, cv, FormsColumns._ID + "=?", new String[] { fs._id }) > 0) { fs.success = true; } } db.setTransactionSuccessful(); } catch (Exception e) { logger.w(t, "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString()); if (e instanceof SQLException) { throw (SQLException) e; } else { throw new SQLException( "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString()); } } finally { if (db != null) { try { if (db.inTransaction()) { db.endTransaction(); } } finally { try { db.releaseReference(); } finally { // this closes the connection OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface() .removeConnection(pf.appName, dbHandleName); } } } } int failureCount = 0; for (FormSpec fs : matchedValues.keySet()) { if (fs.success) { Uri formUri = Uri .withAppendedPath( Uri.withAppendedPath(Uri.withAppendedPath( Uri.parse("content://" + getFormsAuthority()), pf.appName), fs.tableId), fs.formId); getContext().getContentResolver().notifyChange(formUri, null); Uri idUri = Uri.withAppendedPath( Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), pf.appName), fs._id); getContext().getContentResolver().notifyChange(idUri, null); } else { ++failureCount; } } getContext().getContentResolver().notifyChange(uri, null); int count = matchedValues.size(); if (failureCount != 0) { throw new SQLiteException( "Unable to update all forms (" + (count - failureCount) + " of " + count + " updated)"); } return count; }
From source file:com.android.mms.ui.ComposeMessageActivity.java
private boolean isCursorValid() { // Check whether the cursor is valid or not. Cursor cursor = mMsgListAdapter.getCursor(); if (cursor.isClosed() || cursor.isBeforeFirst() || cursor.isAfterLast()) { Log.e(TAG, "Bad cursor.", new RuntimeException()); return false; }/*from w ww. j av a2 s .c o m*/ return true; }
From source file:com.ezac.gliderlogs.FlightOverviewActivity.java
@SuppressLint("SimpleDateFormat") public void GliderLogToCSV(String DB, String device_id) { // format date's SimpleDateFormat CSV = new SimpleDateFormat("yyyyMMdd_kkss"); SimpleDateFormat DIR = new SimpleDateFormat("yyyy/MM_dd"); Date myDate = new Date(); String TS_DB = CSV.format(myDate); String TS_DIR = DIR.format(myDate); // to internal sdcard File dir = new File(Environment.getExternalStorageDirectory() + "/Download/" + TS_DIR); if (!dir.exists() || !dir.isDirectory()) { dir.mkdir();//from w w w . j a v a 2 s .c om } File myFile = new File(Environment.getExternalStorageDirectory() + "/Download/" + TS_DIR + "/" + device_id.toUpperCase(Locale.US) + "_" + TS_DB + ".csv"); try { myFile.createNewFile(); FileOutputStream fOut = new FileOutputStream(myFile); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); myOutWriter.append( "datum;start;landing;duur;soort;registratie;piloot;piloot_id;tweede;tweede_id;instructie;opmerking;methode"); myOutWriter.append("\n"); Uri uri = FlightsContentProvider.CONTENT_URI_FLIGHT; String[] projection = { GliderLogTables.F_DATE, GliderLogTables.F_STARTED, GliderLogTables.F_LANDED, GliderLogTables.F_DURATION, GliderLogTables.F_TYPE, GliderLogTables.F_REGISTRATION, GliderLogTables.F_PILOT, GliderLogTables.F_PILOT_ID, GliderLogTables.F_COPILOT, GliderLogTables.F_COPILOT_ID, GliderLogTables.F_INSTRUCTION, GliderLogTables.F_NOTES, GliderLogTables.F_LAUNCH }; Cursor cur_go = getContentResolver().query(uri, projection, null, null, null); if (cur_go != null) { //Log.d(TAG,"cnt " + cursor.getCount()); try { if ((cur_go.getCount()) > 0) { cur_go.moveToFirst(); do { myOutWriter.append(cur_go .getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_DATE)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_STARTED)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_LANDED)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_DURATION)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_TYPE)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_REGISTRATION)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_PILOT)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_PILOT_ID)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_COPILOT)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_COPILOT_ID)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_INSTRUCTION)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_NOTES)) + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_LAUNCH))); myOutWriter.append("\n"); // Log.d(TAG,"gld " + cursor // .getColumnIndexOrThrow(GliderLogTables.F_REGISTRATION)); } while (cur_go.moveToNext()); } } finally { if (!cur_go.isClosed()) { cur_go.close(); } } } myOutWriter.close(); fOut.close(); } catch (IOException ioe) { Log.e(TAG, "Could not open/write the csv file, error: " + ioe.getMessage()); } catch (SQLiteException e) { Log.e(TAG, "SQLiteException:" + e.getMessage()); } catch (Exception e) { Log.e(TAG, "Could not open/read the DB, error: " + e.getMessage()); } }
From source file:com.android.mms.ui.ComposeMessageActivity.java
@Override protected void onStop() { super.onStop(); // No need to do the querying when finished this activity mBackgroundQueryHandler.cancelOperation(MESSAGE_LIST_QUERY_TOKEN); // Allow any blocked calls to update the thread's read status. mConversation.blockMarkAsRead(false); if (mMsgListAdapter != null) { // Close the cursor in the ListAdapter if the activity stopped. Cursor cursor = mMsgListAdapter.getCursor(); if (cursor != null && !cursor.isClosed()) { cursor.close();/*from w w w. ja v a 2 s. c o m*/ } mMsgListAdapter.changeCursor(null); mMsgListAdapter.cancelBackgroundLoading(); } if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("save draft"); } saveDraft(true); // set 'mShouldLoadDraft' to true, so when coming back to ComposeMessageActivity, we would // load the draft, unless we are coming back to the activity after attaching a photo, etc, // in which case we should set 'mShouldLoadDraft' to false. mShouldLoadDraft = true; // Cleanup the BroadcastReceiver. unregisterReceiver(mHttpProgressReceiver); unregisterReceiver(mDelayedSendProgressReceiver); }
From source file:org.opendatakit.common.android.task.InitializationTask.java
/** * Scan the given formDir and update the Forms database. If it is the * formsFolder, then any 'framework' forms should be forbidden. If it is not * the formsFolder, only 'framework' forms should be allowed * * @param tableId/* w w w. j a v a2 s . com*/ * @param formId * @param formDir * @param isFormsFolder * @param baseStaleMediaPath -- path prefix to the stale forms/framework directory. */ private final void updateFormDir(String tableId, String formId, File formDir, boolean isFormsFolder, String baseStaleMediaPath) { Uri formsProviderContentUri = Uri.parse("content://" + FormsProviderAPI.AUTHORITY); String formDirectoryPath = formDir.getAbsolutePath(); WebLogger.getLogger(appName).i(t, "updateFormDir: " + formDirectoryPath); String successMessage = appContext.getString(R.string.form_register_success, tableId, formId); String failureMessage = appContext.getString(R.string.form_register_failure, tableId, formId); Cursor c = null; try { String selection = FormsColumns.TABLE_ID + "=? AND " + FormsColumns.FORM_ID + "=?"; String[] selectionArgs = { tableId, formId }; c = appContext.getContentResolver().query(Uri.withAppendedPath(formsProviderContentUri, appName), null, selection, selectionArgs, null); if (c == null) { WebLogger.getLogger(appName).w(t, "updateFormDir: " + formDirectoryPath + " null cursor -- cannot update!"); mPendingResult.add(failureMessage); return; } if (c.getCount() > 1) { c.close(); WebLogger.getLogger(appName).w(t, "updateFormDir: " + formDirectoryPath + " multiple records from cursor -- delete all and restore!"); // we have multiple records for this one directory. // Rename the directory. Delete the records, and move the // directory back. File tempMediaPath = moveToStaleDirectory(formDir, baseStaleMediaPath); appContext.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName), selection, selectionArgs); FileUtils.moveDirectory(tempMediaPath, formDir); ContentValues cv = new ContentValues(); cv.put(FormsColumns.TABLE_ID, tableId); cv.put(FormsColumns.FORM_ID, formId); appContext.getContentResolver().insert(Uri.withAppendedPath(formsProviderContentUri, appName), cv); } else if (c.getCount() == 1) { c.close(); ContentValues cv = new ContentValues(); cv.put(FormsColumns.TABLE_ID, tableId); cv.put(FormsColumns.FORM_ID, formId); appContext.getContentResolver().update(Uri.withAppendedPath(formsProviderContentUri, appName), cv, null, null); } else if (c.getCount() == 0) { c.close(); ContentValues cv = new ContentValues(); cv.put(FormsColumns.TABLE_ID, tableId); cv.put(FormsColumns.FORM_ID, formId); appContext.getContentResolver().insert(Uri.withAppendedPath(formsProviderContentUri, appName), cv); } } catch (IOException e) { WebLogger.getLogger(appName).printStackTrace(e); WebLogger.getLogger(appName).e(t, "updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); mPendingResult.add(failureMessage); return; } catch (IllegalArgumentException e) { WebLogger.getLogger(appName).printStackTrace(e); WebLogger.getLogger(appName).e(t, "updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); try { FileUtils.deleteDirectory(formDir); WebLogger.getLogger(appName).i(t, "updateFormDir: " + formDirectoryPath + " Removing -- unable to parse formDef file: " + e.toString()); } catch (IOException e1) { WebLogger.getLogger(appName).printStackTrace(e1); WebLogger.getLogger(appName) .i(t, "updateFormDir: " + formDirectoryPath + " Removing -- unable to delete form directory: " + formDir.getName() + " error: " + e.toString()); } mPendingResult.add(failureMessage); return; } catch (Exception e) { WebLogger.getLogger(appName).printStackTrace(e); WebLogger.getLogger(appName).e(t, "updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); mPendingResult.add(failureMessage); return; } finally { if (c != null && !c.isClosed()) { c.close(); } } mPendingResult.add(successMessage); }
From source file:com.ezac.gliderlogs.FlightOverviewActivity.java
public String getDetailInfo(Uri uri, String param, int mde) { Cursor cur_di = null; String tmp = ""; switch (mde) { case 0:/*from w w w .jav a 2 s . com*/ String[] projection_1 = { GliderLogTables.G_REGISTRATION, GliderLogTables.G_CALLSIGN, GliderLogTables.G_TYPE, GliderLogTables.G_BUILD, GliderLogTables.G_SEATS, GliderLogTables.G_OWNER, GliderLogTables.G_PRIVATE }; selection = GliderLogTables.G_REGISTRATION + " like '" + param + "'"; cur_di = getContentResolver().query(uri, projection_1, selection, null, null); if (cur_di != null) { try { cur_di.moveToFirst(); tmp = cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.G_REGISTRATION)); tmp = tmp + ";" + (cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.G_CALLSIGN)) .equals("null") ? "-" : cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.G_CALLSIGN))); tmp = tmp + ";" + (cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.G_TYPE)).equals("null") ? "-" : cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.G_TYPE))); tmp = tmp + ";" + (cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.G_BUILD)) .equals("null") ? "-" : cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.G_BUILD))); tmp = tmp + ";\nTweezitter: " + (cur_di .getString(cur_di.getColumnIndexOrThrow(GliderLogTables.G_SEATS)).equals("null") ? "?" : (cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.G_SEATS))) .equals("1") ? "Nee" : "Ja"); tmp = tmp + ";\nEigenaar: " + (cur_di .getString(cur_di.getColumnIndexOrThrow(GliderLogTables.G_OWNER)).equals("null") ? "" : cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.G_OWNER))); tmp = tmp + ";Prive: " + (cur_di .getString(cur_di.getColumnIndexOrThrow(GliderLogTables.G_PRIVATE)).equals("null") ? "?" : (cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.G_PRIVATE))) .equals("0") ? "Nee" : "Ja"); } finally { if (!cur_di.isClosed()) { cur_di.close(); } } } break; case 1: String[] projection_2 = { GliderLogTables.M_1_NAME, GliderLogTables.M_2_NAME, GliderLogTables.M_3_NAME, GliderLogTables.M_PHONE, GliderLogTables.M_MOBILE, GliderLogTables.M_INSTRUCTION, GliderLogTables.M_ID }; selection = GliderLogTables.M_ID + " like '" + param + "'"; cur_di = getContentResolver().query(uri, projection_2, selection, null, null); if (cur_di != null) { try { cur_di.moveToFirst(); tmp = cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.M_1_NAME)) + " " + cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.M_2_NAME)) + " " + cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.M_3_NAME)); tmp = tmp.replaceAll("\\s+", " "); tmp = tmp + ";\n" + (cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.M_PHONE)) .equals("null") ? "-" : cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.M_PHONE))); tmp = tmp + ";" + (cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.M_MOBILE)) .equals("null") ? "-" : cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.M_MOBILE))); tmp = tmp + ";\nInstructeur: " + (cur_di.getString(cur_di.getColumnIndexOrThrow(GliderLogTables.M_INSTRUCTION)) .equals("0") ? "Nee" : "Ja"); } finally { if (!cur_di.isClosed()) { cur_di.close(); } } } break; } return tmp; }