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

The following examples show how to use android.database.Cursor#moveToFirst() . 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: CheckInTask.java    From attendee-checkin with Apache License 2.0 6 votes vote down vote up
private Checkin loadCheckin(ContentResolver resolver) {
    Cursor cursor = null;
    try {
        cursor = resolver.query(Table.ATTENDEE.getItemUri(mEventId, mAttendeeId),
                Checkin.PROJECTION, null, null, null);
        if (cursor.getCount() == 0) {
            return null;
        }
        cursor.moveToFirst();
        return new Checkin(cursor);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
 
Example 2
Source File: MusicPlayerRemote.java    From Music-Player 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 3
Source File: DatabaseManager.java    From restcomm-android-sdk with GNU Affero General Public License v3.0 6 votes vote down vote up
public boolean addContactIfNeded(String uri)
{
   if (databaseHelper == null) {
      throw new RuntimeException("Database hasn't been opened.");
   }

   String contactName = uri.replaceAll("^sip.?:", "").replaceAll("@.*$", "");

   Cursor cursor = getContactFromName(contactName);
   if (!cursor.moveToFirst()) {
      // doesn't exist, need to create it
      // Gets the data repository in write mode
      SQLiteDatabase db = databaseHelper.getWritableDatabase();

      // Create a new map of values, where column names are the keys
      ContentValues values = new ContentValues();

      values.put(DatabaseContract.ContactEntry.COLUMN_NAME_NAME, contactName);
      values.put(DatabaseContract.ContactEntry.COLUMN_NAME_URI, contactName);

      db.insertOrThrow(DatabaseContract.ContactEntry.TABLE_NAME, null, values);

      return true;
   }
   return false;
}
 
Example 4
Source File: MovieRequestHandler.java    From cathode with Apache License 2.0 6 votes vote down vote up
@Override protected String getCachedPath(ImageType imageType, long id) {
  Cursor c = null;

  try {
    c = context.getContentResolver().query(Movies.withId(id), new String[] {
        MovieColumns.IMAGES_LAST_UPDATE, MovieColumns.POSTER, MovieColumns.BACKDROP,
    }, null, null, null);
    c.moveToFirst();

    if (imageType == ImageType.POSTER) {
      return Cursors.getString(c, MovieColumns.POSTER);
    } else if (imageType == ImageType.BACKDROP) {
      return Cursors.getString(c, MovieColumns.BACKDROP);
    } else {
      throw new IllegalArgumentException("Unsupported image type: " + imageType.toString());
    }
  } finally {
    Closeables.closeQuietly(c);
  }
}
 
Example 5
Source File: LgcDataUtil.java    From live-group-chat with GNU Affero General Public License v3.0 6 votes vote down vote up
public static int getNoSyncCount(Context context) {
    Cursor cursor =
            context.getContentResolver().query(LgcProvider.NOTIFICATION_URI,
                    new String[] {"count(*)"}, LgcProvider.DataColumns.SYNC + " = ?",
                    new String[] {"0"}, null);
    if (cursor == null) {
        return 0;
    }

    int count = 0;
    if (cursor.moveToFirst()) {
        count = cursor.getInt(0);
    }
    cursor.close();

    return count;
}
 
Example 6
Source File: MainActivity.java    From PixaToon with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Callback for 'Select Picture' intent result
 * @param requestCode
 * @param resultCode
 * @param data
 */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            // Get the cursor
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            // Move to first row
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            // Get selected picture filepath
            String pictureFilePath = cursor.getString(columnIndex);
            cursor.close();
            Log.d(TAG, "Picture picked- " + pictureFilePath);

            // Switch to picture view mode, loading the selected picture
            openPictureFilterViewer(pictureFilePath);
        }
    }
}
 
Example 7
Source File: FileHelper.java    From L.TileLayer.Cordova with MIT License 6 votes vote down vote up
/**
 * 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 8
Source File: TelephonyCompat.java    From flutter_sms with MIT License 6 votes vote down vote up
/**
 * Given the recipients list and subject of an unsaved message,
 * return its thread ID.  If the message starts a new thread,
 * allocate a new thread ID.  Otherwise, use the appropriate
 * existing thread ID.
 *
 * <p>Find the thread ID of the same set of recipients (in any order,
 * without any additions). If one is found, return it. Otherwise,
 * return a unique thread ID.</p>
 */
