List of usage examples for android.database Cursor getCount
int getCount();
From source file:com.ptts.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.// w w w. j ava 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 updateLocalFeedData(final InputStream stream, final SyncResult syncResult) throws IOException, JSONException, RemoteException, OperationApplicationException, ParseException { final FeedParserJson feedParser = new FeedParserJson(); final ContentResolver contentResolver = getContext().getContentResolver(); Log.i(TAG, "Parsing stream as Json feed"); final List<FeedParserJson.Entry> entries = feedParser.parse(stream); Log.i(TAG, "Parsing complete. Found " + entries.size() + " entries"); ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Build hash table of incoming entries HashMap<String, FeedParserJson.Entry> entryMap = new HashMap<String, FeedParserJson.Entry>(); for (FeedParserJson.Entry e : entries) { entryMap.put(e.id, e); } // Get list of all items Log.i(TAG, "Fetching local entries for merge"); Uri uri = FeedContract.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 name; String start; String end; String stops; while (c.moveToNext()) { syncResult.stats.numEntries++; id = c.getInt(COLUMN_ID); entryId = c.getString(COLUMN_ENTRY_ID); name = c.getString(COLUMN_NAME); start = c.getString(COLUMN_START); end = c.getString(COLUMN_END); stops = c.getString(COLUMN_STOPS); Log.i("STOPS FROM PROJECTION", stops); FeedParserJson.Entry 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 Uri existingUri = FeedContract.Entry.CONTENT_URI.buildUpon().appendPath(Integer.toString(id)) .build(); if ((match.name != null && !match.name.equals(name)) || (match.start != null && !match.start.equals(start)) || (match.stops != null && !match.stops.equals(stops)) || (match.end != end)) { Log.i("STOPS FROM HASHMAP", match.stops); if (!match.stops.equals(stops)) { Log.i("COMPARING PROJECTION " + match.stops + " & HASHMAP " + stops, "The two aren't equal"); } else { Log.i("COMPARING PROJECTION & HASHMAP", "The two are equal"); } // Update existing record Log.i(TAG, "Scheduling update: " + existingUri); batch.add(ContentProviderOperation.newUpdate(existingUri) .withValue(FeedContract.Entry.COLUMN_NAME_ENTRY_ID, entryId) .withValue(FeedContract.Entry.COLUMN_NAME_NAME, name) .withValue(FeedContract.Entry.COLUMN_NAME_START, start) .withValue(FeedContract.Entry.COLUMN_NAME_END, end) .withValue(FeedContract.Entry.COLUMN_NAME_STOPS, stops).build()); syncResult.stats.numUpdates++; } else { Log.i(TAG, "No action: " + existingUri); } } else { // Entry doesn't exist. Remove it from the database. Uri deleteUri = FeedContract.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 (FeedParserJson.Entry e : entryMap.values()) { Log.i(TAG, "Scheduling insert: entry_id=" + e.id); batch.add(ContentProviderOperation.newInsert(FeedContract.Entry.CONTENT_URI) .withValue(FeedContract.Entry.COLUMN_NAME_ENTRY_ID, e.id) .withValue(FeedContract.Entry.COLUMN_NAME_NAME, e.name) .withValue(FeedContract.Entry.COLUMN_NAME_START, e.start) .withValue(FeedContract.Entry.COLUMN_NAME_END, e.end) .withValue(FeedContract.Entry.COLUMN_NAME_STOPS, e.stops).build()); syncResult.stats.numInserts++; } Log.i(TAG, "Merge solution ready. Applying batch update"); mContentResolver.applyBatch(FeedContract.CONTENT_AUTHORITY, batch); mContentResolver.notifyChange(FeedContract.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:de.lebenshilfe_muenster.uk_gebaerden_muensterland.database.SignDAO.java
private Sign readSingleSign(long id) { final Sign createdSign; final Cursor cursor = this.database.query(DbContract.SignTable.TABLE_NAME, DbContract.SignTable.ALL_COLUMNS, DbContract.SignTable._ID + DbContract.EQUAL_SIGN + id, null, null, null, null); if (0 == cursor.getCount()) { throw new IllegalStateException( MessageFormat.format("Querying for sign with id: {1} " + "yielded no results!", id)); }//from w ww. jav a2 s . co m cursor.moveToFirst(); createdSign = cursorToSign(cursor); cursor.close(); return createdSign; }
From source file:ch.sebastienzurfluh.swissmuseumguides.contentprovider.model.io.connectors.LocalConnector.java
/** * @param groupId or use -1 if you want to get all pages' menus. *//*from ww w . j av a2 s .c o m*/ @Override public Cursor getPagesMenusInGroup(int groupId) { String query = "SELECT " + MenusContract.ID + " AS \"_id\", " // Cursor needs _id + MenusContract.TITLE + ", " + MenusContract.DESCRIPTION + ", " + MenusContract.THUMB_IMG_URL + ", " + MenusContract.IMG_URL + ", " + AffiliationsContract.PAGE_ID + ", " // we want to differentiate page_id from _id + AffiliationsContract.ORDER + " FROM " + PagesContract.TABLE_NAME + ", " + MenusContract.TABLE_NAME + ", " + AffiliationsContract.TABLE_NAME + " WHERE " + PagesContract.ID + "=" + AffiliationsContract.PAGE_ID; if (groupId >= 0) query += " AND " + AffiliationsContract.GROUP_ID + "=?"; query += " AND " + MenusContract.ID + "=" + PagesContract.MENU_ID + " ORDER BY " + AffiliationsContract.ORDER + ";"; String[] groupIdArgs = (groupId >= 0) ? new String[] { String.valueOf(groupId) } : new String[] {}; Cursor cursor = getReadableDatabase().rawQuery(query, groupIdArgs); // cursor has the links to the resources, but we want to include the resource in the // cursor! if (!(cursor.moveToFirst()) || cursor.getCount() == 0) { System.out.println("LocalConnector: CURSOR IS EMPTY!!!"); } return cursor; }
From source file:com.guess.license.plate.Task.LoadingTaskConn.java
private ServerError insOrUpDB(JSONObject jsObj, String objJS, String[] columns, String whereClause, String[] whereArgs, ContentValues values, int serverVersion) throws JSONException { ServerError result = ServerError.NO_ERROR; Cursor cursor = db.query(objJS, columns, whereClause, whereArgs, null, null, null); int count = cursor.getCount(); if (count > 0) { // Getting the version int currDBVersion = 0; while (cursor.moveToNext()) { if (cursor.isNull(0)) currDBVersion = 0;/*from w w w . ja va 2s . c om*/ else currDBVersion = cursor.getInt(0); } if (objJS.equals(WebConf.JSON_OBJECTS[0])) { if (currDBVersion == serverVersion) { return ServerError.OLD_BUILD; } db.update(objJS, values, whereClause, whereArgs); } else if (objJS.equals(WebConf.JSON_OBJECTS[1])) { // In case the plate processed is a new version update it in the DB if (currDBVersion != serverVersion) { db.update(objJS, values, whereClause, whereArgs); } } else if (objJS.equals(WebConf.JSON_OBJECTS[2])) { // In case the language processed is a new version update it in the DB if (currDBVersion != serverVersion) { db.update(objJS, values, whereClause, whereArgs); } } } else { db.insert(objJS, null, values); } return result; }
From source file:edu.gatech.ppl.cycleatlanta.TripUploader.java
@Override protected Boolean doInBackground(Long... tripid) { // First, send the trip user asked for: Boolean result = true;// w w w. ja va 2 s . c o m if (tripid.length != 0) { result = uploadOneTrip(tripid[0]); } // Then, automatically try and send previously-completed trips // that were not sent successfully. Vector<Long> unsentTrips = new Vector<Long>(); mDb.openReadOnly(); Cursor cur = mDb.fetchUnsentTrips(); if (cur != null && cur.getCount() > 0) { // pd.setMessage("Sent. You have previously unsent trips; submitting those now."); while (!cur.isAfterLast()) { unsentTrips.add(Long.valueOf(cur.getLong(0))); cur.moveToNext(); } cur.close(); } mDb.close(); for (Long trip : unsentTrips) { result &= uploadOneTrip(trip); } return result; }
From source file:com.yuntongxun.ecdemo.storage.IMessageSqlManager.java
/** * ?/*from w w w . ja v a 2s .co m*/ * * @return */ public static List<ECMessage> getDowndFailMsg() { String sql = "select * from " + DatabaseHelper.TABLES_NAME_IM_MESSAGE + " where msgType=" + ECMessage.Type.IMAGE.ordinal() + " and box_type=2 and userData is null"; Cursor cursor = null; List<ECMessage> al = null; try { cursor = getInstance().sqliteDB().rawQuery(sql, null); if (cursor != null && cursor.getCount() > 0) { al = new ArrayList<ECMessage>(); while (cursor.moveToNext()) { ECMessage ecMessage = packageMessage(cursor); if (ecMessage == null) { continue; } al.add(0, ecMessage); } } } catch (Exception e) { LogUtil.e(TAG + " " + e.toString()); e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); cursor = null; } } return al; }
From source file:com.cloudmine.api.db.RequestDBOpenHelper.java
/** * Load all of the unsynced requests, and set their status to in progress. * @return//from w w w . j a va 2s . co m */ private Cursor loadRequestTableContentsForUpdating() { SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { String[] unsychronizedSelectionArgs = { UNSYCHRONIZED.toString() }; Cursor cursor = db.query(BOTH_DATABASE_TABLE_JOIN, RESULTS_COLUMNS, SYNCHRONIZED_VALUE_WHERE, unsychronizedSelectionArgs, null, null, requestColumn(KEY_REQUEST_ID)); cursor.getCount(); //For some reason, accessing the cursor count before performing the update is required for the load to work. Doesn't make much sense unless it is ignoring order. ContentValues updatedValues = getUpdateSynchronizedContentValues(IN_PROGRESS); db.update(REQUEST_DATABASE_TABLE, updatedValues, SYNCHRONIZED_VALUE_WHERE, unsychronizedSelectionArgs); db.setTransactionSuccessful(); return cursor; } catch (Throwable t) { throw new RuntimeException(t); } finally { db.endTransaction(); } }
From source file:com.seneca.android.senfitbeta.DbHelper.java
public ArrayList<Muscle> getMuscles() { Log.d("MUSCLE_GET", "Geting muscles"); String fetchMus = "select * from " + RIP_TABLE + " ORDER BY " + RIP_NAME + " ASC"; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(fetchMus, null); cursor.moveToFirst();/*from ww w .j a v a 2s .c o m*/ if (cursor == null) { Log.d("exiting", "NOTHING"); } if (cursor.getCount() == 0) { Log.d("NOTHING", "0 nothing"); } ArrayList<Muscle> temp = new ArrayList<Muscle>(); cursor.moveToFirst(); do { Muscle ex = new Muscle(); ex.setId(cursor.getInt(cursor.getColumnIndex(RIP_ID))); ex.setName(cursor.getString(cursor.getColumnIndex(RIP_NAME))); temp.add(ex); } while (cursor.moveToNext()); cursor.close(); getReadableDatabase().close(); return temp; }
From source file:com.blandware.android.atleap.test.RobospiceTestCase.java
public void test_books_authors_tables_sql() throws Exception { Book.BooksResult result = makeRobospiceRequest(BOOKS_FILENAME, new BooksAuthorsRobospiceRequest()); assertTrue(result.resultCode == 100); assertTrue(result.getBooks() != null); assertTrue(result.getBooks().size() == 2); assertTrue(result.getBooks().toArray(new Book[0])[0].getAuthors() != null); assertTrue(result.getBooks().toArray(new Book[0])[0].getAuthors().size() == 2); assertTrue(result.getBooks().toArray(new Book[0])[0].getTags() != null); assertTrue(result.getBooks().toArray(new Book[0])[0].getTags().size() == 2); assertTrue(result.getBooks().toArray(new Book[0])[0].getPublisherTitle() != null); assertTrue(result.getBooks().toArray(new Book[0])[0].getPublisherUrl() != null); assertTrue(result.getBooks().toArray(new Book[0])[1].getAuthors() != null); assertTrue(result.getBooks().toArray(new Book[0])[1].getAuthors().size() == 2); assertTrue(result.getBooks().toArray(new Book[0])[1].getTags() != null); assertTrue(result.getBooks().toArray(new Book[0])[1].getTags().size() == 2); assertTrue(result.getBooks().toArray(new Book[0])[1].getPublisherTitle() != null); assertTrue(result.getBooks().toArray(new Book[0])[1].getPublisherUrl() != null); Cursor cursor = getContext().getContentResolver().query(TestContract.CONTENT_URI_BOOKS_AUTHORS1, //uri BOOKS_AUTHORS_PROJECTION, //projection null, //selection null, //selectionArgs null //sort order );//w w w . j a va2 s. c om assertTrue(cursor != null); assertTrue(cursor.getCount() == 4); }
From source file:com.example.cmput301.model.DatabaseManager.java
private boolean localIdExists(String id) { Cursor c = db.rawQuery( "SELECT * FROM " + StringRes.LOCAL_TASK_TABLE_NAME + " WHERE " + StringRes.COL_ID + "=?", new String[] { id, }); if (c == null || c.getCount() == 0) { return false; }//ww w . j a va 2 s . c o m return true; }