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.example.conor.dotaapp.FetchMatchTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us./*from  w  w w  .  j  a v a  2  s. co  m*/
 */
private void getMatchDataFromJson(String matchJsonStr, String steamId) throws JSONException {

    //LOG TAGS
    final String LOG_TAG = FetchMatchTask.class.getSimpleName();
    //final String LOG_MATCH_JSON = "Match JSON Object";
    final String LOG_MATCH_ARRAY = "Match JSON Array";

    //JSON strings
    final String OWM_MATCHES = "matches";
    final String OWM_MATCHID = "match_id";
    final String OWM_START = "start_time";
    final String OWM_PLAYERS = "players";
    //final String OWM_PLAYERID = "account_id";
    //final String OWM_HEROID = "hero_id";
    final String OWM_RESULT = "result";

    //Get number of matches to display from settings
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
    String numberOfMatches = sharedPrefs.getString(mContext.getString(R.string.num_matches_key),
            mContext.getString(R.string.num_matches_default));

    int numMatches = Integer.parseInt(numberOfMatches);

    try {
        JSONObject matchJson = new JSONObject(matchJsonStr);
        JSONArray matchArray = matchJson.getJSONObject(OWM_RESULT).getJSONArray(OWM_MATCHES);
        Log.v(LOG_MATCH_ARRAY, "matchArray: " + matchArray);

        Vector<ContentValues> cVVector = new Vector<ContentValues>(matchArray.length());

        //String array to hold results of each match
        String[] resultStrs = new String[numMatches];

        //For loop to loop through all matches
        //ATM: matchArray.length() = 5
        for (int i = 0; i < matchArray.length(); i++) {
            // For now, using the format "Date, hero, match_id"
            String hero, match_id, dateTime;
            long date;

            // Get the JSON object representing a single match
            JSONObject singleMatch = matchArray.getJSONObject(i);
            Log.v(LOG_TAG, "Single Match JSONObject: " + singleMatch);

            //Get match_id of a single match
            match_id = singleMatch.getString(OWM_MATCHID);
            Log.v(LOG_TAG, "match_id: " + match_id);

            //Change date from UTC to readable date. Get Long value first
            date = Long.parseLong(singleMatch.getString(OWM_START));
            //Output actual date instead of just seconds for start_time
            dateTime = getReadableDateString(date);

            /**
             *  rest of JSON code is for match data
             * */
            //Array of players
            JSONArray allPlayers = matchArray.getJSONObject(i).getJSONArray(OWM_PLAYERS);
            Log.v(LOG_TAG, "allPlayers JSONArray: " + allPlayers);

            //Returns single Hero Object with
            JSONObject heroObject = singleMatch.getJSONArray(OWM_PLAYERS).getJSONObject(0);
            Log.v(LOG_TAG, "heroObject: " + heroObject);
            hero = heroObject.getString("hero_id");
            Log.v(LOG_TAG, "Hero ID: " + hero);

            for (int j = 0; j < allPlayers.length(); j++) {
                JSONObject singlePlayer = allPlayers.getJSONObject(j);
            }
            //Add strings to resultStrs at index i
            resultStrs[i] = "Date: " + dateTime + ", Hero: " + hero + ", Match ID: " + match_id;
            Log.v(LOG_TAG, "ResultStrs[" + i + "]: " + resultStrs[i]);

            for (Object s : resultStrs) {
                Log.v(LOG_TAG, "Dota Data to Display: " + s);
            }
            /**
             *  END OF JSON DATA
             */

            //Insert data into match table
            ContentValues matchValues = new ContentValues();

            matchValues.put(MatchEntry.COLUMN_MATCH_KEY, match_id);
            matchValues.put(MatchEntry.COLUMN_START_TIME, dateTime);
            matchValues.put(MatchEntry.COLUMN_P_ACCOUNT_ID, steamId);

            cVVector.add(matchValues);
        }

        int inserted = 0;
        // add to database using bulkInsert
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            inserted = mContext.getContentResolver().bulkInsert(MatchEntry.CONTENT_URI, cvArray);
        }

        // Sort order:  Ascending, by date.
        String sortOrder = MatchEntry.COLUMN_START_TIME + " ASC";
        Uri matchForPlayerUri = MatchEntry.buildMatchPlayerWithStartTime(steamId, System.currentTimeMillis());

        //display bulk insert
        Cursor cur = mContext.getContentResolver().query(matchForPlayerUri, null, null, null, sortOrder);
        //Display cursor
        ////NULL CURSOR
        Log.e(LOG_TAG, "Cursor: " + cur);

        cVVector = new Vector<ContentValues>(cur.getCount());
        if (cur.moveToFirst()) {
            do {
                ContentValues cv = new ContentValues();
                DatabaseUtils.cursorRowToContentValues(cur, cv);
                cVVector.add(cv);
            } while (cur.moveToNext());
        }

        Log.d(LOG_TAG, "FetchMatchTask Complete. " + inserted + " Inserted");

        //String[] resultStrsActual = convertContentValuesToUXFormat(cVVector);
        //return resultStrsActual;

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    //return null;
}