private static long getOrCreateThreadIdInternal(Context context, Set<String> recipients) {
  Uri.Builder uriBuilder = THREAD_ID_CONTENT_URI.buildUpon();
  for (String recipient : recipients) {
    uriBuilder.appendQueryParameter("recipient", recipient);
  }
  Uri uri = uriBuilder.build();
  Cursor cursor = query(
      context.getContentResolver(), uri, new String[] {BaseColumns._ID});
  if (cursor != null) {
    try {
      if (cursor.moveToFirst()) {
        return cursor.getLong(0);
      }
    } finally {
      cursor.close();
    }
  }
  throw new IllegalArgumentException("Unable to find or allocate a thread ID.");
}
 
Example 9
Source File: LauncherModel.java    From TurboLauncher with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the shortcuts already exists in the database. we identify
 * a shortcut by the component name of the intent.
 */
static boolean appWasRestored(Context context, Intent intent) {
	final ContentResolver cr = context.getContentResolver();
	final ComponentName component = intent.getComponent();
	if (component == null) {
		return false;
	}
	String componentName = component.flattenToString();
	final String where = "intent glob \"*component=" + componentName
			+ "*\" and restored = 1";
	Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
			new String[] { "intent", "restored" }, where, null, null);
	boolean result = false;
	try {
		result = c.moveToFirst();
	} finally {
		c.close();
	}

	return result;
}
 
Example 10
Source File: TestActivity.java    From v2ex with Apache License 2.0 6 votes vote down vote up
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    onRefreshingStateChanged(false);
    if (data != null) {
        data.moveToPosition(-1);
        if (data.moveToFirst()) {
            String id = data.getString(data.getColumnIndex(V2exContract.Reviews.REVIEW_ID));
            String member = data.getString(data.getColumnIndex(V2exContract.Reviews.REVIEW_MEMBER));
            String content = data.getString(data.getColumnIndex(V2exContract.Reviews.REVIEW_CONTENT));
            int reviewCount = data.getCount();
            Toast.makeText(TestActivity.this, "review_id=" + id +
                            ", reviewMember=" + member +
                            ", reviewContent=" + content +
                            ", reviewCount=" + reviewCount,
                    Toast.LENGTH_SHORT).show();
            LOGD(TAG, "review_id=" + id +
                    ", reviewMember=" + member +
                    ", reviewContent=" + content +
                    ", reviewCount=" + reviewCount);

        }
    }
}
 
Example 11
Source File: Database.java    From ShaderEditor with MIT License 5 votes vote down vote up
public boolean isShaderAvailable(long id) {
	Cursor cursor = db.rawQuery(
			"SELECT " +
					SHADERS_ID +
					" FROM " + SHADERS +
					" WHERE " + SHADERS_ID + " = ?",
			new String[]{String.valueOf(id)});
	if (cursor == null) {
		return false;
	}
	boolean exists = cursor.moveToFirst();
	cursor.close();
	return exists;
}
 
