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

The following examples show how to use android.database.Cursor#getColumnIndex() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: MultiView   File: IOUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Try to return the absolute file path from the given Uri
 * 
 * @param context
 * @param uri
 * @return the file path or null
 */
public static String getRealFilePath( final Context context, final Uri uri ) {

	if ( null == uri ) return null;

	final String scheme = uri.getScheme();
	String data = null;

	if ( scheme == null )
		data = uri.getPath();
	else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
		data = uri.getPath();
	} else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
		Cursor cursor = context.getContentResolver().query( uri, new String[] { ImageColumns.DATA }, null, null, null );
		if ( null != cursor ) {
			if ( cursor.moveToFirst() ) {
				int index = cursor.getColumnIndex( ImageColumns.DATA );
				if ( index > -1 ) {
					data = cursor.getString( index );
				}
			}
			cursor.close();
		}
	}
	return data;
}
 
Example 2
Source Project: dingo   File: DbHelper.java    License: GNU General Public License v3.0 6 votes vote down vote up
public JSONObject getAllSettings() {
    try {
        SQLiteDatabase database = getReadableDatabase();
        Cursor resultSet = database.rawQuery("SELECT * FROM " + SETTINGS_TABLE_NAME + ";", null);
        if (resultSet.getCount() > 0 && resultSet.moveToFirst()) {
            int columnIndex = resultSet.getColumnIndex(SETTINGS_COLUMN_SETTINGS);
            String settings = resultSet.getString(columnIndex);
            return new JSONObject(settings);
        }

        resultSet.close();
        database.close();
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 3
private void addWordsLocked(final Cursor cursor) {
    if (cursor == null) return;
    if (cursor.moveToFirst()) {
        final int indexWord = cursor.getColumnIndex(Words.WORD);
        final int indexFrequency = cursor.getColumnIndex(Words.FREQUENCY);
        while (!cursor.isAfterLast()) {
            final String word = cursor.getString(indexWord);
            final int frequency = cursor.getInt(indexFrequency);
            final int adjustedFrequency = scaleFrequencyFromDefaultToLatinIme(frequency);
            // Safeguard against adding really long words.
            if (word.length() <= MAX_WORD_LENGTH) {
                runGCIfRequiredLocked(true /* mindsBlockByGC */);
                addUnigramLocked(word, adjustedFrequency, false /* isNotAWord */,
                        false /* isPossiblyOffensive */,
                        BinaryDictionary.NOT_A_VALID_TIMESTAMP);
            }
            cursor.moveToNext();
        }
    }
}
 
Example 4
Source Project: xmall   File: CordovaResourceApi.java    License: MIT License 6 votes vote down vote up
/**
 * Returns a File that points to the resource, or null if the resource
 * is not on the local filesystem.
 */
public File mapUriToFile(Uri uri) {
    assertBackgroundThread();
    switch (getUriType(uri)) {
        case URI_TYPE_FILE:
            return new File(uri.getPath());
        case URI_TYPE_CONTENT: {
            Cursor cursor = contentResolver.query(uri, LOCAL_FILE_PROJECTION, null, null, null);
            if (cursor != null) {
                try {
                    int columnIndex = cursor.getColumnIndex(LOCAL_FILE_PROJECTION[0]);
                    if (columnIndex != -1 && cursor.getCount() > 0) {
                        cursor.moveToFirst();
                        String realPath = cursor.getString(columnIndex);
                        if (realPath != null) {
                            return new File(realPath);
                        }
                    }
                } finally {
                    cursor.close();
                }
            }
        }
    }
    return null;
}
 
Example 5
public ArrayList<String> getRecentSearches() {
    Cursor searches = queryRecentSearches(String.valueOf(MAX_ITEMS_IN_DB));

    ArrayList<String> results = new ArrayList<String>(MAX_ITEMS_IN_DB);

    try {
        if (searches != null && searches.moveToFirst()) {
            int colIdx = searches.getColumnIndex(SearchHistoryColumns.SEARCHSTRING);

            do {
                results.add(searches.getString(colIdx));
            } while (searches.moveToNext());
        }
    } finally {
        if (searches != null) {
            searches.close();
            searches = null;
        }
    }

    return results;
}
 
Example 6
/**
 * Returns a File that points to the resource, or null if the resource
 * is not on the local filesystem.
 */
public File mapUriToFile(Uri uri) {
    assertBackgroundThread();
    switch (getUriType(uri)) {
        case URI_TYPE_FILE:
            return new File(uri.getPath());
        case URI_TYPE_CONTENT: {
            Cursor cursor = contentResolver.query(uri, LOCAL_FILE_PROJECTION, null, null, null);
            if (cursor != null) {
                try {
                    int columnIndex = cursor.getColumnIndex(LOCAL_FILE_PROJECTION[0]);
                    if (columnIndex != -1 && cursor.getCount() > 0) {
                        cursor.moveToFirst();
                        String realPath = cursor.getString(columnIndex);
                        if (realPath != null) {
                            return new File(realPath);
                        }
                    }
                } finally {
                    cursor.close();
                }
            }
        }
    }
    return null;
}
 
Example 7
public AlphabetIndexerCursorAdapter(Bundle savedInstanceState, Context context, Cursor cursor) {
    super(savedInstanceState, context, R.layout.mca__simple_list_item_checkable_1, cursor, FROM, TO, 0);

    // Sets a new cursor as the data set and resets the cache of indices.
    int columnIndex = cursor.getColumnIndex(BuildingsContract.NAME);
    alphabetIndexer = new AlphabetIndexer(cursor, columnIndex, " ABCDEFGHIJKLMNOPQRTSUVWXYZ");
    alphabetIndexer.setCursor(cursor);
}
 
Example 8
public String lastStarColourForLevelFromDB(DBSQL db, int userid, int masterlistid)
{
    Cursor cursor = db.prepareRawQuery(String.format("SELECT colour FROM %s AS S JOIN %s AS U ON U.unitid = S.unitid WHERE S.userid = ? AND U.masterlistid = ? ORDER BY unitIndex DESC LIMIT 1",
            DBSQL.TABLE_STARS, DBSQL.TABLE_UNITS),
            Arrays.asList(String.valueOf(userid),String.valueOf(masterlistid)));
    String result = null;

    int columnIndex = cursor.getColumnIndex("colour");
    if(cursor.moveToFirst() && !cursor.isNull(columnIndex))
        result = cursor.getString(columnIndex);

    cursor.close();
    return result;
}
 
Example 9
/**
 * Get display name from the uri
 *
 * @param context
 * @param uri
 * @return
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
private static String getDisplayName(Context context, Uri uri) {

    String name = null;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        ContentResolver resolver = context.getContentResolver();
        Cursor nameCursor = resolver.query(uri, null, null, null, null);
        try {
            if (nameCursor.getCount() > 0) {
                int displayNameIndex = nameCursor
                        .getColumnIndex(DocumentsContract.Document.COLUMN_DISPLAY_NAME);
                if (displayNameIndex >= 0 && nameCursor.moveToFirst()) {
                    name = nameCursor.getString(displayNameIndex);
                }
            }
        } finally {
            nameCursor.close();
        }
    }

    if (name == null) {
        name = uri.getPath();
        int index = name.lastIndexOf('/');
        if (index != -1) {
            name = name.substring(index + 1);
        }
    }

    return name;
}
 
Example 10
Source Project: reader   File: ContentFilesystem.java    License: MIT License 5 votes vote down vote up
protected Integer resourceSizeForCursor(Cursor cursor) {
       int columnIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
       if (columnIndex != -1) {
           String sizeStr = cursor.getString(columnIndex);
           if (sizeStr != null) {
           	return Integer.parseInt(sizeStr,10);
           }
       }
       return null;
}
 
Example 11
Source Project: EhViewer   File: SqlUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static long getLong(Cursor cursor, String column, long defValue) {
    try {
        int index = cursor.getColumnIndex(column);
        if (index != -1) {
            return cursor.getLong(index);
        }
    } catch (Throwable e) { /* Ignore */ }
    return defValue;
}
 