From source file:com.sublimis.urgentcallfilter.Magic.java

private boolean isCallerEligible() {
    boolean retVal = true;

    if (MyPreference.isContactsOnly()) {
        if (!strValidAndNotEmpty(mNumber)) {
            retVal = false;// ww w  .  java  2  s . c o  m
        } else {
            try {
                Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(mNumber));

                if (mContext != null) {
                    ContentResolver contentResolver = mContext.getContentResolver();

                    if (contentResolver != null) {
                        Cursor cur = contentResolver.query(uri, new String[] { PhoneLookup._ID }, null, null,
                                null);

                        if (cur == null || cur.getCount() <= 0) {
                            retVal = false;
                        }

                        if (cur != null) {
                            cur.close();
                        }
                    }
                }
            } catch (Exception e) {
            }
        }
    }

    return retVal;
}

From source file:myblog.richard.vewe.launcher3.LauncherApplication.java

public String[] getPasswords() {
    String selection = UsersContract.TableUsers.Column.NAME + "=" + UsersContract.TableUsers.ROOT;
    Cursor cursor = getContentResolver().query(UsersContract.TableUsers.CONTENT_URI,
            new String[] { UsersContract.TableUsers.Column.PASSWORD, UsersContract.TableUsers.Column.PWD2 },
            selection, null, null);//from  ww w .  j av  a  2s  .c  o  m
    if (cursor == null || cursor.getCount() != 1) {
        Log.e(tag, "failed to query root password");
        return null;
    }
    String[] as = new String[2];

    cursor.moveToFirst();
    int index = cursor.getColumnIndex(UsersContract.TableUsers.Column.PASSWORD);
    as[0] = cursor.getString(index);
    index = cursor.getColumnIndex(UsersContract.TableUsers.Column.PWD2);
    as[1] = cursor.getString(index);
    cursor.close();
    return as;
}

From source file:org.odk.collect.android.tasks.DownloadFormsTask.java

