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:myblog.richard.vewe.launcher3.LauncherApplication.java

public String getPassword() {
    String selection = UsersContract.TableUsers.Column.NAME + "=" + UsersContract.TableUsers.ROOT;
    Cursor cursor = getContentResolver().query(UsersContract.TableUsers.CONTENT_URI,
            new String[] { UsersContract.TableUsers.Column.PASSWORD }, selection, null, null);
    if (cursor == null || cursor.getCount() != 1) {
        Log.e(tag, "failed to query root password");
        return null;
    }/*w w  w. j  a v  a2 s.c  o m*/
    cursor.moveToFirst();
    int index = cursor.getColumnIndex(UsersContract.TableUsers.Column.PASSWORD);
    String ret = cursor.getString(index);
    cursor.close();
    return ret;
}

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

private void loadFromContentProvider() {
    //get current user
    ContentResolver resolver = getContentResolver();

    String selection = UsersContract.TableUsers.Column.NAME + "=" + UsersContract.TableUsers.CURRENT;
    try {/*from  ww w .j ava 2s. c om*/
        Cursor cursor = resolver.query(UsersContract.TableUsers.CONTENT_URI,
                UsersContract.TableUsers.BASIC_COLUMNS, selection, null, null);
        if (cursor == null || cursor.getCount() != 1) {
            Log.e(tag, "failed to query current user");
            return;
        }
        cursor.moveToFirst();
        mUser = new User(cursor);
        cursor.close();
        if (LOGD) {
            Log.d(tag, "current User " + mUser);
        }

        mApplist.clear();
        cursor = resolver.query(UsersContract.TableApplist.DIGA_URI, UsersContract.TableApplist.BASIC_COLUMNS,
                null, null, null);
        if (cursor == null) {
            Log.e(tag, "could not query all from table applist diga");
        } else if (cursor.getCount() < 1) {
            if (LOGD) {
                Log.d(tag, "no entries in table applist diga");
            }
        } else {
            while (cursor.moveToNext()) {
                App app = new App(cursor);
                if (LOGD) {
                    Log.d(tag, "app: " + app);
                }
                mApplist.add(app);
            }
            cursor.close();
        }

    } catch (Exception e) {
        Log.e(tag, "exception to query current user or applist");
    }
}

From source file:com.sferadev.etic.tasks.DownloadTasksTask.java

boolean instanceExists(String instancePath) {
    boolean exists = true;

    // Get the provider URI of the instance 
    String where = InstanceColumns.INSTANCE_FILE_PATH + "=?";
    String[] whereArgs = { instancePath };

    ContentResolver cr = Collect.getInstance().getContentResolver();
    Cursor cInstanceProvider = cr.query(InstanceColumns.CONTENT_URI, null, where, whereArgs, null);
    if (cInstanceProvider.getCount() != 1) {
        Log.e("MainListActivity:completeTask",
                "Unique instance not found: count is:" + cInstanceProvider.getCount());
        exists = false;/*from   w w w  . j  a  v  a 2s. c om*/
    }
    cInstanceProvider.close();
    return exists;
}

From source file:org.noorganization.instalistsynch.controller.synch.impl.CategorySynch.java

