Example usage for android.database Cursor getCount

List of usage examples for android.database Cursor getCount

Introduction

In this page you can find the example usage for android.database Cursor getCount.

Prototype

int getCount();

Source Link

Document

Returns the numbers of rows in the cursor.

Usage

From source file:com.hybris.mobile.lib.commerce.loader.ContentAdapterLoader.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

    if (mOnRequestListener != null) {
        mOnRequestListener.afterRequestBeforeResponse();
    }//  www. ja  v a2s.  c  o  m

    boolean isDataSynced = false;

    if (data != null) {
        Log.i(TAG, "Loader finished to load " + data.getCount() + " result(s)");

        mCursorAdapter.swapCursor(data);

        if (data.getCount() > 0) {
            isDataSynced = data.getInt(data.getColumnIndex(
                    CatalogContract.DataBaseDataSimple.ATT_STATUS)) == CatalogContract.SyncStatus.UPTODATE
                            .getValue();
        }

    } else {
        isDataSynced = true;
    }

    if (mOnRequestListener != null) {
        mOnRequestListener.afterRequest(isDataSynced);
    }

}

From source file:com.acrutiapps.browser.tasks.HistoryBookmarksExportTask.java

private String writeAsJSON(Cursor... params) {
    try {//from  www . ja  v  a 2 s .  co m
        String fileName = mContext.getString(R.string.ApplicationName) + "-" + getNowForFileName() + ".json";

        File file = new File(Environment.getExternalStorageDirectory(), fileName);
        FileWriter writer = new FileWriter(file);

        FoldersJSONArray foldersArray = new FoldersJSONArray();
        BookmarksJSONArray bookmarksArray = new BookmarksJSONArray();
        HistoryJSONArray historyArray = new HistoryJSONArray();

        Cursor c = params[0];
        if (c.moveToFirst()) {

            int current = 0;
            int total = c.getCount();

            int idIndex = c.getColumnIndex(BookmarksProvider.Columns._ID);
            int titleIndex = c.getColumnIndex(BookmarksProvider.Columns.TITLE);
            int urlIndex = c.getColumnIndex(BookmarksProvider.Columns.URL);
            int creationDateIndex = c.getColumnIndex(BookmarksProvider.Columns.CREATION_DATE);
            int visitedDateIndex = c.getColumnIndex(BookmarksProvider.Columns.VISITED_DATE);
            int visitsIndex = c.getColumnIndex(BookmarksProvider.Columns.VISITS);
            int bookmarkIndex = c.getColumnIndex(BookmarksProvider.Columns.BOOKMARK);
            int folderIndex = c.getColumnIndex(BookmarksProvider.Columns.IS_FOLDER);
            int parentfolderIdIndex = c.getColumnIndex(BookmarksProvider.Columns.PARENT_FOLDER_ID);

            while (!c.isAfterLast()) {

                publishProgress(1, current, total);

                boolean isFolder = c.getInt(folderIndex) > 0 ? true : false;

                if (isFolder) {
                    String title = c.getString(titleIndex);
                    title = title != null ? URLEncoder.encode(title, "UTF-8") : "";

                    foldersArray.add(title, c.getLong(idIndex), c.getLong(parentfolderIdIndex));

                } else {
                    boolean isBookmark = c.getInt(bookmarkIndex) > 0 ? true : false;

                    String title = c.getString(titleIndex);
                    title = title != null ? URLEncoder.encode(title, "UTF-8") : "";

                    String url = c.getString(urlIndex);
                    url = url != null ? URLEncoder.encode(url, "UTF-8") : "";

                    if (isBookmark) {
                        bookmarksArray.add(c.getLong(parentfolderIdIndex), title, url,
                                c.getLong(creationDateIndex), c.getLong(visitedDateIndex),
                                c.getInt(visitsIndex));
                    } else {
                        historyArray.add(title, url, c.getLong(visitedDateIndex), c.getInt(visitsIndex));
                    }
                }

                current++;
                c.moveToNext();
            }
        }

        JSONObject output = new JSONObject();
        output.put("folders", foldersArray);
        output.put("bookmarks", bookmarksArray);
        output.put("history", historyArray);

        writer.write(output.toString(1));

        writer.flush();
        writer.close();

    } catch (JSONException e) {
        e.printStackTrace();
        return e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        return e.getMessage();
    }

    return null;
}

