Java Code Examples for android.database.Cursor#close()

The following examples show how to use android.database.Cursor#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TableMetadataDataSource.java    From geopackage-android with MIT License 6 votes vote down vote up
/**
 * Get a table metadata
 *
 * @param geoPackageId GeoPackage id
 * @param tableName    table name
 * @return table metadata
 */
public TableMetadata get(long geoPackageId, String tableName) {

    String selection = TableMetadata.COLUMN_GEOPACKAGE_ID
            + " = ? AND " + TableMetadata.COLUMN_TABLE_NAME + " = ?";
    String[] selectionArgs = new String[]{String.valueOf(geoPackageId), tableName};
    Cursor cursor = db.query(
            TableMetadata.TABLE_NAME,
            TableMetadata.COLUMNS, selection, selectionArgs, null, null, null);
    TableMetadata metadata = null;
    try {
        if (cursor.moveToNext()) {
            metadata = createTableMetadata(cursor);
        }
    } finally {
        cursor.close();
    }
    return metadata;
}
 
Example 2
Source File: QuestionsDatabase.java    From iZhihu with GNU General Public License v2.0 6 votes vote down vote up
private ArrayList<Question> getAllQuestionsByCursor(Cursor cursor) {
    ArrayList<Question> questionArrayList = new ArrayList<Question>();

    try {
        getIndexFromCursor(cursor);
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToPosition(i);
            Question question = convertCursorIntoQuestion(cursor);
            questionArrayList.add(question);
        }

        return questionArrayList;
    } finally {
        cursor.close();
    }
}
 
Example 3
Source File: MetadataDbHelper.java    From AOSP-Kayboard-7.1.2 with Apache License 2.0 6 votes vote down vote up
/**
 * Update the last metadata update time for all clients using a particular URI.
 *
 * This method searches for all clients using a particular URI and updates the last
 * update time for this client.
 * The current time is used as the latest update time. This saved date will be what
 * is returned henceforth by {@link #getLastUpdateDateForClient(Context, String)},
 * until this method is called again.
 *
 * @param context a context instance to open the database on
 * @param uri the metadata URI we just downloaded
 */
public static void saveLastUpdateTimeOfUri(final Context context, final String uri) {
    PrivateLog.log("Save last update time of URI : " + uri + " " + System.currentTimeMillis());
    final ContentValues values = new ContentValues();
    values.put(CLIENT_LAST_UPDATE_DATE_COLUMN, System.currentTimeMillis());
    final SQLiteDatabase defaultDb = getDb(context, null);
    final Cursor cursor = MetadataDbHelper.queryClientIds(context);
    if (null == cursor) return;
    try {
        if (!cursor.moveToFirst()) return;
        do {
            final String clientId = cursor.getString(0);
            final String metadataUri =
                    MetadataDbHelper.getMetadataUriAsString(context, clientId);
            if (metadataUri.equals(uri)) {
                defaultDb.update(CLIENT_TABLE_NAME, values,
                        CLIENT_CLIENT_ID_COLUMN + " = ?", new String[] { clientId });
            }
        } while (cursor.moveToNext());
    } finally {
        cursor.close();
    }
}
 
Example 4
Source File: SellsInfo.java    From Android-POS with MIT License 6 votes vote down vote up
public boolean haveAnyData(){

        this.Open();
        try {
            Cursor cursor = database.query(dbHelper.TABLE_SELL_NAME, null, null, null, null, null, null);
            cursor.moveToFirst();

            int temp = cursor.getCount();

            cursor.close();
            this.Close();

            if (temp>0){
                return true;
            }else return false;
        }catch (Exception e){

            Log.d(TAG, "haveAnyData: "+e);
            return false;
        }
    }
 
Example 5
Source File: DatabaseManager.java    From homeassist with Apache License 2.0 6 votes vote down vote up
public ArrayList<Entity> getEntities() {
    ArrayList<Entity> results = new ArrayList<>();
    // Select All Query
    String selectQuery = "SELECT * from " + TABLE_ENTITY + " ORDER BY FRIENDLY_NAME ASC, DOMAIN ASC";

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            results.add(Entity.getInstance(cursor));
        } while (cursor.moveToNext());
    }

    cursor.close();
    return results;
}
 
