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

The following are Jave code examples for showing how to use getColumnIndexOrThrow() of the android.database.Cursor class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: LoRaWAN-Smart-Parking   File: FileHelper.java   Source Code and License Vote up 6 votes
/**
 * Returns the real path of the given URI string.
 * If the given URI string represents a content:// URI, the real path is retrieved from the media store.
 *
 * @param uriString the URI string of the audio/image/video
 * @param cordova the current application context
 * @return the full path to the file
 */
@SuppressWarnings("deprecation")
public static String getRealPath(String uriString, CordovaInterface cordova) {
    String realPath = null;

    if (uriString.startsWith("content://")) {
        String[] proj = { _DATA };
        Cursor cursor = cordova.getActivity().managedQuery(Uri.parse(uriString), proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(_DATA);
        cursor.moveToFirst();
        realPath = cursor.getString(column_index);
        if (realPath == null) {
            LOG.e(LOG_TAG, "Could get real path for URI string %s", uriString);
        }
    } else if (uriString.startsWith("file://")) {
        realPath = uriString.substring(7);
        if (realPath.startsWith("/android_asset/")) {
            LOG.e(LOG_TAG, "Cannot get real path for URI string %s because it is a file:///android_asset/ URI.", uriString);
            realPath = null;
        }
    } else {
        realPath = uriString;
    }

    return realPath;
}
 
Example 2
Project: Customerly-Android-SDK   File: IU_Utils.java   Source Code and License Vote up 6 votes
@Nullable private 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 3
Project: zxing_qrcode_demo   File: CodeUtils.java   Source Code and License Vote up 6 votes
public static String getDataColumn(@NonNull Context context, Uri uri, String selection, String[] selectionArgs) {
    Cursor cursor = null;
    String column = MediaStore.Images.Media.DATA;
    String[] projection = {column};
    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            int index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}
 
Example 4
Project: Bigbang   File: CropFileUtils.java   Source Code and License Vote up 6 votes
/**
 * 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
Project: PaoMovie   File: StaticMethod.java   Source Code and License Vote up 6 votes
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
	Cursor cursor = null;
	String column = MediaStore.Images.Media.DATA;
	String[] projection = { column };
	try {
		cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
		if (cursor != null && cursor.moveToFirst()) {
			int index = cursor.getColumnIndexOrThrow(column);
			return cursor.getString(index);
		}
	} finally {
		if (cursor != null)
			cursor.close();
	}
	return null;
}
 
Example 6
Project: file.io-app   File: FileUtils.java   Source Code and License Vote up 6 votes
/**
 * 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.
 * @author paulburke
 */
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()) {
            if (DEBUG)
                DatabaseUtils.dumpCursor(cursor);

            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}
 
Example 7
Project: BuddyBook   File: PathUtils.java   Source Code and License Vote up 6 votes
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 8
Project: boohee_v5.6   File: WebViewActivity.java   Source Code and License Vote up 6 votes
private Uri a(Intent intent) {
    Cursor query = this.e.getContentResolver().query(intent.getData(), new String[]{"_data"},
            null, null, null);
    if (query == null) {
        return null;
    }
    int columnIndexOrThrow = query.getColumnIndexOrThrow("_data");
    query.moveToFirst();
    String string = query.getString(columnIndexOrThrow);
    if (string != null && (string.endsWith(".png") || string.endsWith(".PNG") || string
            .endsWith(".jpg") || string.endsWith(".JPG"))) {
        return Uri.fromFile(e.b(string, this.b.c));
    }
    query.close();
    return null;
}
 
Example 9
Project: aos-MediaLib   File: LibraryUtils.java   Source Code and License Vote up 6 votes
public static Uri[] getAlbumArtsFromArtist(Context context, long artistId) {

		final Uri uri = MusicStore.Audio.Artists.Albums.getContentUri("external", artistId);
		final String sortOrder = MusicStore.Audio.Media.YEAR + DESC;
		StringBuilder where = new StringBuilder();
		where.append(MusicStore.Audio.Artists.Albums.ALBUM_ART).append(" != ''");

		Cursor c = query(context,uri, ALBUM_COLS, where.toString(), null, sortOrder);
		if (c==null) return null;

		Uri result[] = new Uri[c.getCount()];

		final int albumIdIdx = c.getColumnIndexOrThrow(MusicStore.Audio.Albums._ID);

		c.moveToFirst();
		int n=0;
		while (!c.isAfterLast() && (n<result.length)) { // better safe than sorry
			result[n++] = ContentUris.withAppendedId(ALBUM_ARTWORK_URI, c.getLong(albumIdIdx));
			c.moveToNext();
		}

		return result;
	}
 
