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

The following are Jave code examples for showing how to use moveToFirst() 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: Protestr   File: DetentionAlertPresenterImpl.java   Source Code and License Vote up 7 votes
@Override
public void onContactRetrieved(Cursor contactInfoCursor) {
    contactInfoCursor.moveToFirst();
    try {
        final String displayName = contactInfoCursor.getString(contactInfoCursor.getColumnIndex
                (ContactsContract.Contacts.DISPLAY_NAME));
        final String phoneNumber = contactInfoCursor.getString(contactInfoCursor.getColumnIndex
                (ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("[-() ]", "");

        Prefs.with((DetentionAlertActivity) detentionAlertView).write(
                PreferencesUtils.PREFERENCES_SELECTED_CONTACT_NAME, displayName
        );
        Prefs.with((DetentionAlertActivity) detentionAlertView).write(
                PreferencesUtils.PREFERENCES_SELECTED_CONTACT_NUMBER, phoneNumber
        );

        detentionAlertView.contactSelected(displayName);
    } catch (Exception e) {
        e.printStackTrace();
        detentionAlertView.contactError();
    } finally {
        contactInfoCursor.close();
    }
}
 
Example 2
Project: Divertio   File: ImportSongDialog.java   Source Code and License Vote up 6 votes
private static String getCoverArtPath(long albumId, Context context) {
    Cursor albumCursor = context.getContentResolver().query(
            MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
            new String[]{MediaStore.Audio.Albums.ALBUM_ART},
            MediaStore.Audio.Albums._ID + " = ?",
            new String[]{Long.toString(albumId)},
            null
    );
    boolean queryResult = albumCursor.moveToFirst();
    String result = null;
    if (queryResult) {
        result = albumCursor.getString(0);
    }
    albumCursor.close();
    return result;
}
 
Example 3
Project: XiaoTianQi   File: CoolWeatherDao.java   Source Code and License Vote up 6 votes
public List<Province> loadProvinces() {
    List<Province> provinceList = new ArrayList<>();
    Cursor cursor = db.query("province", null, null, null, null, null, null);
    if (cursor.moveToFirst()) {
        do {
            Province province = new Province();
            province.setId(cursor.getInt(cursor.getColumnIndex("id")));
            province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name")));
            province.setProvinceCode(cursor.getString(cursor.getColumnIndex("province_code")));
            provinceList.add(province);
        } while (cursor.moveToNext());
    }
    if (cursor != null) {
        cursor.close();
    }
    return provinceList;
}
 
Example 4
Project: Pluto-Android   File: PhotoUtil.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 index = cursor.getColumnIndexOrThrow(column);  
            return cursor.getString(index);  
        }  
    } finally {  
        if (cursor != null)  
            cursor.close();  
    }  
    return null;  
}
 
Example 5
Project: Nimbus   File: DbHelper.java   Source Code and License Vote up 5 votes
public List gethomedata() {

        Log.d("TAGGGGG", "insideeeeeee gethomedata");
        List<HomePostsModel> homedetails = new ArrayList<>();
        String query = "select * from " + TABLE_HOMEPOST;
        SQLiteDatabase db = getReadableDatabase();
        mdb = getReadableDatabase();
        Cursor cursor = db.rawQuery(query, null);
        Log.d("LOG", "cursorr" + cursor.toString());
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    do {
                        HomePostsModel homeposts = new HomePostsModel();
                        String id = cursor.getString(cursor.getColumnIndex(NOTIFICATION_ID));
                        String title = cursor.getString(cursor.getColumnIndex(NOTIFICATION_TITLE));
                        String small_icon = cursor.getString(cursor.getColumnIndex(NOTIFICATION_small_icon));

                        Log.d("TAG", "valuesss" +id+title+small_icon);
                        homeposts.setNotification_id(id);
                        homeposts.setTitle(title);
                        homeposts.setSmall_icon(small_icon);
                        homedetails.add(homeposts);
                    } while (cursor.moveToNext());

                    for (int i = 0; i < homedetails.size(); i++) {
                        Log.d("LOG", "arrryyyy" + homedetails.get(i).toString());
                    }
                    cursor.close();
                }
            } catch (Exception e) {
                Log.d("TAG", "Error while trying to get posts from database");
            }

        } else {
            Log.d("DB", "cursor emptyyyy");
        }

        return homedetails;
    }
 
Example 6
Project: Guanajoven   File: RegistrarFragment.java   Source Code and License Vote up 5 votes
/**
 * FunciĆ³n que obtiene el path de un bitmap para cargarlo en el imageView.
 *
 * @param uri
 * @param activity
 * @return
 */
