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

The following examples show how to use android.database.Cursor#getColumnIndexOrThrow() . 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: MusicUtils.java    From LyricHere with Apache License 2.0 6 votes vote down vote up
public static long[] getSongListForCursor(Cursor cursor) {
    if (cursor == null) {
        return sEmptyList;
    }
    int len = cursor.getCount();
    long[] list = new long[len];
    cursor.moveToFirst();
    int colidx = -1;
    try {
        colidx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.Members.AUDIO_ID);
    } catch (IllegalArgumentException ex) {
        colidx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
    }
    for (int i = 0; i < len; i++) {
        list[i] = cursor.getLong(colidx);
        cursor.moveToNext();
    }
    return list;
}
 
Example 2
Source File: Global.java    From Favorite-Android-Client with Apache License 2.0 6 votes vote down vote up
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 column_index = cursor.getColumnIndexOrThrow(column);
			return cursor.getString(column_index);
		}
	} finally {
		if (cursor != null)
			cursor.close();
	}
	return null;
}
 
Example 3
Source File: MusicPlayerRemote.java    From Phonograph with GNU General Public License v3.0 6 votes vote down vote up
@Nullable
private static String getFilePathFromUri(Context context, Uri uri)
{
    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, null, null,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}
 
Example 4
Source File: AppUtils.java    From BmapLite with Apache License 2.0 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 column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}
 
Example 5
Source File: AgentWebUtils.java    From AgentWeb with Apache License 2.0 6 votes vote down vote up
static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
	Cursor cursor = null;
	String[] projection = {MediaStore.Images.Media.DATA};
	try {
		cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
		if (cursor != null && cursor.moveToFirst()) {
			int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			return cursor.getString(index);
		}
	} finally {
		if (cursor != null) {
			cursor.close();
		}
	}
	return null;
}
 
Example 6
Source File: MusicUtils.java    From mobile-manager-tool with MIT License 6 votes vote down vote up
/**
 * @param cursor
 * @return
 */
public static long[] getSongListForCursor(Cursor cursor) {
    if (cursor == null) {
        return sEmptyList;
    }
    int len = cursor.getCount();
    long[] list = new long[len];
    cursor.moveToFirst();
    int colidx = -1;
    try {
        colidx = cursor.getColumnIndexOrThrow(Playlists.Members.AUDIO_ID);
    } catch (IllegalArgumentException ex) {
        colidx = cursor.getColumnIndexOrThrow(BaseColumns._ID);
    }
    for (int i = 0; i < len; i++) {
        list[i] = cursor.getLong(colidx);
        cursor.moveToNext();
    }
    return list;
}
 
Example 7
Source File: Gifflen.java    From Pixiv-Shaft with MIT License 6 votes vote down vote up
/**
 * 从Uri获取图片的绝对路径
 *
 * @param context    上下文对象.
 * @param contentUri 传入的Uri数组.
 * @return 文件绝对路径.
 */
public String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] projection = {MediaStore.Images.Media.DATA};
        cursor = context.getContentResolver().query(contentUri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }

    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return "";
}
 
Example 8
Source File: CommonUtil.java    From sctalk with Apache License 2.0 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: FirestackStorage.java    From react-native-firestack with MIT License 6 votes vote down vote up
@ReactMethod
public void getRealPathFromURI(final String uri, final Callback callback) {
  try {
    Context context = getReactApplicationContext();
    String [] proj = {MediaStore.Images.Media.DATA};
    Cursor cursor = context.getContentResolver().query(Uri.parse(uri), proj,  null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String path = cursor.getString(column_index); 
    cursor.close();

    callback.invoke(null, path);
  } catch (Exception ex) {
    ex.printStackTrace();
    callback.invoke(makeErrorPayload(1, ex));
  }
}
 
Example 10
Source File: SqlStorage.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
@Override
public void bulkReadMetadata(LinkedHashSet cuedCases, String[] metaDataIds, HashMap metadataMap) {
    List<Pair<String, String[]>> whereParamList = TableBuilder.sqlList(cuedCases);
    String[] scrubbedNames = scrubMetadataNames(metaDataIds);
    String[] projection = getProjectedFieldsWithId(false, scrubbedNames);

    for (Pair<String, String[]> querySet : whereParamList) {
        Cursor c = helper.getHandle().query(table, projection, DatabaseHelper.ID_COL + " IN " + querySet.first, querySet.second, null, null, null);
        try {
            if (c.getCount() == 0) {
                return;
            } else {
                c.moveToFirst();
                int idIndex = c.getColumnIndexOrThrow(DatabaseHelper.ID_COL);
                while (!c.isAfterLast()) {
                    String[] metaRead = readMetaDataFromCursor(c, scrubbedNames);
                    metadataMap.put(c.getInt(idIndex), metaRead);
                    c.moveToNext();
                }
            }
        } finally {
            c.close();
        }
    }
}
 
Example 11
Source File: ContentResolverUtils.java    From ImagePicker with Apache License 2.0 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 = MediaStore.MediaColumns.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);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return null;
}
 
