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:eu.thecoder4.gpl.pleftdroid.PleftDroidActivity.java

private void fillList() {
    mDbAdapter.open();//from   w ww  . j a v a 2s . co  m
    // Get all of the appointments from the database and create the item list
    Cursor c = mDbAdapter.fetchAllAppointmentsList();
    startManagingCursor(c);
    if (c.getCount() > 0) {

        String[] from = null;
        int[] to = null;
        SimpleCursorAdapter apts = null;
        if (isPrefDetailListSet()) {
            from = new String[] { PleftDroidDbAdapter.COL_DESC, PleftDroidDbAdapter.COL_ROLE,
                    PleftDroidDbAdapter.COL_STATUS, PleftDroidDbAdapter.COL_PSERVER,
                    PleftDroidDbAdapter.COL_USER };
            to = new int[] { R.id.adesc, R.id.arole, R.id.astatus, R.id.apserver, R.id.auser };
            // Now create an array adapter and set it to display using our row
            apts = new SimpleCursorAdapter(this, R.layout.event_row_details, c, from, to);
        } else {
            from = new String[] { PleftDroidDbAdapter.COL_DESC, PleftDroidDbAdapter.COL_ROLE,
                    PleftDroidDbAdapter.COL_STATUS };
            to = new int[] { R.id.adesc, R.id.arole, R.id.astatus };
            // Now create an array adapter and set it to display using our row
            apts = new SimpleCursorAdapter(this, R.layout.event_row, c, from, to);
        }
        this.getListView().destroyDrawingCache();
        this.getListView().setVisibility(ListView.INVISIBLE);
        this.getListView().setVisibility(ListView.VISIBLE);
        this.getWindow().getDecorView().invalidate();

        setListAdapter(apts);
        apts.notifyDataSetChanged();
    }
    mDbAdapter.close();
}

From source file:com.clearcenter.mobile_demo.mdSyncAdapter.java

public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {//from   w  w w.  ja  v  a2s  .  c  o m
    String authtoken = null;
    Log.i(TAG, "Starting sync operation...");

    try {
        mdSSLUtil.DisableSecurity();

        // Use the account manager to request the AuthToken we'll need
        // to talk to our sample server.  If we don't have an AuthToken
        // yet, this could involve a round-trip to the server to request
        // an AuthToken.
        authtoken = account_manager.blockingGetAuthToken(account, mdConstants.AUTHTOKEN_TYPE,
                NOTIFY_AUTH_FAILURE);

        final String hostname = account_manager.getUserData(account, "hostname");

        long _last_sample = -1;
        if (last_sample.containsKey(account.name))
            _last_sample = last_sample.get(account.name);

        // Get sync data from server...
        final String data = mdRest.GetSystemInfo(hostname, authtoken, _last_sample);

        // Something went wrong :^(
        if (TextUtils.isEmpty(data))
            return;

        if (_last_sample < 0) {
            int count = provider.delete(mdDeviceSamples.CONTENT_URI, mdDeviceSamples.NICKNAME + " = ?",
                    new String[] { account.name });

            Log.d(TAG, "Reset database, purged " + count + " samples.");
        }

        try {
            JSONObject json_data = new JSONObject(data);
            if (json_data.has("time"))
                _last_sample = Long.valueOf(json_data.getString("time"));
            Log.d(TAG, account.name + ": last sample time-stamp: " + _last_sample);
        } catch (JSONException e) {
            Log.e(TAG, "JSONException", e);
            return;
        }

        last_sample.put(account.name, _last_sample);

        ContentValues values = new ContentValues();
        values.put(mdDeviceSamples.NICKNAME, account.name);
        values.put(mdDeviceSamples.DATA, data);

        provider.insert(mdDeviceSamples.CONTENT_URI, values);

        String projection[] = new String[] { mdDeviceSamples.SAMPLE_ID };

        Cursor cursor = provider.query(mdDeviceSamples.CONTENT_URI, projection,
                mdDeviceSamples.NICKNAME + " = ?", new String[] { account.name }, mdDeviceSamples.SAMPLE_ID);

        int rows = cursor.getCount();
        Log.d(TAG, "Rows: " + rows);
        if (rows <= mdConstants.MAX_SAMPLES) {
            cursor.close();
            return;
        }

        Log.d(TAG, "Samples to purge: " + (rows - mdConstants.MAX_SAMPLES));
        cursor.move(rows - mdConstants.MAX_SAMPLES);

        int top_id = cursor.getInt(cursor.getColumnIndex(mdDeviceSamples.SAMPLE_ID));
        Log.d(TAG, "Top ID: " + top_id);

        cursor.close();

        int count = provider.delete(mdDeviceSamples.CONTENT_URI,
                mdDeviceSamples.SAMPLE_ID + " <= ? AND " + mdDeviceSamples.NICKNAME + " = ?",
                new String[] { String.valueOf(top_id), account.name });

        Log.d(TAG, "Purged " + count + " samples.");

    } catch (final RemoteException e) {
        Log.e(TAG, "RemoteException", e);
        syncResult.stats.numParseExceptions++;
    } catch (final AuthenticatorException e) {
        Log.e(TAG, "AuthenticatorException", e);
        syncResult.stats.numParseExceptions++;
    } catch (final OperationCanceledException e) {
        Log.e(TAG, "OperationCanceledExcetpion", e);
    } catch (final IOException e) {
        Log.e(TAG, "IOException", e);
        syncResult.stats.numIoExceptions++;
    } catch (final ParseException e) {
        Log.e(TAG, "ParseException", e);
        syncResult.stats.numParseExceptions++;
    } catch (final AuthenticationException e) {
        Log.e(TAG, "AuthenticationException", e);
        syncResult.stats.numAuthExceptions++;
        account_manager.invalidateAuthToken(mdConstants.AUTHTOKEN_TYPE, authtoken);
    } catch (GeneralSecurityException e) {
        Log.e(TAG, "GeneralSecurityException", e);
    } catch (final JSONException e) {
        Log.e(TAG, "JSONException", e);
        syncResult.stats.numParseExceptions++;
    }
}