Example 12
private static String getRealPathFromURI(ContentResolver contentResolver, Uri contentUri) {
    Cursor cursor = contentResolver.query(contentUri, null, null, null, null);
    if (cursor == null) {
        return contentUri.getPath();
    } else {
        cursor.moveToFirst();
        int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(index);
    }
}
 
Example 13
Source Project: Indic-Keyboard   File: MetadataDbHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Given a specific download ID, return records for all pending downloads across all clients.
 *
 * If several clients use the same metadata URL, we know to only download it once, and
 * dispatch the update process across all relevant clients when the download ends. This means
 * several clients may share a single download ID if they share a metadata URI.
 * The dispatching is done in
 * {@link UpdateHandler#downloadFinished(Context, android.content.Intent)}, which
 * finds out about the list of relevant clients by calling this method.
 *
 * @param context a context instance to open the databases
 * @param downloadId the download ID to query about
 * @return the list of records. Never null, but may be empty.
 */
public static ArrayList<DownloadRecord> getDownloadRecordsForDownloadId(final Context context,
        final long downloadId) {
    final SQLiteDatabase defaultDb = getDb(context, "");
    final ArrayList<DownloadRecord> results = new ArrayList<>();
    final Cursor cursor = defaultDb.query(CLIENT_TABLE_NAME, CLIENT_TABLE_COLUMNS,
            null, null, null, null, null);
    try {
        if (!cursor.moveToFirst()) return results;
        final int clientIdIndex = cursor.getColumnIndex(CLIENT_CLIENT_ID_COLUMN);
        final int pendingIdColumn = cursor.getColumnIndex(CLIENT_PENDINGID_COLUMN);
        do {
            final long pendingId = cursor.getInt(pendingIdColumn);
            final String clientId = cursor.getString(clientIdIndex);
            if (pendingId == downloadId) {
                results.add(new DownloadRecord(clientId, null));
            }
            final ContentValues valuesForThisClient =
                    getContentValuesByPendingId(getDb(context, clientId), downloadId);
            if (null != valuesForThisClient) {
                results.add(new DownloadRecord(clientId, valuesForThisClient));
            }
        } while (cursor.moveToNext());
    } finally {
        cursor.close();
    }
    return results;
}
 
Example 14
private String[] getContactPhone(Cursor cursor) {
    int phoneColumn = cursor
            .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
    try {
        int phoneNum = cursor.getInt(phoneColumn);

        String[] result = new String[2];
        if (phoneNum > 0) {
            // 获得联系人的ID号
            int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            String contactId = cursor.getString(idColumn);
            // 获得联系人电话的cursor
            Cursor phone = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
                            + contactId, null, null);
            if (phone == null)
                return null;
            if (phone.moveToFirst()) {
                for (; !phone.isAfterLast(); phone.moveToNext()) {
                    int index = phone
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    result[1] = phone.getString(index);
                    int name = phone
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
                    result[0] = phone.getString(name);
                }
                if (!phone.isClosed()) {
                    phone.close();
                }
            }
        }
        return result;
    } catch (Exception e) {
        return null;
    }

}
 
