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

The following examples show how to use android.database.Cursor#isAfterLast() . 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: DatabaseHelper.java    From AndroidDemo with MIT License 6 votes vote down vote up
public static Response getAllTableName(SQLiteDatabase database) {
    Response response = new Response();
    Cursor c = database.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
    if (c.moveToFirst()) {
        while (!c.isAfterLast()) {
            response.rows.add(c.getString(0));
            c.moveToNext();
        }
    }
    c.close();
    response.isSuccessful = true;
    try {
        response.dbVersion = database.getVersion();
    } catch (Exception ignore) {

    }
    return response;
}
 
Example 2
Source File: Database.java    From MuslimMateAndroid with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Function to check if country is islamic or not
 *
 * @return Flag islamic or not
 */
public Boolean isIslamicCountry(String code) {
    try {
        SQLiteDatabase db = openDB();
        String sql = "select islamic from countries where Code = '" + code + "'";
        Cursor cursor = db.rawQuery(sql, null);
        cursor.moveToFirst();
        int type = 0;
        while (!cursor.isAfterLast()) {
            type = cursor.getInt(0);
            cursor.moveToNext();
        }
        cursor.close();
        closeDB(db);
        return type == 1 ? true : false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 3
Source File: Dbhandler.java    From CameraBlur with Apache License 2.0 6 votes vote down vote up
public entry getresult(int x){

        entry e=new entry();
        SQLiteDatabase db = getWritableDatabase();
        String query="SELECT * FROM "+TABLE_NAME+" WHERE "+ID+"="+x+";";
        Cursor c=db.rawQuery(query,null);
        c.moveToFirst();
        if(!c.isAfterLast())
        {
            if(c.getString(c.getColumnIndex(ID))!=null)
                e.set_id(c.getInt(c.getColumnIndex(ID)));
            if(c.getString(c.getColumnIndex(COLUMN1_NAME_TITLE_TABLE1))!=null)
                e.setPath(c.getString(c.getColumnIndex(COLUMN1_NAME_TITLE_TABLE1)));
            if(c.getString(c.getColumnIndex(COLUMN2_NAME_TITLE_TABLE1))!=null)
                e.setMap(c.getString(c.getColumnIndex(COLUMN2_NAME_TITLE_TABLE1)));
        }

        c.close();
        return e;
    }
 
Example 4
Source File: UserBinaryDictionary.java    From AOSP-Kayboard-7.1.2 with Apache License 2.0 6 votes vote down vote up
private void addWordsLocked(final Cursor cursor) {
    if (cursor == null) return;
    if (cursor.moveToFirst()) {
        final int indexWord = cursor.getColumnIndex(Words.WORD);
        final int indexFrequency = cursor.getColumnIndex(Words.FREQUENCY);
        while (!cursor.isAfterLast()) {
            final String word = cursor.getString(indexWord);
            final int frequency = cursor.getInt(indexFrequency);
            final int adjustedFrequency = scaleFrequencyFromDefaultToLatinIme(frequency);
            // Safeguard against adding really long words.
            if (word.length() <= MAX_WORD_LENGTH) {
                runGCIfRequiredLocked(true /* mindsBlockByGC */);
                addUnigramLocked(word, adjustedFrequency, false /* isNotAWord */,
                        false /* isPossiblyOffensive */,
                        BinaryDictionary.NOT_A_VALID_TIMESTAMP);
            }
            cursor.moveToNext();
        }
    }
}
 
Example 5
Source File: DatabaseAccess.java    From QuranAndroid with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Function to get all ayat of page
 *
 * @param page Page number
 * @return List of ayat
 */
public List<Aya> getPageAyat(int page) {
    List<Aya> pageAyat = new ArrayList<Aya>();
    SQLiteDatabase db = openDB(MAIN_DATABASE);
    String sql = "select soraid , ayaid from aya where page = " + page + " and ayaid  is not 0  order by soraid,ayaid ;";
    Cursor cursor = db.rawQuery(sql, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        pageAyat.add(new Aya(page,
                cursor.getInt(0),
                cursor.getInt(1)));
        cursor.moveToNext();
    }
    cursor.close();
    closeDB(db);
    return pageAyat;

}
 
Example 6
Source File: StorageHelper.java    From leafpicrevived with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get an Uri from an file path.
 *
 * @param path The file path.
 * @return The Uri.
 */
private static Uri getUriFromFile(Context context, final String path) {
    ContentResolver resolver = context.getContentResolver();

    Cursor filecursor = resolver.query(MediaStore.Files.getContentUri("external"),
            new String[]{BaseColumns._ID}, MediaStore.MediaColumns.DATA + " = ?",
            new String[]{path}, MediaStore.MediaColumns.DATE_ADDED + " desc");
    if (filecursor == null) {
        return null;
    }
    filecursor.moveToFirst();

    if (filecursor.isAfterLast()) {
        filecursor.close();
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, path);
        return resolver.insert(MediaStore.Files.getContentUri("external"), values);
    } else {
        int imageId = filecursor.getInt(filecursor.getColumnIndex(BaseColumns._ID));
        Uri uri = MediaStore.Files.getContentUri("external").buildUpon().appendPath(
                Integer.toString(imageId)).build();
        filecursor.close();
        return uri;
    }
}
 
Example 7
Source File: RenamePlayListDialog.java    From Rey-MusicPlayer with Apache License 2.0 6 votes vote down vote up
private String nameForId(long id) {
    Cursor c = MusicUtils.query(mApp.getApplicationContext(), MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
            new String[]{MediaStore.Audio.Playlists.NAME},
            MediaStore.Audio.Playlists._ID + "=?",
            new String[]{Long.valueOf(id).toString()},
            MediaStore.Audio.Playlists.NAME);
    String name = null;
    if (c != null) {
        c.moveToFirst();
        if (!c.isAfterLast()) {
            name = c.getString(0);
        }
    }
    c.close();
    return name;
}
 
Example 8
Source File: DataBaseHelper.java    From programming with GNU General Public License v3.0 6 votes vote down vote up
public String databasetostring(){
    String dbstring="";
    SQLiteDatabase db = getWritableDatabase();
    //String query = "SELECT * FROM" + TABLE_TASKS +"WHERE 1";
    String query = "SELECT * FROM " + TABLE_TASKS + " WHERE 1";
    Cursor c = db.rawQuery(query, null);
    c.moveToFirst();
    while (!c.isAfterLast()){
        if(c.getString(c.getColumnIndex("taskname")) != null){
            dbstring += c.getString(c.getColumnIndex("taskname"));
            dbstring += "\n";
        }
        c.moveToNext();
    }
    db.close();
    return dbstring;
}
 
Example 9
Source File: DatabaseExporter.java    From privacy-friendly-interval-timer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return a list of all table names, including android_metadata and sqlite_sequence (table that
 * contains current maximal ID of all tables)
 */
public ArrayList<String> getTableNames() {

    SQLiteDatabase dataBase = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READONLY);
    ArrayList<String> arrTblNames = new ArrayList<String>();
    Cursor c = dataBase.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);

    if (c.moveToFirst()) {
        while (!c.isAfterLast()) {
            arrTblNames.add(c.getString(c.getColumnIndex("name")));
            c.moveToNext();
        }
    }
    return arrTblNames;
}
 