Example 12
Source File: ImageValidator.java    From Learning-Resources with MIT 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";// android.provider.MediaStore.Files.FileColumns.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 13
Source File: UriHelper.java    From libcommon with Apache License 2.0 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.
 */
@Nullable
public static String getDataColumn(@NonNull final Context context,
	@NonNull final Uri uri, final String selection, final 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 column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
		}
    }
    return null;
}
 
Example 14
Source File: MainActivity.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
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 15
Source File: UriToPathResolver.java    From aptoide-client-v8 with GNU General Public License v3.0 5 votes vote down vote up
public String getMediaStoragePath(Uri contentUri) {
  if (contentUri == null) {
    throw new NullPointerException("content Uri is null");
  }

  Cursor cursor = null;
  try {
    final String columnName = MediaStore.Images.Media.DATA;
    String[] projection = { columnName };
    cursor = contentResolver.query(contentUri, projection, null, null, null);
    if (cursor != null) {
      int column_index = cursor.getColumnIndexOrThrow(columnName);
      cursor.moveToFirst();
      return cursor.getString(column_index);
    }
  } catch (Exception ex) {
    Logger.getInstance()
        .e(TAG, ex);
  } finally {
    if (cursor != null && !cursor.isClosed()) {
      cursor.close();
    }
  }

  // default situation
  return contentUri.toString();
}
 
Example 16
Source File: AndroidUtilities.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
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 column_index = cursor.getColumnIndexOrThrow(column);
            String value = cursor.getString(column_index);
            if (value.startsWith("content://") || !value.startsWith("/") && !value.startsWith("file://"))
            {
                return null;
            }
            return value;
        }
    }
    catch (Exception ignore)
    {

    }
    finally
    {
        if (cursor != null)
        {
            cursor.close();
        }
    }
    return null;
}
 
Example 17
Source File: CursorAdapter.java    From letv with Apache License 2.0 5 votes vote down vote up
public Cursor swapCursor(Cursor newCursor) {
    if (newCursor == this.mCursor) {
        return null;
    }
    Cursor oldCursor = this.mCursor;
    if (oldCursor != null) {
        if (this.mChangeObserver != null) {
            oldCursor.unregisterContentObserver(this.mChangeObserver);
        }
        if (this.mDataSetObserver != null) {
            oldCursor.unregisterDataSetObserver(this.mDataSetObserver);
        }
    }
    this.mCursor = newCursor;
    if (newCursor != null) {
        if (this.mChangeObserver != null) {
            newCursor.registerContentObserver(this.mChangeObserver);
        }
        if (this.mDataSetObserver != null) {
            newCursor.registerDataSetObserver(this.mDataSetObserver);
        }
        this.mRowIDColumn = newCursor.getColumnIndexOrThrow("_id");
        this.mDataValid = true;
        notifyDataSetChanged();
        return oldCursor;
    }
    this.mRowIDColumn = -1;
    this.mDataValid = false;
    notifyDataSetInvalidated();
    return oldCursor;
}
 
Example 18
Source File: TweetCursorReader.java    From Onosendai with Apache License 2.0 4 votes vote down vote up
public String readUserSubtitle (final Cursor c) {
	if (c == null) return null;
	if (this.colUserSubtitle < 0) this.colUserSubtitle = c.getColumnIndexOrThrow(DbAdapter.TBL_TW_USERSUBTITLE);
	return c.getString(this.colUserSubtitle);
}
 