Example 15
public void bindColumns(Cursor cursor) {
    mColumnMap = new int[9];
    mColumnMap[ID] = cursor.getColumnIndex(PROJECTION[0]);
    mColumnMap[TITLE] = cursor.getColumnIndex(PROJECTION[1]);
    mColumnMap[CATEGORY] = cursor.getColumnIndex(PROJECTION[2]);
    mColumnMap[DESCRIPTION] = cursor.getColumnIndex(PROJECTION[3]);
    mColumnMap[RATING] = cursor.getColumnIndex(PROJECTION[4]);
    mColumnMap[YEAR] = cursor.getColumnIndex(PROJECTION[5]);
    mColumnMap[THUMB_IMG_URL] = cursor.getColumnIndex(PROJECTION[THUMB_IMG_URL]);
    mColumnMap[TAGS] = cursor.getColumnIndex(PROJECTION[7]);
    mColumnMap[CONTENT_URL] = cursor.getColumnIndex(PROJECTION[8]);

}
 
Example 16
@Override
public void loadCachedArts()
{
    if(idsorted_albums == null) return;
    LongSparseArray<v.blade.library.Album> thisArray = idsorted_albums.clone(); //avoid sync problems

    Cursor albumCursor = LibraryService.appContext.getContentResolver().
            query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, null, null, null, null, null);
    if(albumCursor!=null && albumCursor.moveToFirst())
    {
        int idCol = albumCursor.getColumnIndex(MediaStore.Audio.Albums._ID);
        int artCol = albumCursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);

        do
        {
            long thisId = albumCursor.getLong(idCol);
            String path = albumCursor.getString(artCol);

            v.blade.library.Album a = thisArray.get(thisId);
            if(a != null)
            {
                LibraryService.loadArt(a, path, true);
            }
        } while (albumCursor.moveToNext());
        albumCursor.close();
    }

    thisArray = null;

    //generate image for the playlist, after we are sure that all albumarts image are loaded
    if(local_playlists == null) return;
    for(v.blade.library.Playlist list : local_playlists)
    {
        Bitmap[] bitmaps = new Bitmap[4];
        int imagenumber = 0;
        for(Song s : list.getContent())
            if(s.getAlbum().hasArt() && s.getAlbum().getArtMiniature() != bitmaps[0] && s.getAlbum().getArtMiniature() != bitmaps[1] && s.getAlbum().getArtMiniature() != bitmaps[2])
            {
                bitmaps[imagenumber] = s.getAlbum().getArtMiniature();
                imagenumber++;
                if(imagenumber == 4) break;
            }

        if(imagenumber == 4)
        {
            //generate 1 image from the 4
            Bitmap finalBitmap = Bitmap.createBitmap(80, 80, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(finalBitmap);
            canvas.drawBitmap(bitmaps[0], new Rect(0, 0, bitmaps[0].getWidth(), bitmaps[0].getHeight()),
                    new Rect(0, 0, 40, 40), null);
            canvas.drawBitmap(bitmaps[1], new Rect(0, 0, bitmaps[1].getWidth(), bitmaps[1].getHeight()),
                    new Rect(40, 0, 80, 40), null);
            canvas.drawBitmap(bitmaps[2], new Rect(0, 0, bitmaps[2].getWidth(), bitmaps[2].getHeight()),
                    new Rect(0, 40, 40, 80), null);
            canvas.drawBitmap(bitmaps[3], new Rect(0, 0, bitmaps[3].getWidth(), bitmaps[3].getHeight()),
                    new Rect(40, 40, 80, 80), null);

            list.setArt("", finalBitmap);
        }
        else if(imagenumber == 1)
        {
            list.setArt("", bitmaps[0]);
        }
    }
}
 