Example 12
Source File: LevelsDataSource.java    From gravitydefied with GNU General Public License v2.0 5 votes vote down vote up
public synchronized Level createLevel(String name, String author, int countEasy, int countMedium, int countHard, long addedTs, long installedTs, boolean isDefault, long apiId) {
	ContentValues values = new ContentValues();
	values.put(LevelsSQLiteOpenHelper.LEVELS_COLUMN_NAME, name);
	values.put(LevelsSQLiteOpenHelper.LEVELS_COLUMN_AUTHOR, author);
	values.put(LevelsSQLiteOpenHelper.LEVELS_COLUMN_COUNT_EASY, countEasy);
	values.put(LevelsSQLiteOpenHelper.LEVELS_COLUMN_COUNT_MEDIUM, countMedium);
	values.put(LevelsSQLiteOpenHelper.LEVELS_COLUMN_COUNT_HARD, countHard);
	values.put(LevelsSQLiteOpenHelper.LEVELS_COLUMN_ADDED, addedTs);
	values.put(LevelsSQLiteOpenHelper.LEVELS_COLUMN_INSTALLED, installedTs);
	values.put(LevelsSQLiteOpenHelper.LEVELS_COLUMN_IS_DEFAULT, isDefault ? 1 : 0);
	values.put(LevelsSQLiteOpenHelper.LEVELS_COLUMN_API_ID, apiId);
	values.put(LevelsSQLiteOpenHelper.LEVELS_COLUMN_UNLOCKED_EASY, 0);
	values.put(LevelsSQLiteOpenHelper.LEVELS_COLUMN_UNLOCKED_MEDIUM, 0);
	values.put(LevelsSQLiteOpenHelper.LEVELS_COLUMN_UNLOCKED_HARD, 0);
	values.put(LevelsSQLiteOpenHelper.LEVELS_COLUMN_SELECTED_TRACK, 0);
	values.put(LevelsSQLiteOpenHelper.LEVELS_COLUMN_SELECTED_LEVEL, 0);
	values.put(LevelsSQLiteOpenHelper.LEVELS_COLUMN_SELECTED_LEAGUE, 0);
	values.put(LevelsSQLiteOpenHelper.LEVELS_COLUMN_UNLOCKED_LEVELS, 0);
	values.put(LevelsSQLiteOpenHelper.LEVELS_COLUMN_UNLOCKED_LEAGUES, 0);

	long insertId = db.insert(LevelsSQLiteOpenHelper.TABLE_LEVELS, null, values);
	Cursor cursor = db.query(LevelsSQLiteOpenHelper.TABLE_LEVELS, null,
			LevelsSQLiteOpenHelper.LEVELS_COLUMN_ID + " = " + insertId,
			null, null, null, null);

	cursor.moveToFirst();

	Level level = cursorToLevel(cursor);
	cursor.close();
	return level;
}
 
Example 13
Source File: GameDataSQLiteDataSource.java    From Word-Search-Game with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void getGameData(int gid, GameRoundCallback callback) {
    SQLiteDatabase db = mHelper.getReadableDatabase();

    String cols[] = {
            DbContract.GameRound._ID,
            DbContract.GameRound.COL_NAME,
            DbContract.GameRound.COL_DURATION,
            DbContract.GameRound.COL_GRID_ROW_COUNT,
            DbContract.GameRound.COL_GRID_COL_COUNT,
            DbContract.GameRound.COL_GRID_DATA
    };
    String sel = DbContract.GameRound._ID + "=?";
    String selArgs[] = {String.valueOf(gid)};

    Cursor c = db.query(DbContract.GameRound.TABLE_NAME, cols, sel, selArgs, null, null, null);
    GameDataEntity ent = null;
    if (c.moveToFirst()) {
        ent = new GameDataEntity();
        ent.setId(c.getInt(0));
        ent.setName(c.getString(1));
        ent.setDuration(c.getInt(2));
        ent.setGridRowCount(c.getInt(3));
        ent.setGridColCount(c.getInt(4));
        ent.setGridData(c.getString(5));
        ent.setUsedWords(getUsedWords(gid));
    }
    c.close();

    callback.onLoaded(ent);
}
 
Example 14
Source File: OcrUtils.java    From LockDemo with Apache License 2.0 5 votes vote down vote up
public static String getDataColumn(Context context,
                                   Uri uri,
                                   String selection,
                                   String[] selectionArgs) {
    Cursor cursor = null;
    String column = "_data";
    String[] projection = new String[]{"_data"};

    try {
        cursor = context.getContentResolver()
                .query(uri,
                        projection,
                        selection,
                        selectionArgs,
                        null);
        if (cursor != null && cursor.moveToFirst()) {
            int index = cursor.getColumnIndexOrThrow("_data");
            String var9 = cursor.getString(index);
            return var9;
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }

    }

    return null;
}
 