public String getPath(Uri uri, Activity activity) {
    String[] projection = {MediaStore.MediaColumns.DATA};
    Cursor cursor = activity
            .managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}
 
Example 7
Project: ObjectBoxDebugBrowser   File: ContactDBHelper.java   Source Code and License Vote up 5 votes
public int count() {
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.rawQuery("select * from contacts", null);
    if (cursor != null && cursor.getCount() > 0) {
        cursor.moveToFirst();
        return cursor.getInt(0);
    } else {
        return 0;
    }
}
 
Example 8
Project: downloader   File: SubTaskRecordDAO.java   Source Code and License Vote up 5 votes
public long querySumByTaskId(long taskId) {
    SQLiteDatabase db = RecordManager.openDatabase();
    String sql = "select sum("+SqlConst.TB_THREAD_FINISHED+") from "+ TABLE_NAME +" where "+SqlConst.TB_TASK_ID+"=?";
    String[] whereArgs = {String.valueOf(taskId)};
    Cursor cursor = db.rawQuery(sql,whereArgs);
    SubTaskRecord record = null;
    long sum = 0;
    if (cursor.moveToFirst()) {
        sum = cursor.getLong(0);
    }
    cursor.close();
    return sum;
}
 
Example 9
Project: BitcoinBlockExplorer   File: BlocksDataSource.java   Source Code and License Vote up 5 votes
public List<DBBlock> getAll() {
    List<DBBlock> dbblocks = new ArrayList<DBBlock>();
    Cursor cursor = database.query(MySQLiteHelper.TABLE_BLOCKSTORE, allColumns, null, null, null, null, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        dbblocks.add(cursorToBlock(cursor));
        cursor.moveToNext();
    }
    // make sure to close the cursor
    cursor.close();
    return dbblocks;
}
 
Example 10
Project: QuranAndroid   File: DatabaseAccess.java   Source Code and License Vote up 5 votes
/**
 * Function to get the part start page
 *
 * @param partNumber Part Number
 * @return Page number
 */
public int getPartStartPage(int partNumber) {
    int pageNumber = 0;
    SQLiteDatabase db = openDB(MAIN_DATABASE);
    String sql = "select page from aya where joza = " + partNumber + " limit 1 ;";
    Cursor cursor = db.rawQuery(sql, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        pageNumber = cursor.getInt(0);
        cursor.moveToNext();
    }
    cursor.close();
    closeDB(db);
    return pageNumber;
}
 
Example 11
Project: Sanxing   File: TaskRepo.java   Source Code and License Vote up 5 votes
public Long getCount(){

        String sql = "select count(*) from "+Task.TABLE;
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery(sql, null);
        cursor.moveToFirst();
        long count = cursor.getLong(0);
        cursor.close();
        return count;

    }
 
Example 12
Project: Huochexing12306   File: MyCookieDBManager.java   Source Code and License Vote up 5 votes
public List<Cookie> getAllCookies() {
	List<Cookie> cookies = new ArrayList<Cookie>();

	Cursor cursor = db
			.query(TABLE_NAME, null, null, null, null, null, null);

	for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
		String name = cursor.getString(cursor.getColumnIndex(Column.NAME));
		String value = cursor
				.getString(cursor.getColumnIndex(Column.VALUE));

		BasicClientCookie cookie = new BasicClientCookie(name, value);

		cookie.setComment(cursor.getString(cursor
				.getColumnIndex(Column.COMMENT)));
		cookie.setDomain(cursor.getString(cursor
				.getColumnIndex(Column.DOMAIN)));
		long expireTime = cursor.getLong(cursor
				.getColumnIndex(Column.EXPIRY_DATE));
		if (expireTime != 0) {
			cookie.setExpiryDate(new Date(expireTime));
		}
		cookie.setPath(cursor.getString(cursor.getColumnIndex(Column.PATH)));
		cookie.setSecure(cursor.getInt(cursor.getColumnIndex(Column.SECURE)) == 1);
		cookie.setVersion(cursor.getInt(cursor
				.getColumnIndex(Column.VERSION)));

		cookies.add(cookie);
	}

	cursor.close();

	return cookies;
}
 