From source file:com.project.android.dpla.mama_dpla.DataManager.java

/**
 * Complete variable mItems_ with tags by accessing local db
 * Called by getSearchResultsWithTags (String keyword, Context activityContext)
 * @param activityContext : context of the activity that calls this function
 *//*w  w  w  .  j a va  2s  . c o m*/
public void updateResultsWithTags(Context activityContext) {
    int items_len = mItems_.size();

    // Open database for read
    MAMADbHelper helper = new MAMADbHelper(activityContext);
    SQLiteDatabase db = helper.getReadableDatabase();

    // iterate mItems_ arraylist to fill each item
    for (int iter = 0; iter < items_len; iter++) {
        DPLAItem curr_item = mItems_.get(iter);
        String selection = MAMAContract.ItemEntry.COLUMN_NAME_ITEMATID + " = ?";
        String[] selectionArgs = { curr_item.getId() };
        Cursor cur = db.query(MAMAContract.ItemEntry.TABLE_NAME, MAMAContract.ItemEntry.ALL_COLUMS, selection,
                selectionArgs, null, null, null);
        if (cur.getCount() == 0) { // If there are no tags, set null
            curr_item.setTags(null);
        } else {
            cur.moveToFirst();
            curr_item.setTags(cur.getString(MAMAContract.ItemEntry.TAG_COLUMN_NUMBER));
            Log.d(TAG, curr_item.getTags());
        }
    }
}

From source file:com.mobileaffairs.seminar.videolib.VideoLibSyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {/*from   w w  w .  j  ava2s.co m*/

    String videosJson = readVideosFromRemoteService();
    try {
        JSONArray jsonArray = new JSONArray(videosJson);
        Log.i("SyncAdapter", "Number of entries " + jsonArray.length());
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Cursor cs = provider.getLocalContentProvider().query(
                    Uri.parse(VideoLibContentProvider.CONTENT_URI + "/" + jsonObject.getString("id")), null,
                    null, null, null);
            long count = cs.getCount();
            cs.close();
            if (count == 0) {
                ContentValues values = new ContentValues();
                values.put("_id", jsonObject.getString("id"));
                values.put("title", jsonObject.getString("title"));
                values.put("duration", jsonObject.getString("duration"));
                values.put("videoUrl", jsonObject.getString("url"));
                byte[] imageBytes = readImage(jsonObject.getString("thumbnail_small"));
                if (imageBytes != null && imageBytes.length > 0) {
                    values.put("thumbnail", imageBytes);
                }
                provider.getLocalContentProvider().insert(VideoLibContentProvider.CONTENT_URI, values);
            }
            syncResult.fullSyncRequested = true;
        }
    } catch (Exception e) {
        e.printStackTrace();

    }
}

From source file:com.tcl.lzhang1.mymusic.MusicUtil.java

/**
 * get the music info//ww  w. j a v a  2  s.c om
 * 
 * @param musicFile
 * @return
 */