Example 17
Source Project: 4pdaClient-plus   File: NotesTable.java    License: Apache License 2.0 4 votes vote down vote up
public static ArrayList<Note> getNotes(SQLiteAssetHelper helper, String topicId) throws ParseException, IOException {
    ArrayList<Note> notes = new ArrayList<Note>();

    SQLiteDatabase db = null;
    Cursor c = null;
    try {

        db = helper.getWritableDatabase();
        String selection = null;
        String[] selectionArgs = null;

        if (!TextUtils.isEmpty(topicId)) {
            selection = COLUMN_TOPIC_ID + "=?";
            selectionArgs = new String[]{topicId};
        }
        c = db.query(TABLE_NAME, null, selection, selectionArgs, null, null, COLUMN_DATE + " DESC");

        if (c.moveToFirst()) {
            int columnIdIndex = c.getColumnIndex(COLUMN_ID);
            int columnTitleIndex = c.getColumnIndex(COLUMN_TITLE);
            int columnBodyIndex = c.getColumnIndex(COLUMN_BODY);
            int columnUrlIndex = c.getColumnIndex(COLUMN_URL);
            int columnTopicIdIndex = c.getColumnIndex(COLUMN_TOPIC_ID);
            int columnPostIdIndex = c.getColumnIndex(COLUMN_POST_ID);
            int columnUserIdIndex = c.getColumnIndex(COLUMN_USER_ID);
            int columnUserIndex = c.getColumnIndex(COLUMN_USER);
            int columnTopicIndex = c.getColumnIndex(COLUMN_TOPIC);
            int columnDateIndex = c.getColumnIndex(COLUMN_DATE);
            do {
                Note note = new Note();
                note.Id = c.getString(columnIdIndex);
                note.Title = c.getString(columnTitleIndex);
                note.Body = c.getString(columnBodyIndex);
                note.Url = c.getString(columnUrlIndex);
                note.TopicId = c.getString(columnTopicIdIndex);
                note.PostId = c.getString(columnPostIdIndex);
                note.UserId = c.getString(columnUserIdIndex);
                note.User = c.getString(columnUserIndex);
                note.Topic = c.getString(columnTopicIndex);
                note.Date = DbHelper.parseDate(c.getString(columnDateIndex));
                notes.add(note);
            } while (c.moveToNext());
        }
    } finally {
        if (db != null) {
            if (c != null)
                c.close();
            db.close();
        }
    }

    return notes;
}
 
Example 18
public ActivityTypeAdapter(Context context, Cursor cursor) {
    super(context, cursor, 0);
    colTime = cursor.getColumnIndex("time");
    colActivity = cursor.getColumnIndex("activity");
    colCondidence = cursor.getColumnIndex("confidence");
}
 
Example 19
/**
 * Loads masterlist from xml into database
 * @param masterlistid int number the masterlist should have in db
 * @param mlname name of the masterlist(and folder in masterlist folder that contains the xml)
 */