Example 6
Source File: Registro.java    From android with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode,
                                Intent data) {
    if ((requestCode == RESULTADO_CARGA_IMAGEN) &&
            (resultCode == RESULT_OK) && (data != null)) {
        // Obtiene el Uri de la imagen seleccionada por el usuario
        Uri imagenSeleccionada = data.getData();
        String[] ruta = {MediaStore.Images.Media.DATA};

        // Realiza una consulta a la galería de imágenes solicitando la imagen seleccionada
        Cursor cursor = getContentResolver().query(imagenSeleccionada,
                ruta, null, null, null);
        cursor.moveToFirst();

        // Obtiene la ruta a la imagen
        int indice = cursor.getColumnIndex(ruta[0]);
        String picturePath = cursor.getString(indice);
        cursor.close();

        // Carga la imagen en el botón ImageButton
        ImageButton ibFoto = (ImageButton)
                findViewById(R.id.ibFoto);
        ibFoto.setImageBitmap(BitmapFactory.decodeFile(picturePath));
    }
}
 
Example 7
Source File: SqlPersistenceStorageEngine.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public long serverCacheEstimatedSizeInBytes() {
  String query =
      String.format(
          "SELECT sum(length(%s) + length(%s)) FROM %s",
          VALUE_COLUMN_NAME, PATH_COLUMN_NAME, SERVER_CACHE_TABLE);
  Cursor cursor = database.rawQuery(query, null);
  try {
    if (cursor.moveToFirst()) {
      return cursor.getLong(0); // corresponds to the sum in the query
    } else {
      throw new IllegalStateException("Couldn't read database result!");
    }
  } finally {
    cursor.close();
  }
}
 
Example 8
Source File: CommonUtils.java    From Android_framework with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}
 
Example 9
Source File: OCM_FatController.java    From GLEXP-Team-onebillion with Apache License 2.0 6 votes vote down vote up
/**
 * List of stars to display on the top of child menu screen in study mode
 * @param db
 * @param sessionid
 * @return list of stars colours(as integers)
 */
public List<Integer> getStudyStarsForSessionFromDB(DBSQL db,int sessionid)
{
    List<Integer> coloursList = new ArrayList<>();
    Cursor cursor = db.prepareRawQuery(String.format("SELECT UI.starColour as starColour FROM %s AS UI " +
                    "JOIN %s AS U ON U.unitid = UI.unitid " +
                    "WHERE UI.userid = ? AND UI.sessionid = ? AND U.masterlistid = ? " +
                    "AND UI.starColour > 0 AND UI.typeid IN (?,?) " +
                    "GROUP BY UI.unitid,UI.extraunitid ORDER BY UI.rowid ASC", DBSQL.TABLE_UNIT_INSTANCES, DBSQL.TABLE_UNITS),
            Arrays.asList(String.valueOf(currentUser.userid),String.valueOf(sessionid),
                    String.valueOf(currentUser.studylistid),String.valueOf(OCM_MlUnitInstance.INSTANCE_TYPE_STUDY),
                    String.valueOf(OCM_MlUnitInstance.INSTANCE_TYPE_EXTRA)));

    if(cursor.moveToFirst())
    {
        while (cursor.isAfterLast() == false)
        {
            int columnIndex = cursor.getColumnIndex("starColour");
            if(!cursor.isNull(columnIndex))
                coloursList.add(cursor.getInt(columnIndex));
            cursor.moveToNext();
        }
    }
    cursor.close();
    return coloursList;
}
 
Example 10
Source File: ContactAccessor.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
public List<String> getNumbersForThreadSearchFilter(Context context, String constraint) {
  LinkedList<String> numberList = new LinkedList<>();
  Cursor cursor                 = null;

  try {
    cursor = context.getContentResolver().query(Uri.withAppendedPath(Phone.CONTENT_FILTER_URI,
                                                                     Uri.encode(constraint)),
                                                null, null, null, null);

    while (cursor != null && cursor.moveToNext()) {
      numberList.add(cursor.getString(cursor.getColumnIndexOrThrow(Phone.NUMBER)));
    }

  } finally {
    if (cursor != null)
      cursor.close();
  }

  return numberList;
}
 