Example 10
Source File: SearchDatabase.java    From EhViewer with Apache License 2.0 5 votes vote down vote up
public String[] getSuggestions(String prefix, int limit) {
    List<String> queryList = new LinkedList<>();
    limit = Math.max(0, limit);

    StringBuilder sb = new StringBuilder();
    sb.append("SELECT * FROM ").append(TABLE_SUGGESTIONS);
    if (!TextUtils.isEmpty(prefix)) {
        sb.append(" WHERE ").append(COLUMN_QUERY).append(" LIKE '")
                .append(SqlUtils.sqlEscapeString(prefix)).append("%'");
    }
    sb.append(" ORDER BY ").append(COLUMN_DATE).append(" DESC")
        .append(" LIMIT ").append(limit);

    try {
        Cursor cursor = mDatabase.rawQuery(sb.toString(), null);
        int queryIndex = cursor.getColumnIndex(COLUMN_QUERY);
        if (cursor.moveToFirst()) {
            while (!cursor.isAfterLast()) {
                String suggestion = cursor.getString(queryIndex);
                if (!prefix.equals(suggestion)) {
                    queryList.add(suggestion);
                }
                cursor.moveToNext();
            }
        }
        cursor.close();
        return queryList.toArray(new String[queryList.size()]);
    } catch (SQLException e) {
        return new String[0];
    }
}
 