Example 13
Project: an2linuxclient   File: ServerDatabaseHandler.java   Source Code and License Vote up 5 votes
public WifiServer getWifiServer(long id){
    SQLiteDatabase db = this.getReadableDatabase();

    WifiServer wifiServer = new WifiServer();
    wifiServer.setId(id);

    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    qb.setTables(TABLE_SERVERS +
            " JOIN " + TABLE_WIFI_SERVERS +
            " USING(" + COLUMN_ID + ")");

    Cursor c = qb.query(db,
            new String[]{COLUMN_IS_ENABLED,
                    COLUMN_CERTIFICATE_ID,
                    COLUMN_IP_OR_HOSTNAME,
                    COLUMN_PORT_NUMBER,
                    COLUMN_SSID_WHITELIST},
            COLUMN_ID + "=?", new String[]{String.valueOf(id)},
            null, null, null);

    if (c.moveToFirst()){
        wifiServer.setIsEnabled(intToBool(c.getInt(0)));
        wifiServer.setCertificateId(c.getLong(1));
        wifiServer.setIpOrHostname(c.getString(2));
        wifiServer.setPortNumber(c.getInt(3));
        wifiServer.setSsidWhitelist(c.getString(4));
    }

    c.close();
    db.close();
    return wifiServer;
}
 
Example 14
Project: AndiCar   File: MainActivity.java   Source Code and License Vote up 5 votes
private void setSelectedCar(long id, boolean needCallRun) {
    SharedPreferences.Editor editor = mPreferences.edit();
    editor.putLong(AndiCar.getAppResources().getString(R.string.pref_key_last_selected_car_id), id);
    editor.apply();

    mLastSelectedCarID = id;

    //get the car details
    String columnsToGet[] = {DBAdapter.COL_NAME_GEN_ROWID, DBAdapter.COL_NAME_GEN_NAME, DBAdapter.COL_NAME_GEN_USER_COMMENT,
            DBAdapter.COL_NAME_CAR__REGISTRATIONNO, DBAdapter.COL_NAME_CAR__INDEXCURRENT};

    String selectionCondition = DBAdapter.COL_NAME_GEN_ROWID + "=?";
    String[] selectionArgs = {String.valueOf(id)};
    DBAdapter db = new DBAdapter(this);
    Cursor c = db.query(DBAdapter.TABLE_NAME_CAR, columnsToGet, selectionCondition, selectionArgs, DBAdapter.COL_NAME_GEN_NAME);
    if (c.moveToFirst()) {
        mNavigationView.setHeaderLabels(c.getString(1), c.getString(3), c.getString(2));
        setTitle(c.getString(1) + " - " +
                Utils.numberToString(c.getDouble(4), true, 0, RoundingMode.HALF_UP) + " " + db.getUOMCode(db.getCarUOMLengthID(c.getLong(0))));
    }
    else {
        mNavigationView.setHeaderLabels(getString(R.string.main_activity_no_car_title), "", "");
        setTitle(getString(R.string.main_activity_no_car_title));
    }
    c.close();

    mIsAlternateFuelVehicle = db.isAFVCar(mLastSelectedCarID);
    db.close();

    if (needCallRun) {
        fillContent();
    }
}
 
Example 15
Project: APIJSON-Android-RxJava   File: CityDB.java   Source Code and License Vote up 5 votes
private City getCityInfo(String city) {
    Cursor c = db.rawQuery("SELECT * from " + CITY_TABLE_NAME
            + " where city=?", new String[]{city});
    if (c.moveToFirst()) {
        String province = c.getString(c.getColumnIndex("province"));
        String name = c.getString(c.getColumnIndex("city"));
        Double latitude = c.getDouble(c.getColumnIndex("latitude"));
        Double longitude = c.getDouble(c.getColumnIndex("longitude"));

        City item = new City(province, name, latitude, longitude);
        return item;
    }
    return null;
}
 
Example 16
Project: AOSP-Kayboard-7.1.2   File: MetadataDbHelper.java   Source Code and License Vote up 5 votes
/**
 * Returns the metadata URI as a string.
 *
 * If the client is not known, this will return null. If it is known, it will return
 * the URI as a string. Note that the empty string is a valid value.
 *
 * @param context a context instance to open the database on
 * @param clientId the ID of the client we want the metadata URI of
 * @return the string representation of the URI
 */
public static String getMetadataUriAsString(final Context context, final String clientId) {
    SQLiteDatabase defaultDb = MetadataDbHelper.getDb(context, null);
    final Cursor cursor = defaultDb.query(MetadataDbHelper.CLIENT_TABLE_NAME,
            new String[] { MetadataDbHelper.CLIENT_METADATA_URI_COLUMN },
            MetadataDbHelper.CLIENT_CLIENT_ID_COLUMN + " = ?", new String[] { clientId },
            null, null, null, null);
    try {
        if (!cursor.moveToFirst()) return null;
        return sMetadataUriGetter.getUri(context, cursor.getString(0));
    } finally {
        cursor.close();
    }
}
 