Example 11
Source File: FailedActionsDbHelper.java    From LibreTasks with Apache License 2.0 5 votes vote down vote up
/**
 * 
 */
public void deleteOldActions() {
  if (!database.isOpen()) {
    throw new IllegalStateException(TAG + " is already closed.");
  }

  Cursor cursor = failedActionsDbAdapter.fetchOldActions();
  while (cursor.moveToNext()) {
    UtilUI.showNotification(context, UtilUI.NOTIFICATION_RULE, context.getString(R.string.libretasks), getStringFromCursor(cursor, FailedActionsDbAdapter.KEY_MESSAGE));
    failedActionsDbAdapter.delete(getLongFromCursor(cursor, 
        FailedActionsDbAdapter.KEY_FAILEDACTIONID));
  }
  cursor.close();
}
 
Example 12
Source File: LocationService.java    From Androzic with GNU General Public License v3.0 5 votes vote down vote up
public long getTrackStartTime()
{
	long res = Long.MIN_VALUE;
	if (trackDB == null)
		openDatabase();
	if (trackDB == null)
		return res;
	Cursor cursor = trackDB.rawQuery("SELECT MIN(datetime) FROM track WHERE datetime > 0", null);
	if (cursor.moveToFirst())
		res = cursor.getLong(0);
	cursor.close();
	return res;
}
 
Example 13
Source File: TestUtilities.java    From android-dev-challenge with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures there is a non empty cursor and validates the cursor's data by checking it against
 * a set of expected values. This method will then close the cursor.
 *
 * @param error          Message when an error occurs
 * @param valueCursor    The Cursor containing the actual values received from an arbitrary query
 * @param expectedValues The values we expect to receive in valueCursor
 */
static void validateThenCloseCursor(String error, Cursor valueCursor, ContentValues expectedValues) {
    assertNotNull(
            "This cursor is null. Did you make sure to register your ContentProvider in the manifest?",
            valueCursor);

    assertTrue("Empty cursor returned. " + error, valueCursor.moveToFirst());
    validateCurrentRecord(error, valueCursor, expectedValues);
    valueCursor.close();
}
 
Example 14
Source File: Customer.java    From Android-POS with MIT License 5 votes vote down vote up
public ArrayList<CustomerModel> getAllCustomer() {
    this.Open();
    ArrayList<CustomerModel> customers= new ArrayList<>();
    try {
        Cursor cursor = database.query(dbHelper.TABLE_CT_NAME, null, null, null, null, null, null);

        cursor.moveToFirst();
        int totalCustomer = cursor.getCount();
        for (int i = 0; i < totalCustomer; i++){
            customers.add(new CustomerModel(
                    cursor.getString(cursor.getColumnIndex(dbHelper.COL_CT_NAME)),
                    cursor.getString(cursor.getColumnIndex(dbHelper.COL_CT_CODE)),
                    cursor.getString(cursor.getColumnIndex(dbHelper.COL_CT_TYPE_)),
                    cursor.getString(cursor.getColumnIndex(dbHelper.COL_CT_GENDER)),
                    cursor.getString(cursor.getColumnIndex(dbHelper.COL_CT_PHONE)),
                    cursor.getString(cursor.getColumnIndex(dbHelper.COL_CT_EMAIL)),
                    cursor.getString(cursor.getColumnIndex(dbHelper.COL_CT_ADDRESS)),
                    cursor.getString(cursor.getColumnIndex(dbHelper.COL_CT_DUE_AMOUNT))
            ));
            cursor.moveToNext();
        }

        cursor.close();
        this.Close();
        if (totalCustomer > 0) {
            return customers;
        } else {
            return null;
        }
    } catch (Exception e) {
        Log.d(TAG, "getProducts: "+e);
        return null;

    }
}
 
