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.yuntongxun.ecdemo.storage.IMessageSqlManager.java

/**
 * //w w w. j av  a2  s . c  om
 *
 * @return
 */
public static int qureyAllSessionUnreadCount() {
    int count = 0;
    String[] columnsList = { "sum(" + IThreadColumn.UNREAD_COUNT + ")" };
    Cursor cursor = null;
    try {
        cursor = getInstance().sqliteDB().query(DatabaseHelper.TABLES_NAME_IM_SESSION, columnsList, null, null,
                null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                count = cursor.getInt(cursor.getColumnIndex("sum(" + IThreadColumn.UNREAD_COUNT + ")"));
            }
        }
    } catch (Exception e) {
        LogUtil.e(TAG + " " + e.toString());
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return count;
}

From source file:br.com.oromar.dev.android.sunshine.FetchWeatherTask.java

@Override
protected Void doInBackground(String... params) {

    // If there's no zip code, there's nothing to look up.  Verify size of params.
    if (params.length == 0) {
        return null;
    }/*from   w ww .j a va2  s.  c om*/
    String locationQuery = params[0];

    // These two need to be declared outside the try/catch
    // so that they can be closed in the finally block.
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    // Will contain the raw JSON response as a string.
    String forecastJsonStr = null;

    String format = "json";
    String units = "metric";
    int numDays = 14;

    String location = Utility.getPreferredLocation(mContext);
    Uri weatherUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(location,
            System.currentTimeMillis());
    String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC ";
    Cursor cur = mContext.getContentResolver().query(weatherUri, ForecastAdapter.FORECAST_COLUMNS, null, null,
            sortOrder);

    if (cur.getCount() < numDays) {

        try {
            // Construct the URL for the OpenWeatherMap query
            // Possible parameters are avaiable at OWM's forecast API page, at
            // http://openweathermap.org/API#forecast
            final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
            final String QUERY_PARAM = "q";
            final String FORMAT_PARAM = "mode";
            final String UNITS_PARAM = "units";
            final String DAYS_PARAM = "cnt";
            final String APP_ID_PARAM = "APPID";

            Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0])
                    .appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units)
                    .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
                    .appendQueryParameter(APP_ID_PARAM, APPID).build();

            URL url = new URL(builtUri.toString());

            // Create the request to OpenWeatherMap, and open the connection
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // Read the input stream into a String
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                // But it does make debugging a *lot* easier if you print out the completed
                // buffer for debugging.
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                // Stream was empty.  No point in parsing.
                return null;
            }
            forecastJsonStr = buffer.toString();
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error ", e);
            // If the code didn't successfully get the weather data, there's no point in attemping
            // to parse it.
            return null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e(LOG_TAG, "Error closing stream", e);
                }
            }
        }

        try {
            getWeatherDataFromJson(forecastJsonStr, locationQuery);
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
            e.printStackTrace();
        }
    }
    // This will only happen if there was an error getting or parsing the forecast.
    return null;
}

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

/**
 * ????// www  . j  av  a 2s .c  o  m
 *
 * @return
 */
public static int qureyIMCountForSession(long threadId) {
    int count = 0;
    String[] columnsList = { "count(*)" };
    String where = IMessageColumn.OWN_THREAD_ID + " = " + threadId + " and " + IMessageColumn.BOX_TYPE
            + " != 3";
    Cursor cursor = null;
    try {
        cursor = getInstance().sqliteDB().query(DatabaseHelper.TABLES_NAME_IM_MESSAGE, columnsList, where, null,
                null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                count = cursor.getInt(cursor.getColumnIndex("count(*)"));
            }
        }
    } catch (Exception e) {
        LogUtil.e(TAG + " " + e.toString());
    } finally {
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
    }
    return count;
}

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

public static String qureyVideoMsgLength(String msgId) {
    String count = null;//from ww  w . ja v  a 2 s.  c  om
    String where = IMessageColumn.MESSAGE_ID + " = '" + msgId + "' ";
    Cursor cursor = null;
    try {

        cursor = getInstance().sqliteDB().rawQuery("select * from im_message where msgid=?",
                new String[] { String.valueOf(msgId) });

        if (cursor != null && cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                count = cursor.getString(cursor.getColumnIndex(IMessageColumn.BODY));
            }
        }
    } catch (Exception e) {
        LogUtil.e(TAG + " " + e.toString());
    } finally {
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
    }
    return count;
}

