List of usage examples for android.database Cursor isAfterLast
boolean isAfterLast();
From source file:com.rs.TCOfflineStatementCollection.java
/** * get all statements that haven't been posted * @param limit/*from w w w . j a v a 2s. co m*/ * @return List of LocalStatementsItem */ List<LocalStatementsItem> getUnsentStatements(int limit) { List<LocalStatementsItem> statementArray = new ArrayList<LocalStatementsItem>(); Cursor cursor; SQLiteDatabase database; TCLocalStorageDatabaseOpenHelper dbHelper; dbHelper = new TCLocalStorageDatabaseOpenHelper(appContext); database = dbHelper.getWritableDatabase(); String select = LocalStatements.POSTED_DATE + "=" + "\'" + "0" + "\'"; cursor = database.query(TCOfflineDataManager.LOCAL_STATEMENT_TABLE_NAME, null, select, null, null, null, LocalStatements.CREATE_DATE + " ASC", Integer.toString(limit)); //query for all the unposted statements cursor.moveToFirst(); //go to the beginning of the query and then loop through all the packages, adding them to the return List while (!cursor.isAfterLast()) { LocalStatementsItem thisPackage = new LocalStatementsItem(); thisPackage.id = cursor.getInt(0); thisPackage.statementId = cursor.getString(cursor.getColumnIndex("statementId")); thisPackage.statementJson = cursor.getString(cursor.getColumnIndex("statementJson")); thisPackage.createDate = cursor.getLong(cursor.getColumnIndex("createDate")); thisPackage.postedDate = cursor.getLong(cursor.getColumnIndex("postedDate")); thisPackage.querystring = cursor.getString(cursor.getColumnIndex("querystring")); statementArray.add(thisPackage); cursor.moveToNext(); } cursor.close(); database.close(); return statementArray; }
From source file:org.openbmap.soapclient.GpxExporter.java
/** * Iterates on track points and write them. * @param trackName Name of the track (metadata). * @param bw Writer to the target file./* w w w. ja v a 2s . c o m*/ * @param c Cursor to track points. * @throws IOException */ private void writeWaypoints(final int session, final BufferedWriter bw) throws IOException { Log.i(TAG, "Writing trackpoints"); Cursor c = mDbHelper.getReadableDatabase().rawQuery(WAYPOINT_SQL_QUERY, new String[] { String.valueOf(mSession), String.valueOf(0) }); final int colLatitude = c.getColumnIndex(Schema.COL_LATITUDE); final int colLongitude = c.getColumnIndex(Schema.COL_LONGITUDE); final int colAltitude = c.getColumnIndex(Schema.COL_ALTITUDE); final int colTimestamp = c.getColumnIndex(Schema.COL_TIMESTAMP); long outer = 0; while (!c.isAfterLast()) { c.moveToFirst(); //StringBuffer out = new StringBuffer(32 * 1024); while (!c.isAfterLast()) { bw.write("\t\t\t<wpt lat=\""); bw.write(String.valueOf(c.getDouble(colLatitude))); bw.write("\" "); bw.write("lon=\""); bw.write(String.valueOf(c.getDouble(colLongitude))); bw.write("\">"); bw.write("<ele>"); bw.write(String.valueOf(c.getDouble(colAltitude))); bw.write("</ele>"); bw.write("<time>"); // time stamp conversion to ISO 8601 bw.write(getGpxDate(c.getLong(colTimestamp))); bw.write("</time>"); bw.write("</wpt>\n"); c.moveToNext(); } //bw.write(out.toString()); //out = null; // fetch next CURSOR_SIZE records outer += CURSOR_SIZE; c.close(); c = mDbHelper.getReadableDatabase().rawQuery(WAYPOINT_SQL_QUERY, new String[] { String.valueOf(mSession), String.valueOf(outer) }); } c.close(); System.gc(); }
From source file:com.gelakinetic.mtgfam.helpers.updaters.DbUpdaterService.java
/** * This method does the heavy lifting. It opens transactional access to the database, checks the web for new files * to patch in, patches them as necessary, and manipulates the notification to inform the user. * * @param intent The value passed to startService(Intent), it's not used *///from ww w . j a v a2s. c om @Override public void onHandleIntent(Intent intent) { showStatusNotification(); /* Try to open up a log */ PrintWriter logWriter = null; try { if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { /* Open the log */ File logfile = new File(this.getApplicationContext().getExternalFilesDir(null), "mtgf_update.txt"); logWriter = new PrintWriter(new FileWriter(logfile)); /* Datestamp it */ logWriter.write((new Date()).toString() + '\n'); } } catch (IOException e) { /* Couldn't open log, oh well */ } try { PreferenceAdapter mPrefAdapter = new PreferenceAdapter(this); ProgressReporter reporter = new ProgressReporter(); ArrayList<String> updatedStuff = new ArrayList<>(); CardAndSetParser parser = new CardAndSetParser(); boolean commitDates = true; boolean newRulesParsed = false; try { ArrayList<MtgCard> cardsToAdd = new ArrayList<>(); ArrayList<Expansion> setsToAdd = new ArrayList<>(); ArrayList<String> setsToDrop = new ArrayList<>(); /* Look for updates with the banned / restricted lists and formats */ LegalityData legalityDatas = parser.readLegalityJsonStream(mPrefAdapter, logWriter); /* Log the date */ if (logWriter != null) { logWriter.write("mCurrentRulesDate: " + parser.mCurrentRulesTimestamp + '\n'); } /* Look for new cards */ Manifest manifest = parser.readUpdateJsonStream(logWriter); /* Log the date */ if (logWriter != null) { logWriter.write("mCurrentPatchDate: " + parser.mCurrentPatchTimestamp + '\n'); } if (manifest != null) { /* Make an arraylist of all the current set codes */ ArrayList<String> currentSetCodes = new ArrayList<>(); HashMap<String, String> storedDigests = new HashMap<>(); /* Get readable database access */ SQLiteDatabase database = DatabaseManager.getInstance(getApplicationContext(), false) .openDatabase(false); Cursor setCursor = CardDbAdapter.fetchAllSets(database); if (setCursor != null) { setCursor.moveToFirst(); while (!setCursor.isAfterLast()) { String code = setCursor.getString(setCursor.getColumnIndex(CardDbAdapter.KEY_CODE)); String digest = setCursor.getString(setCursor.getColumnIndex(CardDbAdapter.KEY_DIGEST)); storedDigests.put(code, digest); currentSetCodes.add(code); setCursor.moveToNext(); } /* Cleanup */ setCursor.close(); } DatabaseManager.getInstance(getApplicationContext(), false).closeDatabase(false); /* Look through the list of available patches, and if it doesn't exist in the database, add it. */ for (Manifest.ManifestEntry set : manifest.mPatches) { if (!set.mCode.equals("DD3")) { /* Never download the old Duel Deck Anthologies patch */ try { /* If the digest doesn't match, mark the set for dropping * and remove it from currentSetCodes so it redownloads */ if (set.mDigest != null && !storedDigests.get(set.mCode).equals(set.mDigest)) { currentSetCodes.remove(set.mCode); setsToDrop.add(set.mCode); } } catch (NullPointerException e) { /* eat it */ } if (!currentSetCodes .contains(set.mCode)) { /* check to see if the patch is known already */ int retries = 5; while (retries > 0) { try { /* Change the notification to the specific set */ switchToUpdating( String.format(getString(R.string.update_updating_set), set.mName)); InputStream streamToRead = FamiliarActivity.getHttpInputStream(set.mURL, logWriter); if (streamToRead != null) { GZIPInputStream gis = new GZIPInputStream(streamToRead); JsonReader reader = new JsonReader(new InputStreamReader(gis, "UTF-8")); parser.readCardJsonStream(reader, reporter, cardsToAdd, setsToAdd); streamToRead.close(); updatedStuff.add(set.mName); /* Everything was successful, retries = 0 breaks the while loop */ retries = 0; } } catch (IOException e) { if (logWriter != null) { logWriter.print("Retry " + retries + '\n'); e.printStackTrace(logWriter); } } retries--; } } } } } /* Change the notification to generic "checking for updates" */ switchToChecking(); /* Parse the rules * Instead of using a hardcoded string, the default lastRulesUpdate is the timestamp of when the APK was * built. This is a safe assumption to make, since any market release will have the latest database baked * in. */ long lastRulesUpdate = mPrefAdapter.getLastRulesUpdate(); RulesParser rp = new RulesParser(new Date(lastRulesUpdate), reporter); ArrayList<RulesParser.RuleItem> rulesToAdd = new ArrayList<>(); ArrayList<RulesParser.GlossaryItem> glossaryItemsToAdd = new ArrayList<>(); if (rp.needsToUpdate(logWriter)) { switchToUpdating(getString(R.string.update_updating_rules)); if (rp.parseRules(logWriter)) { rp.loadRulesAndGlossary(rulesToAdd, glossaryItemsToAdd); /* Only save the timestamp of this if the update was 100% successful; if something went screwy, we * should let them know and try again next update. */ newRulesParsed = true; updatedStuff.add(getString(R.string.update_added_rules)); } switchToChecking(); } if (logWriter != null) { logWriter.write("legalityDatas: " + ((legalityDatas == null) ? "null" : "not null") + '\n'); logWriter.write("setsToAdd: " + setsToAdd.size() + '\n'); logWriter.write("cardsToAdd: " + cardsToAdd.size() + '\n'); logWriter.write("rulesToAdd: " + rulesToAdd.size() + '\n'); logWriter.write("glossaryItemsToAdd: " + glossaryItemsToAdd.size() + '\n'); } /* Open a writable database, as briefly as possible */ if (legalityDatas != null || setsToDrop.size() > 0 || setsToAdd.size() > 0 || cardsToAdd.size() > 0 || rulesToAdd.size() > 0 || glossaryItemsToAdd.size() > 0) { SQLiteDatabase database = DatabaseManager.getInstance(getApplicationContext(), true) .openDatabase(true); /* Add all the data we've downloaded */ if (legalityDatas != null) { CardDbAdapter.dropLegalTables(database); CardDbAdapter.createLegalTables(database); for (LegalityData.Format format : legalityDatas.mFormats) { CardDbAdapter.createFormat(format.mName, database); for (String legalSet : format.mSets) { CardDbAdapter.addLegalSet(legalSet, format.mName, database); } for (String bannedCard : format.mBanlist) { CardDbAdapter.addLegalCard(bannedCard, format.mName, CardDbAdapter.BANNED, database); } for (String restrictedCard : format.mRestrictedlist) { CardDbAdapter.addLegalCard(restrictedCard, format.mName, CardDbAdapter.RESTRICTED, database); } } } /* Drop any out of date sets */ for (String code : setsToDrop) { CardDbAdapter.dropSetAndCards(code, database); } /* Add set data */ for (Expansion set : setsToAdd) { CardDbAdapter.createSet(set, database); /* Add the corresponding TCG name */ CardDbAdapter.addTcgName(set.mName_tcgp, set.mCode_gatherer, database); /* Add the corresponding foil information */ CardDbAdapter.addFoilInfo(set.mCanBeFoil, set.mCode_gatherer, database); } /* Add cards */ for (MtgCard card : cardsToAdd) { CardDbAdapter.createCard(card, database); } /* Add stored rules */ if (rulesToAdd.size() > 0 || glossaryItemsToAdd.size() > 0) { CardDbAdapter.dropRulesTables(database); CardDbAdapter.createRulesTables(database); } for (RulesParser.RuleItem rule : rulesToAdd) { CardDbAdapter.insertRule(rule.category, rule.subcategory, rule.entry, rule.text, rule.position, database); } for (RulesParser.GlossaryItem term : glossaryItemsToAdd) { CardDbAdapter.insertGlossaryTerm(term.term, term.definition, database); } /* Close the writable database */ DatabaseManager.getInstance(getApplicationContext(), true).closeDatabase(true); } } catch (FamiliarDbException e1) { commitDates = false; /* don't commit the dates */ if (logWriter != null) { e1.printStackTrace(logWriter); } } /* Parse the MTR and IPG */ MTRIPGParser mtrIpgParser = new MTRIPGParser(mPrefAdapter, this); if (mtrIpgParser.performMtrIpgUpdateIfNeeded(MTRIPGParser.MODE_MTR, logWriter)) { updatedStuff.add(getString(R.string.update_added_mtr)); } if (logWriter != null) { logWriter.write("MTR date: " + mtrIpgParser.mPrettyDate + '\n'); } if (mtrIpgParser.performMtrIpgUpdateIfNeeded(MTRIPGParser.MODE_IPG, logWriter)) { updatedStuff.add(getString(R.string.update_added_ipg)); } if (logWriter != null) { logWriter.write("IPG date: " + mtrIpgParser.mPrettyDate + '\n'); } if (mtrIpgParser.performMtrIpgUpdateIfNeeded(MTRIPGParser.MODE_JAR, logWriter)) { updatedStuff.add(getString(R.string.update_added_jar)); } if (logWriter != null) { logWriter.write("JAR date: " + mtrIpgParser.mPrettyDate + '\n'); } /* If everything went well so far, commit the date and show the update complete notification */ if (commitDates) { parser.commitDates(mPrefAdapter); long curTime = new Date().getTime(); mPrefAdapter.setLastLegalityUpdate((int) (curTime / 1000)); if (newRulesParsed) { mPrefAdapter.setLastRulesUpdate(curTime); } if (updatedStuff.size() > 0) { showUpdatedNotification(updatedStuff); } } } catch (Exception e) { /* Generally pokemon handling is bad, but I don't want miss anything */ if (logWriter != null) { e.printStackTrace(logWriter); } } /* Always cancel the status notification */ cancelStatusNotification(); /* close the log */ if (logWriter != null) { logWriter.close(); } }
From source file:liqui.droid.activity.Base.java
public boolean isResultEmpty(Uri uri, String selection, String[] selectionArgs, String orderBy) { boolean empty; Cursor c = getContentResolver().query(uri, null, selection, selectionArgs, orderBy); c.moveToFirst();//from w w w. jav a2 s .c o m if (c.isAfterLast()) { empty = true; } else { empty = false; } c.close(); return empty; }
From source file:com.andrew.apollo.utils.MusicUtils.java
/** * Permanently deletes item(s) from the user's device. * * @param context The {@link Context} to use. * @param list The item(s) to delete.//from w w w . ja v a2 s .com */ public static void deleteTracks(final Context context, final long[] list, boolean showNotification) { if (list == null) { return; } final String[] projection = new String[] { BaseColumns._ID, MediaColumns.DATA, AudioColumns.ALBUM_ID }; final StringBuilder selection = new StringBuilder(); selection.append(BaseColumns._ID + " IN ("); for (int i = 0; i < list.length; i++) { selection.append(list[i]); if (i < list.length - 1) { selection.append(","); } } selection.append(")"); final Cursor c = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, selection.toString(), null, null); if (c != null) { // Step 1: Remove selected tracks from the current playlist, as well // as from the album art cache c.moveToFirst(); while (!c.isAfterLast()) { // Remove from current playlist. final long id = c.getLong(0); removeTrack(id); // Remove from the favorites playlist. FavoritesStore.getInstance(context).removeItem(id); // Remove any items in the recent's database RecentStore.getInstance(context).removeItem(c.getLong(2)); // Remove from all remaining playlists. removeSongFromAllPlaylists(context, id); c.moveToNext(); } // Step 2: Remove selected tracks from the database context.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, selection.toString(), null); // Step 3: Remove files from card FileSystem fs = Platforms.fileSystem(); c.moveToFirst(); while (!c.isAfterLast()) { final String name = c.getString(1); try { // File.delete can throw a security exception final File f = new File(name); if (!fs.delete(f)) { // I'm not sure if we'd ever get here (deletion would // have to fail, but no exception thrown) Log.e("MusicUtils", "Failed to delete file " + name); } c.moveToNext(); } catch (final Throwable ex) { c.moveToNext(); } } c.close(); UIUtils.broadcastAction(context, Constants.ACTION_FILE_ADDED_OR_REMOVED, new UIUtils.IntentByteExtra(Constants.EXTRA_REFRESH_FILE_TYPE, Constants.FILE_TYPE_AUDIO)); } if (showNotification) { try { final String message = makeLabel(context, R.plurals.NNNtracksdeleted, list.length); AppMsg.makeText(context, message, AppMsg.STYLE_CONFIRM).show(); } catch (Throwable ignored) { } } // We deleted a number of tracks, which could affect any number of // things // in the media content domain, so update everything. context.getContentResolver().notifyChange(Uri.parse("content://media"), null); // Notify the lists to update refresh(); }
From source file:com.nookdevs.library.FictionwiseBooks.java
public Vector<String> searchDescription(String keyword) { Vector<String> str = new Vector<String>(); try {/*from www .ja v a2 s. c o m*/ if (m_Db == null) { m_Db = getReadableDatabase(); } String selection; selection = "where desc like '%" + keyword + "%'"; String sql = "select ean from books " + selection; Cursor cursor = m_Db.rawQuery(sql, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { str.add(cursor.getString(0)); cursor.moveToNext(); } cursor.close(); } catch (Exception ex) { Log.e("BNBooks", "Exception searching fictionwise books description ", ex); } return str; }
From source file:com.nookdevs.library.FictionwiseBooks.java
public String getDescription(String ean) { String desc = null;/*from www.j a v a 2s . co m*/ boolean createddb = false; try { if (m_Db == null) { m_Db = getReadableDatabase(); createddb = true; } String query = "select desc from books"; Cursor cursor = m_Db.rawQuery(query, null); cursor.moveToFirst(); if (!cursor.isAfterLast()) desc = cursor.getString(0); } catch (Exception ex) { Log.e("FictionwiseBooks", "Exception querying book desc", ex); } finally { if (createddb) { m_Db.close(); m_Db = null; } } return desc; }
From source file:com.nookdevs.library.FictionwiseBooks.java
public String getKeywordsString(String ean) { String keywordStr = null;//from w w w . ja va 2 s . c o m try { if (m_Db == null) { m_Db = getReadableDatabase(); } String selection; String[] selectionArgs = null; selection = " where ean=?"; selectionArgs = new String[1]; selectionArgs[0] = ean; String sql = "select keywords from books " + selection; Cursor cursor = m_Db.rawQuery(sql, selectionArgs); cursor.moveToFirst(); if (!cursor.isAfterLast()) keywordStr = cursor.getString(0); cursor.close(); } catch (Exception ex) { Log.e("FictionwiseBooks", "Exception loading books keywords Str for " + ean, ex); } return keywordStr; }
From source file:com.aengbee.android.leanback.ui.MainFragment.java
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { final int loaderId = loader.getId(); if (loaderId == CATEGORY_LOADER) { // Every time we have to re-get the category loader, we must re-create the sidebar. mCategoryRowAdapter.clear(); // Iterate through each category entry and add it to the ArrayAdapter. while (!data.isAfterLast()) { int categoryIndex = data.getColumnIndex(VideoContract.VideoEntry.COLUMN_CATEGORY); String category = data.getString(categoryIndex); // Create header for this category. HeaderItem header = new HeaderItem(category); int videoLoaderId = category.hashCode(); // Create unique int from category. CursorObjectAdapter existingAdapter = mVideoCursorAdapters.get(videoLoaderId); if (existingAdapter == null) { // Map video results from the database to Video objects. CursorObjectAdapter videoCursorAdapter = new CursorObjectAdapter(new CardPresenter()); videoCursorAdapter.setMapper(new VideoCursorMapper()); mVideoCursorAdapters.put(videoLoaderId, videoCursorAdapter); ListRow row = new ListRow(header, videoCursorAdapter); mCategoryRowAdapter.add(row); // Start loading the videos from the database for a particular category. Bundle args = new Bundle(); args.putString(VideoContract.VideoEntry.COLUMN_CATEGORY, category); getLoaderManager().initLoader(videoLoaderId, args, this); } else { ListRow row = new ListRow(header, existingAdapter); mCategoryRowAdapter.add(row); }/*w w w . ja v a2 s. co m*/ data.moveToNext(); } // Create a row for this special case with more samples. HeaderItem gridHeader = new HeaderItem(getString(R.string.more_samples)); GridItemPresenter gridPresenter = new GridItemPresenter(this); ArrayObjectAdapter gridRowAdapter = new ArrayObjectAdapter(gridPresenter); gridRowAdapter.add(getString(R.string.personal_settings)); /* SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); try { JSONObject serverJson = new JSONObject(sharedPreferences.getString("serverList", "NULL")); if(serverJson!=null && !serverJson.equals("{}")) { if( serverJson.getString(serverJson.names().getString(0)).contains("http://fytoz.asuscomm.com/android-tv/ky.json")||serverJson.getString(serverJson.names().getString(0)).contains("http://fytoz.asuscomm.com/android-tv/tj.json")) { gridRowAdapter.add("Showcase"); gridRowAdapter.add(getString(R.string.grid_view)); gridRowAdapter.add(getString(R.string.guidedstep_first_title)); gridRowAdapter.add(getString(R.string.error_fragment)); } } } catch (JSONException ex) { ex.printStackTrace(); } gridRowAdapter.add("Showcase"); gridRowAdapter.add(getString(R.string.grid_view)); gridRowAdapter.add(getString(R.string.guidedstep_first_title)); gridRowAdapter.add(getString(R.string.error_fragment)); */ ListRow row = new ListRow(gridHeader, gridRowAdapter); mCategoryRowAdapter.add(row); startEntranceTransition(); // TODO: Move startEntranceTransition to after all // cursors have loaded. } else { // The CursorAdapter contains a Cursor pointing to all videos. mVideoCursorAdapters.get(loaderId).changeCursor(data); } } else { if (isOnline()) { Intent serviceIntent = new Intent(getActivity(), FetchVideoService.class); //serviceIntent.putExtra("data_url", getResources().getString(R.string.catalog_url) ); serviceIntent.putExtra("data_url", "http://fytoz.asuscomm.com/android-tv/tjweb.json"); getActivity().startService(serviceIntent); } else { Intent serviceIntent = new Intent(getActivity(), FetchVideoService.class); //serviceIntent.putExtra("data_url", getResources().getString(R.string.catalog_url) ); serviceIntent.putExtra("data_url", resourceToUri(getActivity(), R.raw.sample).toString()); getActivity().startService(serviceIntent); } } }
From source file:com.samknows.measurement.storage.DBHelper.java
public JSONArray getAverageResults(long starttime, long endtime, List<Integer> test_batches) { synchronized (sync) { open();//www .ja va 2 s . c om JSONArray ret = new JSONArray(); String selection = String.format("dtime BETWEEN %d AND %d AND success <> 0", starttime, endtime); if (test_batches != null && test_batches.size() == 0) { return ret; } if (test_batches != null) { selection += " AND " + getInClause(SKSQLiteHelper.TR_COLUMN_BATCH_ID, test_batches); } String averageColumn = String.format("AVG(%s)", SKSQLiteHelper.TR_COLUMN_RESULT); String[] columns = { SKSQLiteHelper.TR_COLUMN_TYPE, averageColumn, "COUNT(*)" }; String groupBy = SKSQLiteHelper.TR_COLUMN_TYPE; Cursor cursor = database.query(SKSQLiteHelper.TABLE_TESTRESULT, columns, selection, null, groupBy, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { JSONObject curr = new JSONObject(); try { int test_type_id = TestResult.testStringToId(cursor.getString(0)); curr.put(AVERAGEDATA_TYPE, test_type_id + ""); curr.put(AVERAGEDATA_VALUE, TestResult.hrResult(test_type_id, cursor.getDouble(1))); } catch (JSONException je) { } ret.put(curr); cursor.moveToNext(); } cursor.close(); close(); return ret; } }