From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.services.transformationmanager.database.LocalTransformationDBMS.java

public ArrayList<Transformation> getAvailableTransformations() {
    ArrayList<Transformation> transformations = new ArrayList<Transformation>();

    if (D)/*  w w  w  .ja v a 2 s .com*/
        Log.i(TAG, " quering for all transformations");

    Cursor cursor = database.query(LocalTransformationDB.TABLE_LOCAL_TRANSFORMATIONS, null, null, null, null,
            null, null);

    Transformation tempTrans;
    for (int i = 0; i < cursor.getCount(); i++) {
        tempTrans = cursorToTransformation(cursor, i);
        if (tempTrans != null)
            transformations.add(tempTrans);
    }

    cursor.close();
    return transformations;
}

From source file:com.jaspersoft.android.jaspermobile.util.ProfileHelper.java

public void seedProfilesIfNeed() {
    ContentResolver contentResolver = context.getContentResolver();
    Cursor cursor = contentResolver.query(JasperMobileDbProvider.SERVER_PROFILES_CONTENT_URI,
            new String[] { ServerProfilesTable._ID }, null, null, null);
    if (cursor != null) {
        try {//from w  w w  . ja  va 2s  .c o m
            if (cursor.getCount() == 0) {
                ServerProfiles testProfile = new ServerProfiles();

                testProfile.setAlias(DEFAULT_ALIAS);
                testProfile.setServerUrl(DEFAULT_SERVER_URL);
                testProfile.setOrganization(DEFAULT_ORGANIZATION);
                testProfile.setUsername(DEFAULT_USERNAME);
                testProfile.setPassword(DEFAULT_PASS);

                contentResolver.insert(JasperMobileDbProvider.SERVER_PROFILES_CONTENT_URI,
                        testProfile.getContentValues());
                populateTestInstances(contentResolver);
            }
        } finally {
            cursor.close();
        }
    }
}

From source file:com.adamhurwitz.android.popularmovies.service.MovieDataService.java