Example 11
Source File: TagORM.java    From kylewbanks.com-AndroidApp with The Unlicense 5 votes vote down vote up
/**
 * Gets a list of all cached Tags associated with the specified Post
 * @param context
 * @param post
 * @return
 */
public static final List<Tag> getTagsForPost(Context context, Post post) {
    DatabaseWrapper databaseWrapper = new DatabaseWrapper(context);
    SQLiteDatabase database = databaseWrapper.getReadableDatabase();

    List<Tag> tagList = null;

    if (database != null) {
        Cursor cursor = database.rawQuery(
                "SELECT * FROM " + TagORM.TABLE_NAME + " WHERE " + TagORM.COLUMN_POST_ID + " = " + post.getId() + " GROUP BY " + TagORM.COLUMN_NAME, null
        );

        Log.i(TAG, "Loaded " + cursor.getCount() + " Tags for Post["+post.getId()+"]...");
        if(cursor.getCount() > 0) {
            tagList = new ArrayList<Tag>();

            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                tagList.add(TagORM.cursorToTag(cursor));
                cursor.moveToNext();
            }
            Log.i(TAG, "Tags loaded successfully for Post["+post.getId()+"]");
        }

        database.close();
    }
    return tagList;
}
 
Example 12
Source File: MediaResourceDao.java    From BeyondUPnP with Apache License 2.0 5 votes vote down vote up
public static List<Item> getVideoList(String serverUrl, String parentId) {
    List<Item> items = new ArrayList<>();

    Cursor c = BeyondApplication.getApplication().getContentResolver()
            .query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Video.Media.TITLE);
    c.moveToFirst();
    while (!c.isAfterLast()) {
        long id = c.getLong(c.getColumnIndex(MediaStore.Audio.Media._ID));
        String title = c.getString(c.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
        String creator = c.getString(c.getColumnIndexOrThrow(MediaStore.Video.Media.ARTIST));

        String data = c.getString(c.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
        //Remove SDCard path
        data = data.replaceFirst(storageDir, "");
        //Replace file name by "id.ext"
        String fileName = data.substring(data.lastIndexOf(File.separator));
        String ext = fileName.substring(fileName.lastIndexOf("."));
        data = data.replace(fileName, File.separator + id + ext);

        String mimeType = c.getString(c.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE));
        long size = c.getLong(c.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
        long duration = c.getLong(c.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
        //Get duration string
        String durationStr = ModelUtil.toTimeString(duration);

        //Compose audio url
        String url = serverUrl + File.separator + "video" + File.separator + data;
        Res res = new Res(mimeType, size, durationStr, null, url);

        items.add(new Movie(String.valueOf(id), parentId, title, creator, res));

        c.moveToNext();
    }

    return items;
}
 
Example 13
Source File: StudentGateWay.java    From android-apps with MIT License 5 votes vote down vote up
public ArrayList<Students> getAll(String deptCode) {
	open();
	ArrayList<Students> aStudentList = new ArrayList<Students>();

	try {
		Cursor cursor = sqLiteDB.query(DBOpenHelper.TABLE_STUDENT,
				allColumns, DBOpenHelper.STUDENT_DEPT + "=" + "'"
						+ deptCode + "'", null, null, null,
				DBOpenHelper.STUDENT_REGNO);

		// Cursor cursor = sqLiteDB.query(DBOpenHelper.TABLE_STUDENT,
		// allColumns, null, null, null, null, DBOpenHelper.STUDENT_REGNO);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Students aStudent = new Students();
			aStudent.setRegNo(cursor.getString(0));
			aStudent.setStudentName(cursor.getString(1));
			aStudent.setStudentEmail(cursor.getString(2));
			aStudent.setStudentDept(cursor.getString(3));
			aStudentList.add(aStudent);
			cursor.moveToNext();
		}
		cursor.close();
	} catch (Exception e) {
	}
	close();

	return aStudentList;
}
 
Example 14
Source File: GeofenceHandler.java    From PowerSwitch_Android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets all Geofences from Database
 *
 * @return List of Geofences
 */
protected static List<Geofence> getAll() throws Exception {
    List<Geofence> geofences = new ArrayList<>();
    Cursor cursor = DatabaseHandler.database.query(GeofenceTable.TABLE_NAME, GeofenceTable.ALL_COLUMNS, null, null, null, null, null);
    cursor.moveToFirst();

    while (!cursor.isAfterLast()) {
        geofences.add(dbToGeofence(cursor));
        cursor.moveToNext();
    }
    cursor.close();
    return geofences;
}
 
Example 15
Source File: LoginActivity.java    From AndroidProjects with MIT License 5 votes vote down vote up
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
    List<String> emails = new ArrayList<>();
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        emails.add(cursor.getString(ProfileQuery.ADDRESS));
        cursor.moveToNext();
    }

    addEmailsToAutoComplete(emails);
}
 