public void loadMasterListIntoDB(int masterlistid, String mlname)
{

    DBSQL db = null;
    try
    {
        db = new DBSQL(true);
        long token = -1;
        Map<String,String> whereMap = new ArrayMap<>();
        whereMap.put("masterlistid",String.valueOf(masterlistid));
        whereMap.put("name",mlname);
        Cursor cursor = db.doSelectOnTable(DBSQL.TABLE_MASTERLISTS, Arrays.asList("token"),whereMap);
        if(cursor.moveToFirst())
        {
            int columnIndex = cursor.getColumnIndex("token");
            if(!cursor.isNull(columnIndex))
                token = cursor.getLong(columnIndex);
        }
        cursor.close();
        OBXMLManager xmlManager = new OBXMLManager();
        InputStream is = OBUtils.getInputStreamForPath(String.format("masterlists/%s/units.xml", mlname));
        List<OBXMLNode> xml = xmlManager.parseFile(is);
        OBXMLNode rootNode = xml.get(0);
        List<OBXMLNode> masterList = new ArrayList<>();
        long masterListToken = rootNode.attributeLongValue("token");
        if(token < 0 || token != masterListToken)
        {
            db.beginTransaction();
            try
            {
                ContentValues contentValues = new ContentValues();
                contentValues.put("masterlistid", masterlistid);
                contentValues.put("name", mlname);
                contentValues.put("folder", mlname);
                contentValues.put("token", masterListToken);
                db.doReplaceOnTable(DBSQL.TABLE_MASTERLISTS,contentValues);
                whereMap = new ArrayMap<>();
                whereMap.put("masterlistid",String.valueOf(masterlistid));
                db.doDeleteOnTable(DBSQL.TABLE_UNITS, whereMap);
                int unitIndex = 0;

                for (OBXMLNode levelNode : rootNode.childrenOfType("level"))
                {
                    int level = levelNode.attributeIntValue("id");

                    List<OBXMLNode> nodes = levelNode.childrenOfType("unit");
                    masterList.addAll(nodes);

                    for (int i = 0; i < nodes.size(); i++)
                    {
                        OBXMLNode node = nodes.get(i);
                        OCM_MlUnit.insertUnitFromXMLNodeintoDB(db, node, masterlistid, unitIndex, level);

                        unitIndex++;
                    }
                }

                db.setTransactionSuccessful();
            }
            finally
            {
                db.commitTransaction();
            }
        }

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        if(db != null)
            db.close();
    }
}
 
Example 20
public void testCreateDb() throws Throwable {
    // build a HashSet of all of the table names we wish to look for
    // Note that there will be another table in the DB that stores the
    // Android metadata (db version information)
    final HashSet<String> tableNameHashSet = new HashSet<String>();
    tableNameHashSet.add(WeatherContract.LocationEntry.TABLE_NAME);
    tableNameHashSet.add(WeatherContract.WeatherEntry.TABLE_NAME);

    mContext.deleteDatabase(WeatherDbHelper.DATABASE_NAME);
    SQLiteDatabase db = new WeatherDbHelper(
            this.mContext).getWritableDatabase();
    assertEquals(true, db.isOpen());

    // have we created the tables we want?
    Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);

    assertTrue("Error: This means that the database has not been created correctly",
            c.moveToFirst());

    // verify that the tables have been created
    do {
        tableNameHashSet.remove(c.getString(0));
    } while( c.moveToNext() );

    // if this fails, it means that your database doesn't contain both the location entry
    // and weather entry tables
    assertTrue("Error: Your database was created without both the location entry and weather entry tables",
            tableNameHashSet.isEmpty());

    // now, do our tables contain the correct columns?
    c = db.rawQuery("PRAGMA table_info(" + WeatherContract.LocationEntry.TABLE_NAME + ")",
            null);

    assertTrue("Error: This means that we were unable to query the database for table information.",
            c.moveToFirst());

    // Build a HashSet of all of the column names we want to look for
    final HashSet<String> locationColumnHashSet = new HashSet<String>();
    locationColumnHashSet.add(WeatherContract.LocationEntry._ID);
    locationColumnHashSet.add(WeatherContract.LocationEntry.COLUMN_CITY_NAME);
    locationColumnHashSet.add(WeatherContract.LocationEntry.COLUMN_COORD_LAT);
    locationColumnHashSet.add(WeatherContract.LocationEntry.COLUMN_COORD_LONG);
    locationColumnHashSet.add(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING);

    int columnNameIndex = c.getColumnIndex("name");
    do {
        String columnName = c.getString(columnNameIndex);
        locationColumnHashSet.remove(columnName);
    } while(c.moveToNext());

    // if this fails, it means that your database doesn't contain all of the required location
    // entry columns
    assertTrue("Error: The database doesn't contain all of the required location entry columns",
            locationColumnHashSet.isEmpty());
    db.close();
}