Example 19
Source File: AutofillDao_Impl.java    From android-AutofillFramework with Apache License 2.0 4 votes vote down vote up
private void __fetchRelationshipResourceIdHeuristicAscomExampleAndroidAutofillServiceModelResourceIdHeuristic(final ArrayMap<String, ArrayList<ResourceIdHeuristic>> _map) {
  final Set<String> __mapKeySet = _map.keySet();
  if (__mapKeySet.isEmpty()) {
    return;
  }
  StringBuilder _stringBuilder = StringUtil.newStringBuilder();
  _stringBuilder.append("SELECT resourceIdHeuristic,packageName,fieldTypeName FROM `ResourceIdHeuristic` WHERE fieldTypeName IN (");
  final int _inputSize = __mapKeySet.size();
  StringUtil.appendPlaceholders(_stringBuilder, _inputSize);
  _stringBuilder.append(")");
  final String _sql = _stringBuilder.toString();
  final int _argCount = 0 + _inputSize;
  final RoomSQLiteQuery _stmt = RoomSQLiteQuery.acquire(_sql, _argCount);
  int _argIndex = 1;
  for (String _item : __mapKeySet) {
    if (_item == null) {
      _stmt.bindNull(_argIndex);
    } else {
      _stmt.bindString(_argIndex, _item);
    }
    _argIndex ++;
  }
  final Cursor _cursor = __db.query(_stmt);
  try {
    final int _itemKeyIndex = _cursor.getColumnIndex("fieldTypeName");
    if (_itemKeyIndex == -1) {
      return;
    }
    final int _cursorIndexOfMResourceIdHeuristic = _cursor.getColumnIndexOrThrow("resourceIdHeuristic");
    final int _cursorIndexOfMPackageName = _cursor.getColumnIndexOrThrow("packageName");
    final int _cursorIndexOfMFieldTypeName = _cursor.getColumnIndexOrThrow("fieldTypeName");
    while(_cursor.moveToNext()) {
      if (!_cursor.isNull(_itemKeyIndex)) {
        final String _tmpKey = _cursor.getString(_itemKeyIndex);
        ArrayList<ResourceIdHeuristic> _tmpCollection = _map.get(_tmpKey);
        if (_tmpCollection != null) {
          final ResourceIdHeuristic _item_1;
          final String _tmpMResourceIdHeuristic;
          _tmpMResourceIdHeuristic = _cursor.getString(_cursorIndexOfMResourceIdHeuristic);
          final String _tmpMPackageName;
          _tmpMPackageName = _cursor.getString(_cursorIndexOfMPackageName);
          final String _tmpMFieldTypeName;
          _tmpMFieldTypeName = _cursor.getString(_cursorIndexOfMFieldTypeName);
          _item_1 = new ResourceIdHeuristic(_tmpMResourceIdHeuristic,_tmpMFieldTypeName,_tmpMPackageName);
          _tmpCollection.add(_item_1);
        }
      }
    }
  } finally {
    _cursor.close();
  }
}
 
Example 20
Source File: MediaStoreServiceImpl.java    From AndroidMvc with Apache License 2.0 4 votes vote down vote up
/**
 * Extract an imageDTO from given cursor position from its current position.
 * @param cursor
 * @return
 */
protected ImageDTO extractOneImageFromCurrentCursor(Cursor cursor) {
    int api = android.os.Build.VERSION.SDK_INT;
    if(imageIdCol == -1) {
        imageIdCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
        imageTitleCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.TITLE);
        imageDisplayNameCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME);
        imageDescriptionCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DESCRIPTION);
        imageBucketIdCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_ID);
        imageBucketDisplayNameCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
        imageDataCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        imageMimeCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.MIME_TYPE);
        imageSizeCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE);
        imageOrientationCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.ORIENTATION);
        imageDateAddedCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED);
        imageDateTakenCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_TAKEN);
        imageDateModifyCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_MODIFIED);
        latitudeCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.LATITUDE);
        longitudeCol = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.LONGITUDE);
        if (api >= 16) {
            widthCol = cursor.getColumnIndexOrThrow(MediaStore_Media_WIDTH);
            heightCol = cursor.getColumnIndexOrThrow(MediaStore_Media_HEIGHT);
        }
    }

    ImageDTO image = new ImageDTO();
    image.setId(cursor.getLong(imageIdCol));
    image.setTitle(cursor.getString(imageTitleCol));
    image.setDisplayName(cursor.getString(imageDisplayNameCol));
    image.setDescription(cursor.getString(imageDescriptionCol));
    image.setBucketId(cursor.getString(imageBucketIdCol));
    image.setBucketDisplayName(cursor.getString(imageBucketDisplayNameCol));
    image.setUri(cursor.getString(imageDataCol));
    image.setMimeType(cursor.getString(imageMimeCol));
    image.setSize(cursor.getLong(imageSizeCol));
    image.setOrientation(translateOrientation(cursor.getInt(imageOrientationCol)));
    image.setAddedDate(new Date(cursor.getLong(imageDateAddedCol)));
    image.setTakenDate(new Date(cursor.getLong(imageDateTakenCol)));
    image.setModifyDate(new Date(cursor.getLong(imageDateModifyCol)));
    image.setLatitude(cursor.getDouble(latitudeCol));
    image.setLongitude(cursor.getDouble(longitudeCol));
    if (api >= 16) {
        image.setWidth(cursor.getInt(widthCol));
        image.setHeight(cursor.getInt(heightCol));
    }

    return image;
}