Example 16
Source File: UpdatesAdapter.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
private void onCanUpdateLoadFinished(Cursor cursor) {
    updateableApps.clear();

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        updateableApps.add(new UpdateableApp(activity, new App(cursor)));
        cursor.moveToNext();
    }
}
 
Example 17
Source File: ChatMessageDatabase.java    From Rumble with GNU General Public License v3.0 5 votes vote down vote up
public ChatMessage getChatMessage(String uuid) {
    Cursor cursor = null;
    try {
        SQLiteDatabase database = databaseHelper.getReadableDatabase();
        cursor = database.query(TABLE_NAME, null, UUID+" = ?",new String[]{uuid}, null, null, null);
        if(cursor == null)
            return null;
        if(cursor.moveToFirst() && !cursor.isAfterLast())
            return cursorToChatMessage(cursor);
    } finally {
        if(cursor != null)
            cursor.close();
    }
    return null;
}
 
Example 18
Source File: UniversalButtonHandler.java    From PowerSwitch_Android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets all Buttons associated with a Receiver
 *
 * @param receiverId ID of Receiver
 * @return List of Buttons
 */
protected static List<UniversalButton> getUniversalButtons(Long receiverId) throws Exception {
    List<UniversalButton> buttons = new ArrayList<>();
    Cursor cursor = DatabaseHandler.database.query(UniversalButtonTable.TABLE_NAME, UniversalButtonTable.ALL_COLUMNS, UniversalButtonTable.COLUMN_RECEIVER_ID +
            "=" + receiverId, null, null, null, null);
    cursor.moveToFirst();

    while (!cursor.isAfterLast()) {
        buttons.add(dbToUniversalButton(cursor));
        cursor.moveToNext();
    }
    cursor.close();
    return buttons;
}
 
Example 19
Source File: GroupDatabase.java    From Rumble with GNU General Public License v3.0 5 votes vote down vote up
public long getGroupDBID(String group_id) {
    Cursor cursor = null;
    try {
        SQLiteDatabase database = databaseHelper.getReadableDatabase();
        cursor = database.query(TABLE_NAME, new String[] { ID }, GID+ " = ?", new String[] {group_id}, null, null, null);
        if((cursor != null) && cursor.moveToFirst() && !cursor.isAfterLast())
            return cursor.getLong(cursor.getColumnIndexOrThrow(ID));
    } finally {
        if(cursor != null)
            cursor.close();
    }
    return -1;
}
 