From source file:com.weimed.app.sync.SyncAdapter.java

/**
 * Read JSON from an input stream, storing it into the content provider.
 *
 * <p>This is where incoming data is persisted, committing the results of a sync. In order to
 * minimize (expensive) disk operations, we compare incoming data with what's already in our
 * database, and compute a merge. Only changes (insert/update/delete) will result in a database
 * write./*  ww  w . j av  a  2  s.c  o m*/
 *
 * <p>As an additional optimization, we use a batch operation to perform all database writes at
 * once.
 *
 * <p>Merge strategy:
 * 1. Get cursor to all items in feed<br/>
 * 2. For each item, check if it's in the incoming data.<br/>
 *    a. YES: Remove from "incoming" list. Check if data has mutated, if so, perform
 *            database UPDATE.<br/>
 *    b. NO: Schedule DELETE from database.<br/>
 * (At this point, incoming database only contains missing items.)<br/>
 * 3. For any items remaining in incoming list, ADD to database.
 */
public void updateLocalJSONData(final InputStream stream, final SyncResult syncResult)
        throws IOException, JSONException, RemoteException, OperationApplicationException, ParseException {
    final JSONParser JSONParser = new JSONParser();
    final ContentResolver contentResolver = getContext().getContentResolver();

    Log.i(TAG, "Parsing stream as JSON Array");
    final JSONObject json = JSONParser.parseJSONObject(stream);
    Log.i(TAG, "Parsing complete. Found " + json.getInt("total_rows") + " entries");

    ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();

    // Build hash table of incoming entries
    HashMap<String, JSONObject> entryMap = new HashMap<String, JSONObject>();
    final JSONArray entries = json.getJSONArray("rows");
    for (int i = 0; i < json.getInt("total_rows"); i++) {
        JSONObject e = entries.getJSONObject(i).getJSONObject("value");
        entryMap.put(e.getString("_id"), e);
    }

    // Get list of all items
    Log.i(TAG, "Fetching local entries for merge");
    Uri uri = NewsContract.Entry.CONTENT_URI; // Get all entries
    Cursor c = contentResolver.query(uri, PROJECTION, null, null, null);
    assert c != null;
    Log.i(TAG, "Found " + c.getCount() + " local entries. Computing merge solution...");

    // Find stale data
    int id;
    String entryId;
    String title;
    String content;
    String publisher;
    String picurl;
    String originalurl;
    String createdat;
    String updatedat;
    String publishedat;

    while (c.moveToNext()) {
        syncResult.stats.numEntries++;
        id = c.getInt(COLUMN_ID);
        entryId = c.getString(COLUMN_ENTRY_ID);
        title = c.getString(COLUMN_TITLE);
        content = c.getString(COLUMN_CONTENT);
        publisher = c.getString(COLUMN_PUBLISHER);
        picurl = c.getString(COLUMN_PICURL);
        originalurl = c.getString(COLUMN_ORIGINALURL);
        createdat = c.getString(COLUMN_CREATEDAT);
        updatedat = c.getString(COLUMN_UPDATEDAT);
        publishedat = c.getString(COLUMN_PUBLISHEDAT);
        JSONObject match = entryMap.get(entryId);
        //            if (match != null) {
        // Entry exists. Remove from entry map to prevent insert later.
        //                entryMap.remove(entryId);
        // Check to see if the entry needs to be updated
        // How to know update local or remote? updatedAt! which is newer, update another.
        //                Uri existingUri = NewsContract.Entry.CONTENT_URI.buildUpon()
        //                                              .appendPath(Integer.toString(id)).build();
        //                if ((match.getString("title") != null && !match.getString("title").equals(title)) ||
        //                    (match.getString("content") != null && !match.getString("content").equals(content)) ||
        //                    (match.getString("publisher") != null && !match.getString("publisher").equals(publisher)) ||
        //                    (match.getString("picurl") != null && !match.getString("picurl").equals(picurl)) ||
        //                    (match.getString("originalurl") != null && !match.getString("originalurl").equals(originalurl)) ||
        //                    (match.getString("createdat") != null && !match.getString("createdat").equals(createdat)) ||
        //                    (match.getString("updatedat") != null && !match.getString("updatedat").equals(updatedat)) ||
        //                    (match.getString("publishedat") != null && !match.getString("publishedat").equals(publishedat))
        //                   ) {
        //                    // Update existing record
        //                    Log.i(TAG, "Scheduling update: " + existingUri);
        //                    batch.add(ContentProviderOperation.newUpdate(existingUri)
        //                         .withValue(NewsContract.Entry.COLUMN_TITLE, title)
        //                         .withValue(NewsContract.Entry.COLUMN_CONTENT, content)
        //                         .withValue(NewsContract.Entry.COLUMN_PUBLISHER, publisher)
        //                         .withValue(NewsContract.Entry.COLUMN_PICURL, picurl)
        //                         .withValue(NewsContract.Entry.COLUMN_ORIGINALURL, originalurl)
        //                         .withValue(NewsContract.Entry.COLUMN_CREATEDAT, createdat)
        //                         .withValue(NewsContract.Entry.COLUMN_UPDATEDAT, updatedat)
        //                         .withValue(NewsContract.Entry.COLUMN_PUBLISHEDAT, publishedat)
        //                         .build());
        //                    syncResult.stats.numUpdates++;
        //                } else {
        //                    Log.i(TAG, "No action: " + existingUri);
        //                }
        //            } else {
        // Entry doesn't exist. Remove it from the database.
        Uri deleteUri = NewsContract.Entry.CONTENT_URI.buildUpon().appendPath(Integer.toString(id)).build();
        Log.i(TAG, "Scheduling delete: " + deleteUri);
        batch.add(ContentProviderOperation.newDelete(deleteUri).build());
        syncResult.stats.numDeletes++;
        //            }
    }
    c.close();

    // Add new items
    for (JSONObject e : entryMap.values()) {
        Log.i(TAG, "Scheduling insert: entry_id=" + e.getString("_id"));
        batch.add(ContentProviderOperation.newInsert(NewsContract.Entry.CONTENT_URI)
                .withValue(NewsContract.Entry.COLUMN_ENTRY_ID, e.getString("_id"))
                .withValue(NewsContract.Entry.COLUMN_TITLE, e.getString("title"))
                .withValue(NewsContract.Entry.COLUMN_CONTENT,
                        fetchTextFileToString(NEWS_URL_BASE + '/' + e.getString("_id") + "/content.md"))
                .withValue(NewsContract.Entry.COLUMN_PUBLISHER, e.getString("publisher"))
                .withValue(NewsContract.Entry.COLUMN_PICURL, e.has("pic_link") ? e.getString("pic_link") : null)
                .withValue(NewsContract.Entry.COLUMN_ORIGINALURL, e.getString("origin_link"))
                .withValue(NewsContract.Entry.COLUMN_CREATEDAT, e.getString("created_at"))
                .withValue(NewsContract.Entry.COLUMN_UPDATEDAT, e.getString("updated_at"))
                .withValue(NewsContract.Entry.COLUMN_PUBLISHEDAT, e.getString("publish_at")).build());
        syncResult.stats.numInserts++;
    }
    Log.i(TAG, "Merge solution ready. Applying batch update");
    mContentResolver.applyBatch(NewsContract.CONTENT_AUTHORITY, batch);
    mContentResolver.notifyChange(NewsContract.Entry.CONTENT_URI, // URI where data was modified
            null, // No local observer
            false); // IMPORTANT: Do not sync to network
    // This sample doesn't support uploads, but if *your* code does, make sure you set
    // syncToNetwork=false in the line above to prevent duplicate syncs.
}