Example 15
Source File: DesktopHostsActivity.java    From deskcon-android with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unused")
private void testreaddb() {
	Cursor cursor = dbhelper.getHostsOnWifiCursor("<unknown ssid>");
	System.out.println(cursor.getCount());

       if (cursor.moveToFirst()) {
           do {                
               System.out.println(cursor.getLong(0));
               System.out.println(cursor.getString(2));
               System.out.println(cursor.getInt(3));
               //System.out.println(cursor.getString(6));
           } while (cursor.moveToNext());
       }
}
 
Example 16
Source File: DynamicSongQuery.java    From Android-Remote with GNU General Public License v3.0 5 votes vote down vote up
private int countItems(String[] selection) {
    int items = 0;

    StringBuilder query = new StringBuilder();
    query.append("SELECT ");
    query.append(" COUNT(DISTINCT(");
    query.append(mSelectedFields[selection.length]);
    query.append("))");

    query.append(" FROM ");
    query.append(getTable());

    String hiddenWhere = getHiddenWhere();
    if (selection.length > 0) {
        query.append(" WHERE ");
        for (int i = 0; i < selection.length; i++) {
            query.append(mSelectedFields[i]);
            query.append(" = ? ");
            if (i < selection.length - 1)
                query.append(" and ");
        }
        if (!hiddenWhere.isEmpty()) {
            query.append(" and ");
            query.append(hiddenWhere);
        }
    } else if (!hiddenWhere.isEmpty()) {
        query.append(" WHERE ");
        query.append(hiddenWhere);
    }

    Cursor c = mDatabase.rawQuery(query.toString(), selection);

    if (c != null && c.moveToFirst()) {
        items = c.getInt(0);
        c.close();
    }

    return items;
}
 
Example 17
Source File: FileDataStorageManager.java    From Cirrus_depricated with GNU General Public License v2.0 5 votes vote down vote up
public ArrayList<OCShare> getSharesWithForAFile(String filePath, String accountName){
    // Condition
    String where = ProviderTableMeta.OCSHARES_PATH + "=?" + " AND "
            + ProviderTableMeta.OCSHARES_ACCOUNT_OWNER + "=?"+ "AND"
            + " (" + ProviderTableMeta.OCSHARES_SHARE_TYPE + "=? OR "
            + ProviderTableMeta.OCSHARES_SHARE_TYPE +  "=? ) ";
    String [] whereArgs = new String[]{ filePath, accountName ,
            Integer.toString(ShareType.USER.getValue()),
            Integer.toString(ShareType.GROUP.getValue()) };

    Cursor c = null;
    if (getContentResolver() != null) {
        c = getContentResolver().query(
                ProviderTableMeta.CONTENT_URI_SHARE,
                null, where, whereArgs, null);
    } else {
        try {
            c = getContentProviderClient().query(
                    ProviderTableMeta.CONTENT_URI_SHARE,
                    null, where, whereArgs, null);

        } catch (RemoteException e) {
            Log_OC.e(TAG, "Could not get list of shares with: " + e.getMessage());
            c = null;
        }
    }
    ArrayList<OCShare> shares = new ArrayList<OCShare>();
    OCShare share = null;
    if (c.moveToFirst()) {
        do {
            share = createShareInstance(c);
            shares.add(share);
            // }
        } while (c.moveToNext());
    }
    c.close();

    return shares;
}
 
Example 18
Source File: TaskerIntent.java    From beaconloc with Apache License 2.0 4 votes vote down vote up
private static boolean prefSet(Context context, String col) {

		String[] proj = new String[] { col };

		Cursor c = context.getContentResolver().query(Uri.parse(TASKER_PREFS_URI), proj, null, null, null);

		boolean acceptingFlag = false;

		if (c == null)
			Log.w(TAG, "no cursor for " + TASKER_PREFS_URI);
		else {
			c.moveToFirst();

			if (Boolean.TRUE.toString().equals(c.getString(0)))
				acceptingFlag = true;

			c.close();
		}

		return acceptingFlag;
	}
 