Example 20
Source File: RecipeActivity.java    From app-indexing with Apache License 2.0 4 votes vote down vote up
private void showRecipe(Uri recipeUri) {
    Log.d("Recipe Uri", recipeUri.toString());

    String[] projection = {RecipeTable.ID, RecipeTable.TITLE,
            RecipeTable.DESCRIPTION, RecipeTable.PHOTO,
            RecipeTable.PREP_TIME};
    Cursor cursor = getContentResolver().query(recipeUri, projection, null, null, null);
    if (cursor != null && cursor.moveToFirst()) {

        mRecipe = Recipe.fromCursor(cursor);

        Uri ingredientsUri = RecipeContentProvider.CONTENT_URI.buildUpon().appendPath
                ("ingredients").appendPath(mRecipe.getId()).build();
        Cursor ingredientsCursor = getContentResolver().query(ingredientsUri, projection,
                null, null, null);
        if (ingredientsCursor != null && ingredientsCursor.moveToFirst()) {
            do {
                Recipe.Ingredient ingredient = new Recipe.Ingredient();
                ingredient.setAmount(ingredientsCursor.getString(0));
                ingredient.setDescription(ingredientsCursor.getString(1));
                mRecipe.addIngredient(ingredient);
                ingredientsCursor.moveToNext();
            } while (!ingredientsCursor.isAfterLast());
            ingredientsCursor.close();
        }

        Uri instructionsUri = RecipeContentProvider.CONTENT_URI.buildUpon().appendPath
                ("instructions").appendPath(mRecipe.getId()).build();
        Cursor instructionsCursor = getContentResolver().query(instructionsUri, projection,
                null, null, null);
        if (instructionsCursor != null && instructionsCursor.moveToFirst()) {
            do {
                Recipe.Step step = new Recipe.Step();
                step.setDescription(instructionsCursor.getString(1));
                step.setPhoto(instructionsCursor.getString(2));
                mRecipe.addStep(step);
                instructionsCursor.moveToNext();
            } while (!instructionsCursor.isAfterLast());
            instructionsCursor.close();
        }

        Uri noteUri = RecipeContentProvider.CONTENT_URI.buildUpon().appendPath("notes")
                .appendPath(mRecipe.getId()).build();
        Cursor noteCursor = getContentResolver().query(noteUri, projection, null, null, null);
        if (noteCursor != null && noteCursor.moveToFirst()) {
            Note note = Note.fromCursor(noteCursor);
            mRecipe.setNote(note);
            noteCursor.close();
        }

        // always close the cursor
        cursor.close();
    } else {
        Toast toast = Toast.makeText(getApplicationContext(),
                "No match for deep link " + recipeUri.toString(),
                Toast.LENGTH_SHORT);
        toast.show();
    }

    if (mRecipe != null) {
        // Create the adapter that will return a fragment for each of the steps of the recipe.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // Set the recipe title
        TextView recipeTitle = (TextView) findViewById(R.id.recipeTitle);
        recipeTitle.setText(mRecipe.getTitle());

        // Set the recipe prep time
        TextView recipeTime = (TextView) findViewById(R.id.recipeTime);
        recipeTime.setText("  " + mRecipe.getPrepTime());

        //Set the note button toggle
        ToggleButton addNoteToggle = (ToggleButton) findViewById(R.id.addNoteToggle);
        addNoteToggle.setChecked(mRecipe.getNote() != null);
        addNoteToggle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mRecipe.getNote() != null) {
                    displayNoteDialog(getString(R.string.dialog_update_note), getString(R
                            .string.dialog_delete_note));
                } else {
                    displayNoteDialog(getString(R.string.dialog_add_note), getString(R.string
                            .dialog_cancel_note));
                }
            }
        });
    }
}