public static SongModel getMusicInfo(File musicFile) {
    SongModel model = new SongModel();
    // retrun null if music file is null or is or directory
    if (musicFile == null || !musicFile.isFile()) {
        return null;
    }

    byte[] buf = new byte[128];
    try {
        Log.d(LOG_TAG, "process music file{" + musicFile.getAbsolutePath() + "}");
        // tag_v1
        RandomAccessFile music = new RandomAccessFile(musicFile, "r");

        music.seek(music.length() - 128);
        music.read(buf);// read tag to buffer
        // tag_v2
        byte[] header = new byte[10];
        music.seek(0);
        music.read(header, 0, 10);
        // if ("ID3".equalsIgnoreCase(new String(header, 0, 3))) {
        // int ID3V2_frame_size = (int) (header[6] & 0x7F) * 0x200000
        // | (int) (header[7] & 0x7F) * 0x400
        // | (int) (header[8] & 0x7F) * 0x80
        // | (int) (header[9] & 0x7F);
        // byte[] FrameHeader = new byte[4];
        // music.seek(ID3V2_frame_size + 10);
        // music.read(FrameHeader, 0, 4);
        // model = getTimeInfo(FrameHeader, ID3V2_frame_size, musicFile);
        // } else {
        // byte[] FrameHeader = new byte[4];
        // music.read(FrameHeader, 0, 4);
        // model = getTimeInfo(FrameHeader, 0, musicFile);
        // }

        music.close();// close file
        // check length
        // if (buf.length != 128) {
        // throw new
        // ErrorMusicLength(String.format("error music info length, length is:%i",
        // buf.length));
        // }
        //
        // if (!"TAG".equalsIgnoreCase(new String(buf, 0, 3))) {
        // throw new UnknownTagException("unknown tag exception");
        // }
        String songName = null;
        // try {
        // songName = new String(buf, 3, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // e.printStackTrace();
        // songName = new String(buf, 3, 30).trim();
        // }
        String singerName = "";
        // try {
        // singerName = new String(buf, 33, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // singerName = new String(buf, 33, 30).trim();
        // }
        String ablum = "";
        // try {
        // ablum = new String(buf, 63, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // ablum = new String(buf, 63, 30).trim();
        // }
        String year = "";
        // try {
        // year = new String(buf, 93, 4, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // year = new String(buf, 93, 4).trim();
        // // TODO: handle exception
        // }

        String reamrk = "";
        ContentResolver contentResolver = sContext.getContentResolver();
        Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, "_data=?",
                new String[] { musicFile.getAbsolutePath() }, null);
        cursor.moveToFirst();
        if (cursor != null && cursor.getCount() != 0) {
            try {
                if (TextUtils.isEmpty(songName)) {
                    songName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE));
                    singerName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST));
                    ablum = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.ALBUM));
                    year = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.YEAR));
                }

                long secs = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION));
                model.setTime(secs);
                secs /= 1000;
                model.setHours((int) secs / 3600);
                model.setMinutes(((int) secs % 3600) / 60);
                model.setSeconds(((int) secs % 3600) % 60);
                cursor.close();
            } catch (CursorIndexOutOfBoundsException e) {
                // TODO: handle exception
                if (null != cursor) {
                    cursor.close();
                    cursor = null;
                }
                Log.d(LOG_TAG, "CursorIndexOutOfBoundsException:" + e.getMessage());
                try {
                    songName = new String(buf, 3, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e0) {
                    // TODO: handle exception
                    e.printStackTrace();
                    songName = new String(buf, 3, 30).trim();
                }
                try {
                    singerName = new String(buf, 33, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e1) {
                    // TODO: handle exception
                    singerName = new String(buf, 33, 30).trim();
                }
                try {
                    ablum = new String(buf, 63, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e2) {
                    // TODO: handle exception
                    ablum = new String(buf, 63, 30).trim();
                }
                try {
                    year = new String(buf, 93, 4, "gbk").trim();
                } catch (UnsupportedEncodingException e3) {
                    year = new String(buf, 93, 4).trim();
                    // TODO: handle exception
                }

                try {
                    reamrk = new String(buf, 97, 28, "gbk").trim();
                } catch (UnsupportedEncodingException e4) {
                    // TODO: handle exception
                    reamrk = new String(buf, 97, 28).trim();
                }

            }
        }

        //

        // get the time len

        model.setSongName(songName);
        model.setSingerName(singerName);
        model.setAblumName(ablum);
        model.setFile(musicFile.getAbsolutePath());
        model.setRemark("");
        Log.d(LOG_TAG, String.format("scaned music file[%s],album name[%s],song name[%s],singer name[%s]",
                model.getFile(), model.getAblumName(), model.getSingerName(), model.getSingerName()));

        mSongs.add(model);

        return model;
    } catch (IOException e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    return model;
}

From source file:com.github.gw2app.events.Gw2ApiEvents.java

private boolean _hasMapNamesInDB() {
    SQLiteDatabase db = this.dbhelper.getReadableDatabase();
    Cursor cursor;
    if (db != null) {
        cursor = db.query(Gw2DB.MAP_NAMES_TABLE, null, null, null, null, null, null);
        if (cursor.getCount() == 0) {
            cursor.close();//  w  ww. ja  va 2s  .c o m
            return false;
        } else {
            cursor.close();
            return true;
        }
    }
    return false;
}

From source file:edu.auburn.ppl.cyclecolumbus.NoteUploader.java

@Override
protected Boolean doInBackground(Long... noteid) {
    // First, send the note user asked for:
    Boolean result = true;// w  w w. jav  a2 s.com
    if (noteid.length != 0) {
        result = uploadOneNote(noteid[0]);
    }

    // Then, automatically try and send previously-completed notes
    // that were not sent successfully.
    Vector<Long> unsentNotes = new Vector<Long>();

    mDb.openReadOnly();
    Cursor cur = mDb.fetchUnsentNotes();
    if (cur != null && cur.getCount() > 0) {
        // pd.setMessage("Sent. You have previously unsent notes; submitting those now.");
        while (!cur.isAfterLast()) {
            unsentNotes.add(Long.valueOf(cur.getLong(0)));
            cur.moveToNext();
        }
        cur.close();
    }
    mDb.close();

    for (Long note : unsentNotes) {
        result &= uploadOneNote(note);
    }
    return result;
}

From source file:com.github.gw2app.events.Gw2ApiEvents.java

private boolean _hasWorldNamesInDB() {
    SQLiteDatabase db = this.dbhelper.getReadableDatabase();
    Cursor cursor;
    if (db != null) {
        cursor = db.query(Gw2DB.WORLD_NAMES_TABLE, null, null, null, null, null, null);
        if (cursor.getCount() == 0) {
            cursor.close();//from   w  ww . java2s  .  c om
            return false;
        } else {
            cursor.close();
            return true;
        }
    }
    return false;
}

From source file:net.mutina.uclimb.ForegroundCameraLauncher.java

/**
 * Used to find out if we are in a situation where the Camera Intent adds to images
 * to the content store. If we are using a FILE_URI and the number of images in the DB 
 * increases by 2 we have a duplicate, when using a DATA_URL the number is 1.
 */// ww  w.  ja  v  a 2 s .co  m
private void checkForDuplicateImage() {
    int diff = 2;
    Cursor cursor = queryImgDB();
    int currentNumOfImages = cursor.getCount();

    // delete the duplicate file if the difference is 2 for file URI or 1 for Data URL
    if ((currentNumOfImages - numPics) == diff) {
        cursor.moveToLast();
        int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))) - 1;
        Uri uri = Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/" + id);
        this.ctx.getContentResolver().delete(uri, null, null);
    }
}