Example 17
Project: Bee-Analyzer   File: MapsActivity.java   Source Code and License Vote up 4 votes
public void onLocationChanged(Location location)
{
    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    LatLng newLocation = new LatLng(latitude, longitude);

    String out = "0";

    String selectQuery = "SELECT imei,latitude,longitude,datetime(timestamp,'localtime') as currentTime, out FROM position ORDER BY currentTime LIMIT 1";
    Cursor cursor = localdb.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) //If there is any location info before
    {
        HashMap<String, String> lastLocation = new HashMap<String, String>();
        for(int i=0; i<cursor.getColumnCount();i++)
            lastLocation.put(cursor.getColumnName(i), cursor.getString(i));

        //If Last location is out of activation area
        if(lastLocation.get("out") == "1")
        {
            //if (true)
            if (PolyUtil.containsLocation(newLocation,ituArea.getPoints(),true))
                Insertion(newLocation, out);
        }
        //If distance greater or equal to 20 meter between last location and new location
        //else if(true)
        else if(getDistance(newLocation, new LatLng(Double.parseDouble(lastLocation.get("latitude")),Double.parseDouble(lastLocation.get("longitude")))) >= 20)
        {
            //if(false)
            if (!PolyUtil.containsLocation(newLocation,ituArea.getPoints(),true))
                out = "1";
            Insertion(newLocation,out);
        }
    }
    else // First location info
    {
        //if (true)
        if (PolyUtil.containsLocation(newLocation,ituArea.getPoints(),true))
            Insertion(newLocation,out);
    }
}
 
Example 18
Project: hyperrail-for-android   File: StationsDb.java   Source Code and License Vote up 4 votes
/**
 * Load stations from a cursor. This method <strong>does not close the cursor afterwards</strong>.
 *
 * @param c The cursor from which stations should be loaded.
 * @return The array of loaded stations
 */
private Station[] loadStationCursor(Cursor c) {
    if (c.isClosed()) {
        FirebaseCrash.logcat(SEVERE.intValue(), LOGTAG, "Tried to load closed cursor");
        return null;
    }

    if (c.getCount() == 0) {
        FirebaseCrash.logcat(SEVERE.intValue(), LOGTAG, "Tried to load cursor with 0 results!");
        return null;
    }

    c.moveToFirst();
    Station[] result = new Station[c.getCount()];
    int i = 0;
    while (!c.isAfterLast()) {

        String locale = PreferenceManager.getDefaultSharedPreferences(context).getString("pref_stations_language", "");
        if (locale.isEmpty()) {
            // Only get locale when needed
            locale = Locale.getDefault().getISO3Language();
            PreferenceManager.getDefaultSharedPreferences(context).edit().putString("pref_stations_language", locale).apply();
        }

        String name = c.getString(c.getColumnIndex(StationsDataColumns.COLUMN_NAME_NAME));
        String localizedName = null;

        String nl = c.getString(c.getColumnIndex(StationsDataColumns.COLUMN_NAME_ALTERNATIVE_NL));
        String fr = c.getString(c.getColumnIndex(StationsDataColumns.COLUMN_NAME_ALTERNATIVE_FR));
        String de = c.getString(c.getColumnIndex(StationsDataColumns.COLUMN_NAME_ALTERNATIVE_DE));
        String en = c.getString(c.getColumnIndex(StationsDataColumns.COLUMN_NAME_ALTERNATIVE_EN));

        switch (locale) {
            case "nld":
                localizedName = nl;
                break;
            case "fra":
                localizedName = fr;
                break;
            case "deu":
                localizedName = de;
                break;
            case "eng":
                localizedName = en;
                break;
        }

        if (localizedName == null || localizedName.isEmpty()) {
            localizedName = name;
        }

        Station s = new Station(
                c.getString(c.getColumnIndex(StationsDataColumns._ID)),
                name,
                nl,
                fr,
                de,
                en,
                localizedName,
                c.getString(c.getColumnIndex(StationsDataColumns.COLUMN_NAME_COUNTRY_CODE)),
                c.getDouble(c.getColumnIndex(StationsDataColumns.COLUMN_NAME_LATITUDE)),
                c.getDouble(c.getColumnIndex(StationsDataColumns.COLUMN_NAME_LONGITUDE)),
                c.getFloat(c.getColumnIndex(StationsDataColumns.COLUMN_NAME_AVG_STOP_TIMES)));

        c.moveToNext();
        result[i] = s;
        i++;
    }
    return result;
}
 