Example 15
Source File: UpnpMovie.java    From Mizuu with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> searchFolder() {
	DbAdapterMovieMappings dbHelper = MizuuApplication.getMovieMappingAdapter();
	Cursor cursor = dbHelper.getAllFilepaths(false); // Query database to return all filepaths in a cursor
	ColumnIndexCache cache = new ColumnIndexCache();
	
	try {
		while (cursor.moveToNext()) {// Add all movies in cursor to ArrayList of all existing movies
			existingMovies.put(cursor.getString(cache.getColumnIndex(cursor, DbAdapterMovieMappings.KEY_FILEPATH)), "");
		}
	} catch (Exception e) {
	} finally {
		cursor.close(); // Close cursor
		cache.clear();
	}

	// Do a recursive search in the file source folder
	recursiveSearch(getFolder(), results);

	List<String> list = new ArrayList<String>();

	Iterator<String> it = results.iterator();
	while (it.hasNext())
		list.add(it.next());

	return list;
}
 
Example 16
Source File: ContentFilesystem.java    From reader with MIT License 5 votes vote down vote up
@Override
public String filesystemPathForURL(LocalFilesystemURL url) {
    Cursor cursor = openCursorForURL(url);
    try {
    	if (cursor != null && cursor.moveToFirst()) {
    		return filesystemPathForCursor(cursor);
    	}
    } finally {
        if (cursor != null)
        	cursor.close();
    }
    return null;
}
 
Example 17
Source File: KcaDBHelper.java    From kcanotify_h5-master with GNU General Public License v3.0 5 votes vote down vote up
public String getQuestListData() {
    SQLiteDatabase db = this.getReadableDatabase();
    StringBuilder sb = new StringBuilder();
    Cursor c = db.query(questlist_table_name, null, null, null, null, null, null);
    while (c.moveToNext()) {
        String key = c.getString(c.getColumnIndex("KEY"));
        String value = c.getString(c.getColumnIndex("VALUE"));
        String time = c.getString(c.getColumnIndex("TIME"));
        sb.append(KcaUtils.format("[%s] %s %s\n", key, value, time));
    }
    c.close();
    return sb.toString().trim();
}
 
Example 18
Source File: DbUtil.java    From commcare-android with Apache License 2.0 4 votes vote down vote up
public static void explainSql(SQLiteDatabase handle, String sql, String[] args) {
    Cursor explain = handle.rawQuery("EXPLAIN QUERY PLAN " + sql, args);
    Log.d(TAG, "SQL: " + sql);
    DatabaseUtils.dumpCursor(explain);
    explain.close();
}
 
Example 19
Source File: TestSunshineDatabase.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
<<<<<<< HEAD
     * Tests to ensure that inserts into your database results in automatically incrementing row
     * IDs and that row IDs are not reused.
     * <p>
     * If the INTEGER PRIMARY KEY column is not explicitly given a value, then it will be filled
     * automatically with an unused integer, usually one more than the largest _ID currently in
     * use. This is true regardless of whether or not the AUTOINCREMENT keyword is used.
     * <p>
     * If the AUTOINCREMENT keyword appears after INTEGER PRIMARY KEY, that changes the automatic
     * _ID assignment algorithm to prevent the reuse of _IDs over the lifetime of the database.
     * In other words, the purpose of AUTOINCREMENT is to prevent the reuse of _IDs from previously
     * deleted rows.
     * <p>
     * To test this, we first insert a row into the database and get its _ID. Then, we'll delete
     * that row, change the data that we're going to insert, and insert the changed data into the
     * database again. If AUTOINCREMENT isn't set up properly in the WeatherDbHelper's table
     * create statement, then the _ID of the first insert will be reused. However, if AUTOINCREMENT
     * is setup properly, that older ID will NOT be reused, and the test will pass.