Example 19
Source File: SmsMessageReceiver.java    From codeexamples-android with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    Bundle extras = intent.getExtras();
    if (extras == null)
        return;

    Object[] pdus = (Object[]) extras.get("pdus");

    for (int i = 0; i < pdus.length; i++) {
        SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[i]);
        String fromAddress = message.getOriginatingAddress();
        String fromDisplayName = fromAddress;

        Uri uri;
        String[] projection;

        // If targeting Donut or below, use
        // Contacts.Phones.CONTENT_FILTER_URL and
        // Contacts.Phones.DISPLAY_NAME
        uri = Uri.withAppendedPath(
                ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                Uri.encode(fromAddress));
        projection = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME };

        // Query the filter URI
        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst())
                fromDisplayName = cursor.getString(0);

            cursor.close();
        }

        // Trigger the main activity to fire up a dialog that shows/reads the received messages
        Intent di = new Intent();
        di.setClass(context, SmsReceivedDialog.class);
        di.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        di.putExtra(SmsReceivedDialog.SMS_FROM_ADDRESS_EXTRA, fromAddress);
        di.putExtra(SmsReceivedDialog.SMS_FROM_DISPLAY_NAME_EXTRA, fromDisplayName);
        di.putExtra(SmsReceivedDialog.SMS_MESSAGE_EXTRA, message.getMessageBody().toString());
        context.startActivity(di);

        // For the purposes of this demo, we'll only handle the first received message.
        break;
    }
}
 
Example 20
Source File: MetadataDbHelper.java    From Indic-Keyboard with Apache License 2.0 4 votes vote down vote up
/**
 * Marks a downloading entry as having successfully downloaded and being installed.
 *
 * The metadata database contains information about ongoing processes, typically ongoing
 * downloads. This marks such an entry as having finished and having installed successfully,
 * so it becomes INSTALLED.
 *
 * @param db the metadata database.
 * @param r content values about the entry to mark as processed.
 */
public static void markEntryAsFinishedDownloadingAndInstalled(final SQLiteDatabase db,
        final ContentValues r) {
    switch (r.getAsInteger(TYPE_COLUMN)) {
        case TYPE_BULK:
            DebugLogUtils.l("Ended processing a wordlist");
            // Updating a bulk word list is a three-step operation:
            // - Add the new entry to the table
            // - Remove the old entry from the table
            // - Erase the old file
            // We start by gathering the names of the files we should delete.
            final List<String> filenames = new LinkedList<>();
            final Cursor c = db.query(METADATA_TABLE_NAME,
                    new String[] { LOCAL_FILENAME_COLUMN },
                    LOCALE_COLUMN + " = ? AND " +
                    WORDLISTID_COLUMN + " = ? AND " + STATUS_COLUMN + " = ?",
                    new String[] { r.getAsString(LOCALE_COLUMN),
                            r.getAsString(WORDLISTID_COLUMN),
                            Integer.toString(STATUS_INSTALLED) },
                    null, null, null);
            try {
                if (c.moveToFirst()) {
                    // There should never be more than one file, but if there are, it's a bug
                    // and we should remove them all. I think it might happen if the power of
                    // the phone is suddenly cut during an update.
                    final int filenameIndex = c.getColumnIndex(LOCAL_FILENAME_COLUMN);
                    do {
                        DebugLogUtils.l("Setting for removal", c.getString(filenameIndex));
                        filenames.add(c.getString(filenameIndex));
                    } while (c.moveToNext());
                }
            } finally {
                c.close();
            }
            r.put(STATUS_COLUMN, STATUS_INSTALLED);
            db.beginTransactionNonExclusive();
            // Delete all old entries. There should never be any stalled entries, but if
            // there are, this deletes them.
            db.delete(METADATA_TABLE_NAME,
                    WORDLISTID_COLUMN + " = ?",
                    new String[] { r.getAsString(WORDLISTID_COLUMN) });
            db.insert(METADATA_TABLE_NAME, null, r);
            db.setTransactionSuccessful();
            db.endTransaction();
            for (String filename : filenames) {
                try {
                    final File f = new File(filename);
                    f.delete();
                } catch (SecurityException e) {
                    // No permissions to delete. Um. Can't do anything.
                } // I don't think anything else can be thrown
            }
            break;
        default:
            // Unknown type: do nothing.
            break;
    }
 }