Example 19
Project: MusicX-music-player   File: PlaylistLoader.java   Source Code and License Vote up 4 votes
@Override
public List<Song> loadInBackground() {
    List<Song> playlist = new ArrayList<>();
    String sortorder = MediaStore.Audio.Playlists.Members.PLAY_ORDER;
    if (mPlaylistId == 0) {
        return null;
    }
    if (PermissionChecker.checkCallingOrSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) == PermissionChecker.PERMISSION_GRANTED) {
        Cursor cursor = getContext().getContentResolver().query(MediaStore.Audio.Playlists.Members.getContentUri("external", mPlaylistId), sProjection, "", null, sortorder);
        if (cursor != null && cursor.moveToFirst()) {
            int idCol = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID);
            if (idCol == -1) {
                idCol = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members._ID);
            }
            int titleCol = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.TITLE);
            int artistCol = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.ARTIST);
            int albumCol = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.ALBUM);
            int albumIdCol = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.ALBUM_ID);
            int trackCol = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.TRACK);
            int datacol = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.DATA);
            do {
                long id = cursor.getLong(idCol);
                String title = cursor.getString(titleCol);
                String artist = cursor.getString(artistCol);
                String album = cursor.getString(albumCol);
                long albumId = cursor.getLong(albumIdCol);
                int track = cursor.getInt(trackCol);
                String mSongPath = cursor.getString(datacol);
                Song song = new Song();
                /*
                 Setup metadata of playlist
                */
                song.setAlbum(album);
                song.setmSongPath(mSongPath);
                song.setArtist(artist);
                song.setId(id);
                song.setAlbumId(albumId);
                song.setTrackNumber(track);
                song.setTitle(title);
                playlist.add(song);
            } while (cursor.moveToNext());
            cursor.close();
        }
        if (cursor == null) {
            Collections.emptyList();
        }
        return playlist;
    } else {
        return null;
    }
}
 
Example 20
Project: kognitivo   File: AttributionIdentifiers.java   Source Code and License Vote up 4 votes
public static AttributionIdentifiers getAttributionIdentifiers(Context context) {
    if (recentlyFetchedIdentifiers != null &&
        System.currentTimeMillis() - recentlyFetchedIdentifiers.fetchTime <
                IDENTIFIER_REFRESH_INTERVAL_MILLIS) {
        return recentlyFetchedIdentifiers;
    }

    AttributionIdentifiers identifiers = getAndroidId(context);
    Cursor c = null;
    try {
        String [] projection = {
                ATTRIBUTION_ID_COLUMN_NAME,
                ANDROID_ID_COLUMN_NAME,
                LIMIT_TRACKING_COLUMN_NAME};
        Uri providerUri = null;
        if (context.getPackageManager().resolveContentProvider(
                ATTRIBUTION_ID_CONTENT_PROVIDER, 0) != null) {
            providerUri = Uri.parse("content://" + ATTRIBUTION_ID_CONTENT_PROVIDER);
        } else if (context.getPackageManager().resolveContentProvider(
                ATTRIBUTION_ID_CONTENT_PROVIDER_WAKIZASHI, 0) != null) {
            providerUri = Uri.parse("content://" + ATTRIBUTION_ID_CONTENT_PROVIDER_WAKIZASHI);
        }
        String installerPackageName = getInstallerPackageName(context);
        if (installerPackageName != null) {
            identifiers.androidInstallerPackage = installerPackageName;
        }
        if (providerUri == null) {
            return cacheAndReturnIdentifiers(identifiers);
        }
        c = context.getContentResolver().query(providerUri, projection, null, null, null);
        if (c == null || !c.moveToFirst()) {
            return cacheAndReturnIdentifiers(identifiers);
        }
        int attributionColumnIndex = c.getColumnIndex(ATTRIBUTION_ID_COLUMN_NAME);
        int androidIdColumnIndex = c.getColumnIndex(ANDROID_ID_COLUMN_NAME);
        int limitTrackingColumnIndex = c.getColumnIndex(LIMIT_TRACKING_COLUMN_NAME);

        identifiers.attributionId = c.getString(attributionColumnIndex);

        // if we failed to call Google's APIs directly (due to improper integration by the
        // client), it may be possible for the local facebook application to relay it to us.
        if (androidIdColumnIndex > 0 && limitTrackingColumnIndex > 0 &&
                identifiers.getAndroidAdvertiserId() == null) {
            identifiers.androidAdvertiserId = c.getString(androidIdColumnIndex);
            identifiers.limitTracking =
                    Boolean.parseBoolean(c.getString(limitTrackingColumnIndex));
        }
    } catch (Exception e) {
        Log.d(TAG, "Caught unexpected exception in getAttributionId(): " + e.toString());
        return null;
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return cacheAndReturnIdentifiers(identifiers);
}