From source file:com.photon.phresco.nativeapp.eshop.activity.CategoryListActivity.java

/**
 * Search the category version number in local database. Update the category
 * version number with AppVersionNo read from AppConfig JSON, if it's
 * present, Else insert the AppVersionNo as category version number in
 * database//from ww w . j av a 2 s  . c  o m
 *
 * @throws IllegalArgumentException
 * @throws NumberFormatException
 */
private void searchCategoryVersionNoInLocalDatabase() {
    try {
        AppConfiguration appConf = new AppConfiguration(((PhrescoApp) getApplication()).getDatabase());

        // Check if categoryVersionNo is stored in local database
        Cursor searchCategoryVersionRow = appConf.searchAllRow("category_version");

        if (searchCategoryVersionRow.getCount() > 0) {
            updateCategoryVersionNoInLocalDatabase(appConf, searchCategoryVersionRow);
        } else {
            insertCategoryVersionNoInLocalDatabase(appConf);
        }
    } catch (Exception ex) {
        PhrescoLogger.info(TAG + " buildCategoryListAdapter - Exception " + ex.toString());
        PhrescoLogger.warning(ex);
    }
}

From source file:cn.apputest.ctria.service.UploadFailRecordService.java

public void uploadrecord() {
    Cursor cars = mgr.queryTheCursorCarsFailUpload();
    List<CarsFailUploadDataEntity> list_c = new ArrayList<CarsFailUploadDataEntity>();

    if (cars.getCount() != 0) {
        System.out.println("???");
        while (cars.moveToNext()) {
            CarsFailUploadDataEntity carsfailupload = new CarsFailUploadDataEntity();
            carsfailupload.setUserID(cars.getString(cars.getColumnIndex("userID")));
            carsfailupload.setBaseStationID(cars.getString(cars.getColumnIndex("baseStationID")));
            carsfailupload.setIsOverWeight(cars.getString(cars.getColumnIndex("isOverWeight")));
            carsfailupload.setStatus4PermitRunCert(cars.getString(cars.getColumnIndex("status4PermitRunCert")));
            carsfailupload.setStatus4TransportCert_Head(
                    cars.getString(cars.getColumnIndex("status4TransportCert_Head")));
            carsfailupload.setStatus4TransportCert_Tail(
                    cars.getString(cars.getColumnIndex("status4TransportCert_Tail")));
            carsfailupload.setStatus4InsuranceCert_Head(
                    cars.getString(cars.getColumnIndex("status4InsuranceCert_Head")));
            carsfailupload.setStatus4InsuranceCert_Cargo(
                    cars.getString(cars.getColumnIndex("status4InsuranceCert_Cargo")));
            carsfailupload.setStatus4InsuranceCert_Tail(
                    cars.getString(cars.getColumnIndex("status4InsuranceCert_Tail")));
            carsfailupload.setStatus4SpecialEquipUsage(
                    cars.getString(cars.getColumnIndex("status4SpecialEquipUsage")));
            carsfailupload.setPlateNumber(cars.getString(cars.getColumnIndex("plateNumber")));
            carsfailupload.setID(cars.getInt(cars.getColumnIndex("ID")));
            list_c.add(carsfailupload);// w  w w.ja v a2s .  c o m
        }
        cars.close();
        for (CarsFailUploadDataEntity carsFailUploadDataEntity : list_c) {
            postcarcheckrecord(carsFailUploadDataEntity);
            if (IsOK) {
                mgr.DeleteCarsFailUpload(carsFailUploadDataEntity.getID());
                System.out.println("?");
            }
        }
    } else {
        System.out.println("???");
    }
    /**
     * ?
     */

    Cursor people = mgr.queryTheCursorPeopleFailUpload();
    List<PeopleFailUploadDataEntity> list_p = new ArrayList<PeopleFailUploadDataEntity>();

    if (people.getCount() != 0) {
        System.out.println("???");
        while (people.moveToNext()) {
            PeopleFailUploadDataEntity peoplefailupload = new PeopleFailUploadDataEntity();
            peoplefailupload.setUserID(people.getString(people.getColumnIndex("userID")));
            peoplefailupload.setBaseStationID(people.getString(people.getColumnIndex("baseStationID")));
            peoplefailupload
                    .setStatus4DriverLicense(people.getString(people.getColumnIndex("status4DriverLicense")));
            peoplefailupload.setStatus4JobCert(people.getString(people.getColumnIndex("status4JobCert")));
            peoplefailupload.setID(people.getInt(people.getColumnIndex("ID")));
            peoplefailupload.setDriverName(people.getString(people.getColumnIndex("driverName")));
            list_p.add(peoplefailupload);
        }
        people.close();
        for (PeopleFailUploadDataEntity peopleFailUploadDataEntity : list_p) {
            postpersoncheckrecord(peopleFailUploadDataEntity);
            if (IsOK) {

                mgr.DeletePeopleFailUpload(peopleFailUploadDataEntity.getID());
                System.out.println("?");
            }
        }

    } else {
        System.out.println("???");
    }
    //      stopSelf();
}