public void putDataIntoDb(
        //String id,
        Integer movie_id, String title, String image_url, String summary, Double vote_average,
        Double popularity, String release_date) {

    // Access database
    //CursorDbHelper mDbHelper = new CursorDbHelper(context);

    // Put Info into Database

    // Gets the data repository in write mode
    //SQLiteDatabase db = mDbHelper.getWritableDatabase();

    // Create a new map of values, where column names are the keys
    ContentValues values = new ContentValues();
    values.put(CursorContract.MovieData.COLUMN_NAME_MOVIEID, movie_id);
    values.put(CursorContract.MovieData.COLUMN_NAME_TITLE, title);
    values.put(CursorContract.MovieData.COLUMN_NAME_IMAGEURL, image_url);
    values.put(CursorContract.MovieData.COLUMN_NAME_SUMMARY, summary);
    values.put(CursorContract.MovieData.COLUMN_NAME_VOTEAVERAGE, vote_average);
    values.put(CursorContract.MovieData.COLUMN_NAME_POPULARITY, popularity);
    values.put(CursorContract.MovieData.COLUMN_NAME_RELEASEDATE, release_date);
    values.put(CursorContract.MovieData.COLUMN_NAME_FAVORITE, "1");

    // Insert the new row, returning the primary key value of the new row
    long thisRowID;

    Cursor cursor = this.getContentResolver().query(CursorContract.MovieData.CONTENT_URI, null,
            CursorContract.MovieData.COLUMN_NAME_TITLE + "= ?", new String[] { title },
            CursorContract.MovieData.COLUMN_NAME_POPULARITY + " DESC");
    if (cursor.getCount() == 0) {
        Uri uri;/*from  ww  w .  j av a2s . c  om*/
        uri = this.getContentResolver().insert(CursorContract.MovieData.CONTENT_URI, values);
    }
}

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

/**
 * ?/*w w w. j av  a2s  .com*/
 *
 * @param session
 * @return
 */
public static List<String> getImageMessageIdSession(long session) {
    String sql = "select msgid from " + DatabaseHelper.TABLES_NAME_IM_MESSAGE + " where "
            + IMessageColumn.OWN_THREAD_ID + " = " + session + " and msgType=" + ECMessage.Type.IMAGE.ordinal();
    Cursor cursor = getInstance().sqliteDB().rawQuery(sql, null);
    List<String> msgids = null;
    if (cursor != null && cursor.getCount() > 0) {
        msgids = new ArrayList<String>();
        while (cursor.moveToNext()) {
            msgids.add(cursor.getString(0));
        }
        cursor.close();
    }
    return msgids;
}

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

protected void writeSessionFooter(final FileWriter destination, final Session session, Cursor rowCursor)
        throws IOException {
    if (rowCursor.getCount() != 0) {
        destination.write("]} ");
    }/*from   w ww. j av a  2  s . c o  m*/
}

From source file:org.noorganization.instalistsynch.controller.local.dba.impl.ClientLogDbController.java

@Override
public Date getLeastRecentUpdateTimeForUuid(String _clientUuid) {
    Cursor cursor = mContentResolver.query(Uri.withAppendedPath(InstalistProvider.BASE_CONTENT_URI, "log"),
            LogInfo.COLUMN.ALL_COLUMNS, LogInfo.COLUMN.ITEM_UUID + " LIKE ? ", new String[] { _clientUuid },
            LogInfo.COLUMN.ACTION_DATE + " DESC ");
    if (cursor == null) {
        return null;
    }/*ww  w  . j a v a  2  s .  c  o m*/
    if (cursor.getCount() == 0) {
        cursor.close();
        return null;
    }
    cursor.moveToFirst();

    String date = cursor.getString(cursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE));
    try {
        return ISO8601Utils.parse(date, new ParsePosition(0));
    } catch (ParseException e) {
        e.printStackTrace();
        return null;
    } finally {
        cursor.close();
    }
}

From source file:info.dc585.hpt.sa.SyncAdapter.java