From source file:com.android.email.provider.EmailMessageCursor.java

public EmailMessageCursor(final Context c, final Cursor cursor, final String htmlColumn,
        final String textColumn) {
    super(cursor);
    mHtmlColumnIndex = cursor.getColumnIndex(htmlColumn);
    mTextColumnIndex = cursor.getColumnIndex(textColumn);
    final int cursorSize = cursor.getCount();
    mHtmlParts = new SparseArray<String>(cursorSize);
    mTextParts = new SparseArray<String>(cursorSize);

    final ContentResolver cr = c.getContentResolver();

    while (cursor.moveToNext()) {
        final int position = cursor.getPosition();
        final long messageId = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
        try {/*  w w w .j ava  2s.c om*/
            if (mHtmlColumnIndex != -1) {
                final Uri htmlUri = Body.getBodyHtmlUriForMessageWithId(messageId);
                final InputStream in = cr.openInputStream(htmlUri);
                final String underlyingHtmlString;
                try {
                    underlyingHtmlString = IOUtils.toString(in);
                } finally {
                    in.close();
                }
                final String sanitizedHtml = HtmlSanitizer.sanitizeHtml(underlyingHtmlString);
                mHtmlParts.put(position, sanitizedHtml);
            }
        } catch (final IOException e) {
            LogUtils.v(LogUtils.TAG, e, "Did not find html body for message %d", messageId);
        }
        try {
            if (mTextColumnIndex != -1) {
                final Uri textUri = Body.getBodyTextUriForMessageWithId(messageId);
                final InputStream in = cr.openInputStream(textUri);
                final String underlyingTextString;
                try {
                    underlyingTextString = IOUtils.toString(in);
                } finally {
                    in.close();
                }
                mTextParts.put(position, underlyingTextString);
            }
        } catch (final IOException e) {
            LogUtils.v(LogUtils.TAG, e, "Did not find text body for message %d", messageId);
        }
    }
    cursor.moveToPosition(-1);
}