Example 10
Project: AndroidSdrRtlTuner   File: SettingsFragment.java   Source Code and License Vote up 5 votes
/**
 * Extract the path from an uri
 * This code was published on StackOverflow by dextor
 *
 * @param contentUri		uri that contains the file path
 * @return absolute file path as string
 */
private String getRealPathFromURI(Uri contentUri) {
	String[] proj = { MediaStore.Images.Media.DATA };
	CursorLoader loader = new CursorLoader(this.getActivity(), contentUri, proj, null, null, null);
	Cursor cursor = loader.loadInBackground();
	int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	cursor.moveToFirst();
	return cursor.getString(column_index);
}
 
Example 11
Project: AgentWeb   File: AgentWebUtils.java   Source Code and License Vote up 5 votes
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 12
Project: Cable-Android   File: SmsMigrator.java   Source Code and License Vote up 5 votes
private static void addEncryptedStringToStatement(Context context, SQLiteStatement statement,
                                                  Cursor cursor, MasterSecret masterSecret,
                                                  int index, String key)
{
  int columnIndex = cursor.getColumnIndexOrThrow(key);

  if (cursor.isNull(columnIndex)) {
    statement.bindNull(index);
  } else {
    statement.bindString(index, encrypt(masterSecret, cursor.getString(columnIndex)));
  }
}
 
Example 13
Project: siiMobilityAppKit   File: FileHelper.java   Source Code and License Vote up 5 votes
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    String result = null;

    try {
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        result = cursor.getString(column_index);

    } catch (Exception e) {
        result = null;
    }
    return result;
}
 
Example 14
Project: News24x7-news-from-every-part-of-the-world   File: CursorRecyclerViewAdapter.java   Source Code and License Vote up 5 votes
/**
 * Swap in a new Cursor, returning the old Cursor.  Unlike
 * {@link #changeCursor(Cursor)}, the returned old Cursor is <em>not</em>
 * closed.
 *
 * @param newCursor The new cursor to be used.
 * @return Returns the previously set Cursor, or null if there wasa not one.
 * If the given new Cursor is the same instance is the previously set
 * Cursor, null is also returned.
 */
public Cursor swapCursor(Cursor newCursor) {
    if (newCursor == mCursor) {
        return null;
    }
    Cursor oldCursor = mCursor;
    if (oldCursor != null) {
        if (mChangeObserver != null) oldCursor.unregisterContentObserver(mChangeObserver);
        if (mDataSetObserver != null) oldCursor.unregisterDataSetObserver(mDataSetObserver);
    }
    mCursor = newCursor;
    if (newCursor != null) {
        if (mChangeObserver != null) newCursor.registerContentObserver(mChangeObserver);
        if (mDataSetObserver != null) newCursor.registerDataSetObserver(mDataSetObserver);
        mRowIDColumn = newCursor.getColumnIndexOrThrow("_id");
        mDataValid = true;
        // notify the observers about the new cursor
        notifyDataSetChanged();
    } else {
        mRowIDColumn = -1;
        mDataValid = false;
        // notify the observers about the lack of a data set
        // notifyDataSetInvalidated();
        notifyItemRangeRemoved(0, oldCursor.getCount());
    }
    return oldCursor;
}
 
Example 15
Project: GCSApp   File: CreateACActivity.java   Source Code and License Vote up 5 votes
public String getPathFromUri(Uri uri) {
    String[] projection = {MediaStore.Images.Media.DATA};
    Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}
 
Example 16
Project: MVP-Android   File: RealPathUtils.java   Source Code and License Vote up 5 votes
@SuppressLint("Recycle")
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
    String[] proj = { MediaStore.Images.Media.DATA };
    Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
    int column_index = cursor != null ? cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA) : 0;
    if (cursor != null) {
        cursor.moveToFirst();
    }
    return cursor != null ? cursor.getString(column_index) : null;
}
 
Example 17
Project: financisto1-holo   File: Utils.java   Source Code and License Vote up 5 votes
public static int moveCursor(Cursor cursor, String idColumnName, long id) {
       int pos = cursor.getColumnIndexOrThrow(idColumnName);
       if (cursor.moveToFirst()) {
           do {
               if (cursor.getLong(pos) == id) {
                   return cursor.getPosition();
               }
           } while(cursor.moveToNext());
       }
	return -1;
}
 