From source file:com.girnarsoft.android.shunshine.FetchWeatherTask.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName A human-readable city name, e.g "Mountain View"
 * @param lat the latitude of the city//from   ww w. j  ava  2 s .c  om
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
public long addLocation(String locationSetting, String cityName, double lat, double lon) {

    Cursor cursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI, null,
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + "=?", new String[] { locationSetting },
            null);

    long location = 0;

    if (cursor.getCount() > 0) {
        cursor.moveToFirst();
        location = cursor.getLong(cursor.getColumnIndex(WeatherContract.LocationEntry._ID));
    } else {
        ContentValues values = new ContentValues();
        values.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        values.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        values.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        values.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        Uri uri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI, values);

        location = ContentUris.parseId(uri);
    }

    return location;
}

From source file:com.money.manager.ex.database.MmxOpenHelper.java

private void initCategories(SQLiteDatabase database) {
    try {/*from  w  w  w .  j a  va2  s . c  om*/
        Cursor countCategories = database.rawQuery("SELECT * FROM CATEGORY_V1", null);
        if (countCategories == null || countCategories.getCount() > 0)
            return;

        int keyCategory = 0;
        String[] categories = new String[] { "1;1", "2;1", "3;1", "4;1", "5;1", "6;1", "7;1", "8;2", "9;2",
                "10;3", "11;3", "12;3", "13;4", "14;4", "15;4", "16;4", "17;5", "18;5", "19;5", "20;6", "21;6",
                "22;6", "23;7", "24;7", "25;7", "26;7", "27;7", "28;8", "29;8", "30;8", "31;8", "32;9", "33;9",
                "34;9", "35;10", "36;10", "37;10", "38;10", "39;13", "40;13", "41;13" };

        for (String item : categories) {
            int subCategoryId = Integer.parseInt(item.substring(0, item.indexOf(";")));
            int categoryId = Integer.parseInt(item.substring(item.indexOf(";") + 1));

            if (categoryId != keyCategory) {
                keyCategory = categoryId;
                int idStringCategory = mContext.getResources().getIdentifier(
                        "category_" + Integer.toString(categoryId), "string", mContext.getPackageName());

                if (idStringCategory > 0) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(Category.CATEGID, categoryId);
                    contentValues.put(Category.CATEGNAME, mContext.getString(idStringCategory));

                    // Update existing records, inserted via the db creation script.
                    int updated = database.update(CategoryRepository.tableName, contentValues,
                            Category.CATEGID + "=?", new String[] { Integer.toString(categoryId) });
                    if (updated <= 0) {
                        Timber.w("updating %s for category %s", contentValues.toString(),
                                Integer.toString(categoryId));
                    }
                }
            }

            int idStringSubcategory = mContext.getResources().getIdentifier(
                    "subcategory_" + Integer.toString(subCategoryId), "string", mContext.getPackageName());
            if (idStringSubcategory > 0) {
                ContentValues contentValues = new ContentValues();
                contentValues.put(Subcategory.SUBCATEGID, subCategoryId);
                contentValues.put(Subcategory.CATEGID, categoryId);
                contentValues.put(Subcategory.SUBCATEGNAME, mContext.getString(idStringSubcategory));

                int updated = database.update(SubcategoryRepository.tableName, contentValues,
                        Subcategory.SUBCATEGID + "=?", new String[] { Integer.toString(subCategoryId) });
                if (updated <= 0) {
                    Timber.w("update failed, %s for subcategory %s", contentValues.toString(),
                            Integer.toString(subCategoryId));
                }
            }
        }

        countCategories.close();
    } catch (Exception e) {
        Timber.e(e, "init database, categories");
    }
}

From source file:me.kartikarora.transfersh.activities.TransferActivity.java

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

    if (mAdapter != null)
        mAdapter.swapCursor(data);/*from   w  w w  .  ja  v  a 2s.  c om*/
    else
        mAdapter = new FileGridAdapter(TransferActivity.this, data, mTracker);
    mFileItemsGridView.setAdapter(mAdapter);
    mAdapter.notifyDataSetChanged();
    updateWidgets();

    if (null != data && data.getCount() == 0) {
        mFileItemsGridView.setVisibility(View.GONE);
        mNoFilesTextView.setVisibility(View.VISIBLE);
    } else {
        mFileItemsGridView.setVisibility(View.VISIBLE);
        mNoFilesTextView.setVisibility(View.GONE);
    }

}