private void syncTopHackers(ContentProviderClient provider, SyncResult syncResult) {

    try {/*from   w  w w. j  av a2  s.c o  m*/

        Log.d(TAG, "Calling something to sync up hackerpoint db");

        JSONArray hackers = NetworkUtilities.getTopHackers();
        if (hackers == null) {
            Log.e(TAG, "somehow got null hackers, explode please");
            syncResult.stats.numParseExceptions++;
        }
        if (hackers.length() == 0) {
            return;
        }

        Log.i(TAG, "Updateing content provider");
        Log.i(TAG, "hackers.length():" + hackers.length());
        for (int i = 0; i < hackers.length(); i++) {
            JSONObject jo = hackers.getJSONObject(i);
            String name = jo.getString("name");

            String selection = TopHackerTable.COLUMN_NAME + " like ?";
            String[] selectionArgs = { name };

            String[] projection = { TopHackerTable.COLUMN_ID, TopHackerTable.COLUMN_NAME };

            ContentValues values = new ContentValues();

            // FIXME:  Dear self, WTF would i trust network returned data without verifying limits ;)
            // TODO: See FIXME above.
            Cursor c = provider.query(HackerPointsContentProvider.HACKERS_URI, projection, selection,
                    selectionArgs, null);
            if (c.getCount() == 0) {
                Log.d(TAG, "performing insert for new name:" + name);

                int points = jo.getInt("points");
                values.put(TopHackerTable.COLUMN_POINTS, points);

                int pool = jo.getInt("pool");
                values.put(TopHackerTable.COLUMN_POOL, pool);

                int internets = jo.getInt("internets");
                values.put(TopHackerTable.COLUMN_INTERNETS, internets);

                String pictureURL = jo.getString("pictureURL");
                values.put(TopHackerTable.COLUMN_PICTUREURL, pictureURL);

                values.put(TopHackerTable.COLUMN_NAME, name);
                values.put(TopHackerTable.COLUMN_UPDATE, System.currentTimeMillis());
                provider.insert(HackerPointsContentProvider.HACKERS_URI, values);
                syncResult.stats.numInserts++;

            } else if (c.getCount() == 1) {
                Log.d(TAG, "performing update for name:" + name);
                if (name == null || name.isEmpty()) {
                    Log.e(TAG, "null or empty name");
                    continue;
                }

                int points = jo.getInt("points");
                values.put(TopHackerTable.COLUMN_POINTS, points);

                int pool = jo.getInt("pool");
                values.put(TopHackerTable.COLUMN_POOL, pool);

                int internets = jo.getInt("internets");
                values.put(TopHackerTable.COLUMN_INTERNETS, internets);

                String pictureURL = jo.getString("pictureURL");
                values.put(TopHackerTable.COLUMN_PICTUREURL, pictureURL);

                int rows = provider.update(HackerPointsContentProvider.HACKERS_URI, values, selection,
                        selectionArgs);

                Log.d(TAG, "Updated:" + rows + ": rows");
                syncResult.stats.numUpdates += rows;

            } else {
                Log.e(TAG, "Cursor count was not 0 or 1 was:" + c.getCount());
                continue;
            }
        }

        // Now run through both lists and figure out which one to delete.
        String[] projection = { TopHackerTable.COLUMN_NAME };
        Cursor c = provider.query(HackerPointsContentProvider.HACKERS_URI, projection, null, null, null);
        if (c.getCount() == 0) {
            return;
        }

        ArrayList<String> goodNames = new ArrayList<String>();
        ArrayList<String> rmNames = new ArrayList<String>();

        for (int i = 0; i < hackers.length(); i++) {
            JSONObject jo = hackers.getJSONObject(i);
            String name = jo.getString("name");
            goodNames.add(name);
        }

        while (c.moveToNext()) {
            int namec = c.getColumnIndex(TopHackerTable.COLUMN_NAME);
            String dbName = c.getString(namec);

            if (goodNames.contains(dbName) == false) {
                Log.d(TAG, "Adding name:" + dbName + ": to the delete list");
                rmNames.add(dbName);
            }
        }

        for (String nextName : rmNames) {
            Log.d(TAG, "deleting name:" + nextName + ":");
            // FIXME: use column name from Table class
            String where = " name = ? ";
            String[] whereArgs = { nextName };
            int rows = provider.delete(HackerPointsContentProvider.HACKERS_URI, where, whereArgs);
            syncResult.stats.numDeletes += rows;
        }

    } catch (final AuthenticationException e) {
        Log.e(TAG, "AuthenticationException", e);
    } catch (final JSONException e) {
        Log.e(TAG, "JSONException", e);
    } catch (final IOException e) {
        Log.e(TAG, "IOException", e);
    } catch (final ParseException e) {
        Log.e(TAG, "ParseException", e);
        syncResult.stats.numParseExceptions++;
    } catch (final RemoteException e) {
        Log.e(TAG, "RemoteException", e);
    }
}