Example 18
Project: FlickLauncher   File: GridSizeMigrationTask.java   Source Code and License Vote up 4 votes
private ArrayList<DbEntry> loadHotseatEntries() {
    Cursor c =  mContext.getContentResolver().query(LauncherSettings.Favorites.CONTENT_URI,
            new String[]{
                    Favorites._ID,                  // 0
                    Favorites.ITEM_TYPE,            // 1
                    Favorites.INTENT,               // 2
                    Favorites.SCREEN},              // 3
            Favorites.CONTAINER + " = " + Favorites.CONTAINER_HOTSEAT, null, null, null);

    final int indexId = c.getColumnIndexOrThrow(Favorites._ID);
    final int indexItemType = c.getColumnIndexOrThrow(Favorites.ITEM_TYPE);
    final int indexIntent = c.getColumnIndexOrThrow(Favorites.INTENT);
    final int indexScreen = c.getColumnIndexOrThrow(Favorites.SCREEN);

    ArrayList<DbEntry> entries = new ArrayList<>();
    while (c.moveToNext()) {
        DbEntry entry = new DbEntry();
        entry.id = c.getLong(indexId);
        entry.itemType = c.getInt(indexItemType);
        entry.screenId = c.getLong(indexScreen);

        if (entry.screenId >= mSrcHotseatSize) {
            mEntryToRemove.add(entry.id);
            continue;
        }

        try {
            // calculate weight
            switch (entry.itemType) {
                case Favorites.ITEM_TYPE_SHORTCUT:
                case Favorites.ITEM_TYPE_DEEP_SHORTCUT:
                case Favorites.ITEM_TYPE_APPLICATION: {
                    verifyIntent(c.getString(indexIntent));
                    entry.weight = entry.itemType == Favorites.ITEM_TYPE_APPLICATION ?
                            WT_APPLICATION : WT_SHORTCUT;
                    break;
                }
                case Favorites.ITEM_TYPE_FOLDER: {
                    int total = getFolderItemsCount(entry.id);
                    if (total == 0) {
                        throw new Exception("Folder is empty");
                    }
                    entry.weight = WT_FOLDER_FACTOR * total;
                    break;
                }
                default:
                    throw new Exception("Invalid item type");
            }
        } catch (Exception e) {
            if (DEBUG) {
                Log.d(TAG, "Removing item " + entry.id, e);
            }
            mEntryToRemove.add(entry.id);
            continue;
        }
        entries.add(entry);
    }
    c.close();
    return entries;
}
 
Example 19
Project: FuelUp   File: VehicleService.java   Source Code and License Vote up 4 votes
public static Vehicle getVehicleById(long id, Context context) {
    String[] selectionArgs = { String.valueOf(id) };
    Cursor cursor = context.getContentResolver().query(VehicleEntry.CONTENT_URI,
            FuelUpContract.ALL_COLUMNS_VEHICLES, VehicleEntry._ID + "=?",
            selectionArgs, null);

    if (cursor == null || cursor.getCount() != 1) {
        Log.e(LOG_TAG, "Cannot get Vehicle for id=" + id);
        return null;
    }

    cursor.moveToFirst();
    int typeId = cursor.getInt(cursor.getColumnIndexOrThrow(VehicleEntry.COLUMN_TYPE));

    Vehicle vehicle = new Vehicle();
    vehicle.setId(cursor.getLong(cursor.getColumnIndexOrThrow(VehicleEntry._ID)));
    vehicle.setName(cursor.getString(cursor.getColumnIndexOrThrow(VehicleEntry.COLUMN_NAME)));
    vehicle.setCurrency(Currency.getInstance(cursor.getString(cursor.getColumnIndexOrThrow(VehicleEntry.COLUMN_CURRENCY))));
    vehicle.setVehicleMaker(cursor.getString(cursor.getColumnIndexOrThrow(VehicleEntry.COLUMN_VEHICLE_MAKER)));
    vehicle.setType(VehicleTypeService.getVehicleTypeById(typeId, context));
    vehicle.setVolumeUnit(getVolumeUnitFromString(cursor.getString(cursor.getColumnIndexOrThrow(VehicleEntry.COLUMN_VOLUME_UNIT))));

    int columnPicturePath = cursor.getColumnIndexOrThrow(VehicleEntry.COLUMN_PICTURE);
    if (cursor.isNull(columnPicturePath)) {
        vehicle.setPathToPicture(null);
    } else {
        vehicle.setPathToPicture(cursor.getString(columnPicturePath));
    }


    int columnMileage = cursor.getColumnIndexOrThrow(VehicleEntry.COLUMN_START_MILEAGE);
    if (cursor.isNull(columnMileage)) {
        vehicle.setStartMileage(null);
    } else {
        vehicle.setStartMileage(cursor.getLong(columnMileage));
    }

    cursor.close();

    return vehicle;
}
 