@Override
protected HashMap<String, String> doInBackground(ArrayList<FormDetails>... values) {
    ArrayList<FormDetails> toDownload = values[0];

    int total = toDownload.size();
    int count = 1;

    HashMap<String, String> result = new HashMap<String, String>();

    for (int i = 0; i < total; i++) {
        FormDetails fd = toDownload.get(i);
        publishProgress(fd.formName, Integer.valueOf(count).toString(), Integer.valueOf(total).toString());

        String message = "";

        try {/* ww w.j a va2 s. c  o  m*/
            // get the xml file
            // if we've downloaded a duplicate, this gives us the file
            File dl = downloadXform(fd.formName, fd.downloadUrl);

            String[] projection = { FormsColumns._ID, FormsColumns.FORM_FILE_PATH };
            String[] selectionArgs = { dl.getAbsolutePath() };
            String selection = FormsColumns.FORM_FILE_PATH + "=?";
            Cursor alreadyExists = Collect.getInstance().getContentResolver().query(FormsColumns.CONTENT_URI,
                    projection, selection, selectionArgs, null);

            Uri uri = null;
            if (alreadyExists.getCount() <= 0) {
                // doesn't exist, so insert it
                ContentValues v = new ContentValues();
                v.put(FormsColumns.FORM_FILE_PATH, dl.getAbsolutePath());

                HashMap<String, String> formInfo = FileUtils.parseXML(dl);
                v.put(FormsColumns.DISPLAY_NAME, formInfo.get(FileUtils.TITLE));
                v.put(FormsColumns.MODEL_VERSION, formInfo.get(FileUtils.MODEL));
                v.put(FormsColumns.UI_VERSION, formInfo.get(FileUtils.UI));
                v.put(FormsColumns.JR_FORM_ID, formInfo.get(FileUtils.FORMID));
                v.put(FormsColumns.SUBMISSION_URI, formInfo.get(FileUtils.SUBMISSIONURI));
                uri = Collect.getInstance().getContentResolver().insert(FormsColumns.CONTENT_URI, v);
            } else {
                alreadyExists.moveToFirst();
                uri = Uri.withAppendedPath(FormsColumns.CONTENT_URI,
                        alreadyExists.getString(alreadyExists.getColumnIndex(FormsColumns._ID)));
            }

            if (fd.manifestUrl != null) {
                Cursor c = Collect.getInstance().getContentResolver().query(uri, null, null, null, null);
                if (c.getCount() > 0) {
                    // should be exactly 1
                    c.moveToFirst();

                    String error = downloadManifestAndMediaFiles(
                            c.getString(c.getColumnIndex(FormsColumns.FORM_MEDIA_PATH)), fd, count, total);
                    if (error != null) {
                        message += error;
                    }
                }
            } else {
                // TODO: manifest was null?
                Log.e(t, "Manifest was null.  PANIC");
            }
        } catch (SocketTimeoutException se) {
            se.printStackTrace();
            message += se.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
            message += e.getMessage();
        }
        count++;
        if (message.equalsIgnoreCase("")) {
            message = Collect.getInstance().getString(R.string.success);
        }
        result.put(fd.formName, message);
    }

    return result;
}

From source file:com.polyvi.xface.extension.telephony.XTelephonyExt.java

/**
 * ???// w w  w.  j  a  v  a  2 s  . c  om
 *
 * @param[in] callRecordType ?
 * @return ?
 */
private int getCallRecordCount(String callRecordType) {
    int callType = getCallRecordType(callRecordType);
    Cursor c = mContentResolver.query(CallLog.Calls.CONTENT_URI, new String[] { CallLog.Calls._ID },
            CallLog.Calls.TYPE + "=" + callType, null, CallLog.Calls.DEFAULT_SORT_ORDER);
    int count = 0;
    if (null != c) {
        count = c.getCount();
    }
    c.close();
    return count;
}

From source file:com.ubikod.urbantag.model.TagManager.java

/**
 * Get all tags from db/* ww w.  j  a v a  2  s .  com*/
 * @return
 */
private HashMap<Integer, Tag> dbGetAll() {
    open();

    Cursor c = mDB.query(
            DatabaseHelper.TABLE_TAGS, new String[] { DatabaseHelper.TAG_COL_ID, DatabaseHelper.TAG_COL_NAME,
                    DatabaseHelper.TAG_COL_COLOR, DatabaseHelper.TAG_COL_NOTIFY },
            null, null, null, null, null);
    HashMap<Integer, Tag> tags = new HashMap<Integer, Tag>();

    if (c.getCount() == 0) {
        c.close();
        close();
        return tags;
    }

    c.moveToFirst();
    do {
        Tag t = this.cursorToTag(c);
        tags.put(t.getId(), t);
    } while (c.moveToNext());

    c.close();
    close();
    return tags;
}

From source file:com.mp3tunes.android.player.content.LockerDb.java

private Album cursorToAlbum(Cursor c) {
    if (c.getCount() > 1)
        Log.e("Mp3Tunes", "Got more than one album");
    if (c.moveToFirst()) {
        Album a = new Album(new LockerId(c.getInt(Music.ALBUM_MAPPING.ID)),
                c.getString(Music.ALBUM_MAPPING.ALBUM_NAME));
        c.close();//from   w ww. j a v a2s  . c  om
        return a;
    }
    c.close();
    return null;
}

From source file:com.raspi.chatapp.util.storage.MessageHistory.java