=======
     * Tests the columns with null values cannot be inserted into the database.
     */
    @Test
    public void testNullColumnConstraints() {
        /* Use a WeatherDbHelper to get access to a writable database */

        /* We need a cursor from a weather table query to access the column names */
        Cursor weatherTableCursor = database.query(
                REFLECTED_TABLE_NAME,
                /* We don't care about specifications, we just want the column names */
                null, null, null, null, null, null);

        /* Store the column names and close the cursor */
        String[] weatherTableColumnNames = weatherTableCursor.getColumnNames();
        weatherTableCursor.close();

        /* Obtain weather values from TestUtilities and make a copy to avoid altering singleton */
        ContentValues testValues = TestUtilities.createTestWeatherContentValues();
        /* Create a copy of the testValues to save as a reference point to restore values */
        ContentValues testValuesReferenceCopy = new ContentValues(testValues);

        for (String columnName : weatherTableColumnNames) {

            /* We don't need to verify the _ID column value is not null, the system does */
            if (columnName.equals(WeatherContract.WeatherEntry._ID)) continue;

            /* Set the value to null */
            testValues.putNull(columnName);

            /* Insert ContentValues into database and get a row ID back */
            long shouldFailRowId = database.insert(
                    REFLECTED_TABLE_NAME,
                    null,
                    testValues);

            String variableName = getConstantNameByStringValue(
                    WeatherContract.WeatherEntry.class,
                    columnName);

            /* If the insert fails, which it should in this case, database.insert returns -1 */
            String nullRowInsertShouldFail =
                    "Insert should have failed due to a null value for column: '" + columnName + "'"
                            + ", but didn't."
                            + "\n Check that you've added NOT NULL to " + variableName
                            + " in your create table statement in the WeatherEntry class."
                            + "\n Row ID: ";
            assertEquals(nullRowInsertShouldFail,
                    -1,
                    shouldFailRowId);

            /* "Restore" the original value in testValues */
            testValues.put(columnName, testValuesReferenceCopy.getAsDouble(columnName));
        }

        /* Close database */
        dbHelper.close();
    }
 
Example 20
Source File: DatabaseHelper.java    From IdeaTrackerPlus with MIT License 4 votes vote down vote up
/**
 * Search for ideas using a substring,
 * match can occur in the title or the note of the idea,
 * search is case insensitive
 *
 * @param sub
 * @return
 */
public ArrayList<Pair<Integer, String>> searchIdeas(String sub) {
    if (!DataEntry.TABLE_NAME.equals("[]")) {

        SQLiteDatabase db = this.getReadableDatabase();

        // Only the text and id will be read
        String[] projection = {DataEntry._ID, DataEntry.COLUMN_NAME_TEXT, DataEntry.COLUMN_NAME_NOTE};

        // How you want the results sorted in the resulting Cursor
        String sortOrder = DataEntry.COLUMN_NAME_TEXT + " ASC";

        //Define the where condition, all not temps ideas
        String where = "temp=?";
        String[] values = new String[]{"0"};

        Cursor cursor = null;
        ArrayList<Pair<Integer, String>> ideas = new ArrayList<>();
        try {
            cursor = db.query(
                    DataEntry.TABLE_NAME,  // The table to query
                    projection,                               // The columns to return
                    where,                                   // The columns for the WHERE clause
                    values,                      // The values for the WHERE clause
                    null,                                     // don't group the rows
                    null,                                     // don't filter by row groups
                    sortOrder                                 // The sort order
            );


            Pair<Integer, String> pair;

            //Scan the ideas and return everything
            if (cursor.moveToFirst()) {

                while (!cursor.isAfterLast()) {
                    String text = cursor.getString(cursor.getColumnIndex(DataEntry.COLUMN_NAME_TEXT));
                    String note = cursor.getString(cursor.getColumnIndex(DataEntry.COLUMN_NAME_NOTE));
                    int id = cursor.getInt(cursor.getColumnIndex(DataEntry._ID));

                    if (text.toLowerCase().contains(sub.toLowerCase()) || note.toLowerCase().contains(sub.toLowerCase())) {
                        pair = new Pair<>(id, text);
                        ideas.add(pair);
                    }
                    cursor.moveToNext();
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return ideas;
    }

    return new ArrayList<>();
}