@Override
public void indexLocal(int _groupId, Date _lastIndexTime) {
    String lastIndexTime = ISO8601Utils.format(_lastIndexTime, false, TimeZone.getTimeZone("GMT+0000"));//.concat("+0000");
    boolean isLocal = false;
    GroupAuth groupAuth = mGroupAuthDbController.getLocalGroup();
    if (groupAuth != null) {
        isLocal = groupAuth.getGroupId() == _groupId;
    }// w  w  w. j av a2s.  co  m
    Cursor categoryLogCursor = mClientLogDbController.getLogsSince(lastIndexTime, mModelType);
    if (categoryLogCursor.getCount() == 0) {
        categoryLogCursor.close();
        return;
    }

    try {
        while (categoryLogCursor.moveToNext()) {
            // fetch the action type
            int actionId = categoryLogCursor.getInt(categoryLogCursor.getColumnIndex(LogInfo.COLUMN.ACTION));
            eActionType actionType = eActionType.getTypeById(actionId);

            List<ModelMapping> modelMappingList = mCategoryModelMappingController.get(
                    ModelMapping.COLUMN.GROUP_ID + " = ? AND " + ModelMapping.COLUMN.CLIENT_SIDE_UUID
                            + " LIKE ?",
                    new String[] { String.valueOf(_groupId), categoryLogCursor
                            .getString(categoryLogCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID)) });
            ModelMapping modelMapping = modelMappingList.size() == 0 ? null : modelMappingList.get(0);

            switch (actionType) {
            case INSERT:
                // skip insertion because this should be decided by the user if the non local groups should have access to the category
                // and also skip if a mapping for this case already exists!
                if (!isLocal || modelMapping != null) {
                    continue;
                }

                String clientUuid = categoryLogCursor
                        .getString(categoryLogCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID));
                Date clientDate = ISO8601Utils.parse(
                        categoryLogCursor
                                .getString(categoryLogCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)),
                        new ParsePosition(0));
                modelMapping = new ModelMapping(null, groupAuth.getGroupId(), null, clientUuid,
                        new Date(Constants.INITIAL_DATE), clientDate, false);
                mCategoryModelMappingController.insert(modelMapping);
                break;
            case UPDATE:
                if (modelMapping == null) {
                    Log.i(TAG, "indexLocal: the model is null but shouldn't be");
                    continue;
                }
                String timeString = categoryLogCursor
                        .getString(categoryLogCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE));
                clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0));
                modelMapping.setLastClientChange(clientDate);
                mCategoryModelMappingController.update(modelMapping);
                break;
            case DELETE:
                if (modelMapping == null) {
                    Log.i(TAG, "indexLocal: the model is null but shouldn't be");
                    continue;
                }
                modelMapping.setDeleted(true);
                timeString = categoryLogCursor
                        .getString(categoryLogCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE));
                clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0));
                modelMapping.setLastClientChange(clientDate);
                mCategoryModelMappingController.update(modelMapping);
                break;
            default:
            }

        }
    } catch (Exception e) {
        categoryLogCursor.close();
    }
}

From source file:com.jsonstore.database.ReadableDatabase.java

protected String findOperationForObjectById(int id) {
    Cursor cursor = rawQuery(JSONStoreUtil.formatString(ReadableDatabase.SQL_FIND_OP,
            DatabaseConstants.FIELD_OPERATION, this.schema.getName(), DatabaseConstants.FIELD_ID),
            new String[] { "" + id }); //$NON-NLS-1$
    String result;//  www . ja  v  a 2s  .  com

    if (cursor.getCount() < 1) {
        cursor.close();

        return null;
    }

    cursor.moveToNext();

    result = cursor.getString(0);

    cursor.close();

    return result;
}

From source file:info.staticfree.android.units.UnitUsageDBHelper.java

public int getUnitUsageDbCount() {
    final SQLiteDatabase db = getReadableDatabase();
    final String[] proj = { UsageEntry._ID };
    if (!db.isOpen()) {
        return -1;
    }//ww w  . j  a  v a  2s  .  c  o m
    final Cursor c = db.query(DB_USAGE_TABLE, proj, null, null, null, null, null);
    c.moveToFirst();
    final int count = c.getCount();
    c.close();
    db.close();
    return count;
}

From source file:com.money.manager.ex.reports.IncomeVsExpensesListFragment.java