public MessageArrayContent getLastMessage(String buddyId) {
    MessageArrayContent mac = null;//w ww  .j a v a 2s .  c o m
    SQLiteDatabase db = mDbHelper.getReadableDatabase();

    try {
        String[] columns = new String[] { MessageHistoryContract.MessageEntry.COLUMN_NAME_BUDDY_ID,
                MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TYPE,
                MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_CONTENT,
                MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_STATUS,
                MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TIMESTAMP,
                MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_URL,
                MessageHistoryContract.MessageEntry._ID,
                MessageHistoryContract.MessageEntry.COLUMN_NAME_OTHERS_ID };
        Cursor lastMessage = db.query(buddyId, columns, null, null, null, null,
                MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TIMESTAMP + " DESC", "1");
        lastMessage.moveToFirst();
        if (lastMessage.getCount() != 0 && lastMessage.moveToFirst()) {
            String type = lastMessage.getString(1);
            SharedPreferences preferences = context.getSharedPreferences(Constants.PREFERENCES, 0);
            String me = preferences.getString(Constants.USERNAME, "");
            boolean sent = me.equals(lastMessage.getString(0));

            if (TYPE_TEXT.equals(type)) {
                mac = new TextMessage(!sent, lastMessage.getString(2), lastMessage.getLong(4),
                        lastMessage.getString(3), lastMessage.getLong(6), lastMessage.getLong(7));
            } else if (TYPE_IMAGE.equals(type)) {
                JSONArray contentJSON = new JSONArray(lastMessage.getString(2));
                mac = new ImageMessage(!sent, contentJSON.getString(0), contentJSON.getString(1),
                        lastMessage.getString(5), lastMessage.getInt(6), lastMessage.getLong(4),
                        lastMessage.getString(3), lastMessage.getLong(6), lastMessage.getString(1),
                        lastMessage.getLong(7));
            }
        }
    } catch (Exception e) {

    } finally {
        db.close();
    }
    return mac;
}

From source file:com.yuntongxun.ecdemo.storage.IMessageSqlManager.java

/**
 * ???ID//from  w  w w.j  a v  a2s .c  o  m
 *
 * @param contactId
 * @return
 */
public static long querySessionIdForByContactId(String contactId) {
    Cursor cursor = null;
    long threadId = 0;
    if (contactId != null) {
        String where = IThreadColumn.CONTACT_ID + " = '" + contactId + "' ";
        try {
            cursor = getInstance().sqliteDB().query(DatabaseHelper.TABLES_NAME_IM_SESSION, null, where, null,
                    null, null, null);
            if (cursor != null && cursor.getCount() > 0) {
                if (cursor.moveToFirst()) {
                    threadId = cursor.getLong(cursor.getColumnIndexOrThrow(IThreadColumn.ID));
                }
            }
        } catch (SQLException e) {
            LogUtil.e(TAG + " " + e.toString());
        } finally {
            if (cursor != null) {
                cursor.close();
                cursor = null;
            }
        }
    }
    return threadId;
}

From source file:fi.hut.soberit.sensors.services.BatchDataUploadService.java

protected void writeSession(final FileWriter destination, final Session session, boolean lastSession)
        throws IOException {

    final DatabaseHelper shardHelper = new DatabaseHelper(BatchDataUploadService.this, session.getId());
    final SQLiteDatabase db = shardHelper.getReadableDatabase();

    final Cursor rowCursor = db.query(DatabaseHelper.OBSERVATION_VALUE_TABLE, null, null, null, null, null,
            ObservationValueTable.TIME + " ASC");

    rowCursor.moveToFirst();//from  ww  w  . jav  a  2s .  c o  m

    writeSessionHeader(destination, session, rowCursor);

    Log.d(TAG, "sessions: " + rowCursor.getCount());
    final StringBuilder builder = new StringBuilder();
    for (int row = 0; row < rowCursor.getCount(); row++) {
        rowCursor.moveToPosition(row);

        final GenericObservation observation = ObservationValueTable.observationFromCursor(rowCursor, row);

        final ObservationType type = typesMap.get(observation.getObservationTypeId());
        builder.setLength(0);

        writeObservation(builder, session, observation, type, row + 1 != rowCursor.getCount());

        destination.write(builder.toString());
    } // for(int row = 0; row < rowCursor.getCount(); row++) {

    writeSessionFooter(destination, session, rowCursor);

    rowCursor.close();
    shardHelper.close();

    if (!lastSession) {
        destination.write(",");
    }
}