Example 20
Project: aos-Video   File: AllTVShowsProvider.java   Source Code and License Vote up 4 votes
protected Collection<Cover> convertCursorToCovers(Cursor c, boolean update) {
    if(DBG) Log.d(TAG, "convertCursorToCovers()");
    final int mIdidx = c.getColumnIndexOrThrow(BaseColumns._ID);
    final int mNameIdx = c.getColumnIndexOrThrow(VideoStore.Video.VideoColumns.SCRAPER_TITLE);
    final int mPosterIdx = c.getColumnIndexOrThrow(VideoStore.Video.VideoColumns.SCRAPER_S_COVER);
    final int seasonNumberIdx = c.getColumnIndexOrThrow(VideoStore.Video.VideoColumns.SCRAPER_E_SEASON);
    final int anyEpisodeFilePathIdx = c.getColumnIndexOrThrow(VideoStore.Video.VideoColumns.DATA);
    final int epCountIdx = c.getColumnIndexOrThrow(AllTvshowsLoader.COLUMN_EPISODE_COUNT);
    final int seasCountIdx = c.getColumnIndexOrThrow(AllTvshowsLoader.COLUMN_SEASON_COUNT);

    //keep a reference to the previous Cover Map, to keep track of covers that are not in the new cursor anymore, to recycle them
    HashMap<String, Cover> newCoverIdMap = new HashMap<String, Cover>();

    // Allocate new array (we don't have to keep the previous one, update is handled using the old CoverMap instead
    mCoverArray = new ArrayList<Cover>(c.getCount());
    c.moveToPosition(-1); // make sure position is before first
    while (c.moveToNext()) {
        final long id = c.getLong(mIdidx);
        final int numberOfEpisodes = c.getInt(epCountIdx);
        final String name = c.getString(mNameIdx);
        final String poster = c.getString(mPosterIdx);
        final int seasonCount = c.getInt(seasCountIdx);
        final int seasonNumber = c.getInt(seasonNumberIdx);
        final String anyEpisodeFilePath = c.getString(anyEpisodeFilePathIdx);
        Cover cover = null;
        // Update case
        if (update) {
            // For the TVShow covers there is a special method to compute the CoverID. It integrates the number of episodes,
            // so that the cover is updated in case it is changed (only the description texture should be updated tough...)
            final String coverID = TvShowCover.computeCoverIDwithNumberOfEpisode(id, numberOfEpisodes);
            if (DBG) Log.d(TAG, "convertCursorToCovers update: coverID="+coverID);
            // Is it in the previous cover collection already?
            cover = mCoverIdMap.get(coverID);
            if (cover!=null) {
                if (DBG) Log.d(TAG, "convertCursorToCovers update: found "+coverID+" in previous covers");
                // remove in the old cover map. Will allow to keep track of the non-recycled covers remaining at the end
                mCoverIdMap.remove(coverID);
            } else {
                if (DBG) Log.d(TAG, "convertCursorToCovers update: "+coverID+" not found in previous covers");
            }
        }
        if (cover==null) {
            // Create a new one
            cover = new TvShowCover(id, name, numberOfEpisodes, poster, seasonCount, seasonNumber, anyEpisodeFilePath);
        }
        mCoverArray.add(cover);
        if (DBG) Log.d(TAG, "convertCursorToCovers: put coverID="+cover.getCoverID());
        newCoverIdMap.put(cover.getCoverID(), cover);
    }

    // Must not close the cursor here. It is handled at CoverProvider level.

    // Return the collection of covers to recycle
    Collection<Cover> coversToRecycle = null;
    if (update) {
        coversToRecycle = mCoverIdMap.values();
    }

    // Update the CoverMap: old = new, now
    mCoverIdMap = newCoverIdMap;

    // Sanity check
    if (mCoverArray.size() == 0) {
        mErrorMessage = mContext.getResources().getString(R.string.you_have_no_tv_shows);
        mErrorMessage += "\n\n" + mContext.getResources().getString(R.string.scraper_suggest_message);
        Log.e(TAG,"Error: " + mErrorMessage);
    }
    return coversToRecycle;
}