private void showChartInternal() {
    // take a adapter and cursor
    IncomeVsExpensesAdapter adapter = ((IncomeVsExpensesAdapter) getListAdapter());
    if (adapter == null)
        return;/*from w  w  w  .j  a v  a  2  s  .  c  o m*/
    Cursor cursor = adapter.getCursor();
    if (cursor == null)
        return;
    // Move to the first record.
    if (cursor.getCount() <= 0)
        return;

    // arrays
    ArrayList<Double> incomes = new ArrayList<>();
    ArrayList<Double> expenses = new ArrayList<>();
    ArrayList<String> titles = new ArrayList<>();

    // Reset cursor to initial position.
    cursor.moveToPosition(-1);
    // cycle cursor
    while (cursor.moveToNext()) {
        int month = cursor.getInt(cursor.getColumnIndex(IncomeVsExpenseReportEntity.Month));
        // check if not subtotal
        if (month != IncomeVsExpensesActivity.SUBTOTAL_MONTH) {
            // incomes and expenses
            incomes.add(cursor.getDouble(cursor.getColumnIndex(IncomeVsExpenseReportEntity.Income)));
            expenses.add(
                    Math.abs(cursor.getDouble(cursor.getColumnIndex(IncomeVsExpenseReportEntity.Expenses))));
            // titles
            int year = cursor.getInt(cursor.getColumnIndex(IncomeVsExpenseReportEntity.YEAR));

            // format month
            Calendar calendar = Calendar.getInstance();
            calendar.set(year, month - 1, 1);
            // titles
            titles.add(Integer.toString(year) + "-" + new SimpleDateFormat("MMM").format(calendar.getTime()));
        }
    }
    //compose bundle for arguments
    Bundle args = new Bundle();
    args.putDoubleArray(IncomeVsExpensesChartFragment.KEY_EXPENSES_VALUES,
            ArrayUtils.toPrimitive(expenses.toArray(new Double[0])));
    args.putDoubleArray(IncomeVsExpensesChartFragment.KEY_INCOME_VALUES,
            ArrayUtils.toPrimitive(incomes.toArray(new Double[0])));
    args.putStringArray(IncomeVsExpensesChartFragment.KEY_XTITLES, titles.toArray(new String[titles.size()]));
    //get fragment manager
    FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
    if (fragmentManager != null) {
        IncomeVsExpensesChartFragment fragment;
        fragment = (IncomeVsExpensesChartFragment) fragmentManager
                .findFragmentByTag(IncomeVsExpensesChartFragment.class.getSimpleName());
        if (fragment == null) {
            fragment = new IncomeVsExpensesChartFragment();
        }
        fragment.setChartArguments(args);
        fragment.setDisplayHomeAsUpEnabled(true);

        if (fragment.isVisible())
            fragment.onResume();

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (((IncomeVsExpensesActivity) getActivity()).mIsDualPanel) {
            fragmentTransaction.replace(R.id.fragmentChart, fragment,
                    IncomeVsExpensesChartFragment.class.getSimpleName());
        } else {
            fragmentTransaction.replace(R.id.fragmentMain, fragment,
                    IncomeVsExpensesChartFragment.class.getSimpleName());
            fragmentTransaction.addToBackStack(null);
        }
        fragmentTransaction.commit();
    }
}

From source file:com.snt.bt.recon.database.DBHandler.java

public <T> int dbSyncCount(Class<T> cl) throws InstantiationException, IllegalAccessException {
    T inst = cl.newInstance();/*  ww w .j av  a2 s. c o m*/
    String selectQuery = "";

    if (inst instanceof Trip)
        selectQuery = "SELECT * FROM " + TABLE_TRIPS + " where " + KEY_UPLOAD_STATUS + " = '" + "no" + "' or "
                + KEY_UPLOAD_STATUS + " = '" + "partial" + "'";

    else if (inst instanceof GPSLocation)
        selectQuery = "SELECT  * FROM " + TABLE_LOCATIONS + " where " + KEY_UPLOAD_STATUS + " = '" + "no" + "'";

    else if (inst instanceof BluetoothClassicEntry)
        selectQuery = "SELECT  * FROM " + TABLE_BC + " where " + KEY_UPLOAD_STATUS + " = '" + "no" + "'";

    else if (inst instanceof BluetoothLowEnergyEntry)
        selectQuery = "SELECT  * FROM " + TABLE_BLE + " where " + KEY_UPLOAD_STATUS + " = '" + "no" + "'";

    int count = 0;
    SQLiteDatabase database = this.getWritableDatabase();
    Cursor cursor = database.rawQuery(selectQuery, null);
    count = cursor.getCount();
    cursor.close();
    database.close();
    return count;
}

From source file:app.com.example.kiran.sunshine.FetchWeatherTask.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.
 * <p/>//from   www.  ja  v a  2  s . co m
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

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

        // Sort order:  Ascending, by date.
        String sortOrder = WeatherEntry.COLUMN_DATE + " ASC";
        Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate(locationSetting,
                System.currentTimeMillis());

        // Students: Uncomment the next lines to display what what you stored in the bulkInsert
        Cursor cur = mContext.getContentResolver().query(weatherForLocationUri, null, null, null, sortOrder);

        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, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted");

        //String resultStrs = convertContentValuesToUXFormat(cur);
        //return resultStrs;

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

From source file:com.bt.download.android.gui.UniversalScanner.java

private boolean documentExists(String filePath, long size) {
    boolean result = false;

    Cursor c = null;

    try {/*from  www . j  a  v a2 s . c o  m*/
        ContentResolver cr = context.getContentResolver();
        c = cr.query(UniversalStore.Documents.Media.CONTENT_URI, new String[] { DocumentsColumns._ID },
                DocumentsColumns.DATA + "=?" + " AND " + DocumentsColumns.SIZE + "=?",
                new String[] { filePath, String.valueOf(size) }, null);
        result = c != null && c.getCount() != 0;
    } catch (Throwable e) {
        LOG.warn("Error detecting if file exists: " + filePath, e);
    } finally {
        if (c != null) {
            c.close();
        }
    }

    return result;
}