List of usage examples for android.database Cursor getLong
long getLong(int columnIndex);
From source file:com.samknows.measurement.storage.DBHelper.java
public JSONObject getArchiveData(int index) { synchronized (sync) { open();// w w w . j av a 2 s . com JSONObject ret = new JSONObject(); String limit = index + "," + 1; Cursor cursor = database.query(SKSQLiteHelper.TABLE_TESTBATCH, SKSQLiteHelper.TABLE_TESTBATCH_ALLCOLUMNS, null, null, null, null, SKSQLiteHelper.TEST_BATCH_ORDER, limit); if (cursor == null) { close(); return null; } if (!cursor.moveToFirst()) { cursor.close(); close(); return null; } long test_batch_id = cursor.getLong(0); long test_batch_time = cursor.getLong(1); cursor.close(); String selection = SKSQLiteHelper.TR_COLUMN_BATCH_ID + " = " + test_batch_id; List<JSONObject> tests = getTestResults(selection); List<JSONObject> passive_metrics = getPassiveMetrics(test_batch_id); JSONArray j_tests = new JSONArray(); JSONArray j_pm = new JSONArray(); try { ret.put(ARCHIVEDATA_INDEX, index + ""); ret.put(ARCHIVEDATA_DTIME, test_batch_time + ""); for (JSONObject jo : tests) { j_tests.put(testResultToArchiveData(jo)); } for (JSONObject jo : passive_metrics) { j_pm.put(passiveMetricToArchiveData(jo)); } ret.put(ARCHIVEDATA_ACTIVEMETRICS, j_tests); ret.put(ARCHIVEDATA_PASSIVEMETRICS, j_pm); } catch (JSONException je) { Logger.e(DBHelper.class, "Error in converting tests and passive metrics for archive data" + je.getMessage()); } close(); return ret; } }
From source file:com.ichi2.libanki.Finder.java
private String _findDupes(String val) { // caller must call stripHTMLMedia on passed val String[] split = val.split(",", 1); if (split.length != 2) { return null; }// w w w . j av a2 s. c om String mid = split[0]; val = split[1]; String csum = Long.toString(Utils.fieldChecksum(val)); List<Long> nids = new ArrayList<Long>(); Cursor cur = null; try { cur = mCol.getDb().getDatabase().rawQuery("select id, flds from notes where mid=? and csum=?", new String[] { mid, csum }); long nid = cur.getLong(0); String flds = cur.getString(1); if (Utils.stripHTMLMedia(Utils.splitFields(flds)[0]) == val) { nids.add(nid); } } finally { if (cur != null) { cur.close(); } } return "n.id in " + Utils.ids2str(nids); }
From source file:net.kourlas.voipms_sms.Database.java
/** * Gets all of the messages associated with the specified contact phone number, except for deleted messages. * * @param contact The contact phone number. * @return All of the messages associated with the specified contact phone number, except for deleted messages. *///from www . j av a 2s. c om public synchronized Conversation getConversation(String did, String contact) { List<Message> messages = new ArrayList<>(); Cursor cursor = database.query(TABLE_MESSAGE, columns, COLUMN_CONTACT + "=" + contact + " AND " + COLUMN_DID + "=" + did + " AND " + COLUMN_DELETED + "=" + "0", null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { Message message = new Message(cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_DATABASE_ID)), cursor.isNull(cursor.getColumnIndexOrThrow(COLUMN_VOIP_ID)) ? null : cursor.getLong(cursor.getColumnIndex(COLUMN_VOIP_ID)), cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_DATE)), cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_TYPE)), cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_DID)), cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_CONTACT)), cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_MESSAGE)), cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_UNREAD)), cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_DELETED)), cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_DELIVERED)), cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_DELIVERY_IN_PROGRESS))); messages.add(message); cursor.moveToNext(); } cursor.close(); Message[] messageArray = new Message[messages.size()]; messages.toArray(messageArray); return new Conversation(messageArray); }
From source file:com.xorcode.andtweet.TweetListActivity.java
@Override public boolean onContextItemSelected(MenuItem item) { super.onContextItemSelected(item); AdapterView.AdapterContextMenuInfo info; try {//from ww w . j a v a 2 s . c o m info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return false; } mCurrentId = info.id; Uri uri; Cursor c; switch (item.getItemId()) { case CONTEXT_MENU_ITEM_REPLY: uri = ContentUris.withAppendedId(Tweets.CONTENT_URI, info.id); c = getContentResolver().query(uri, new String[] { Tweets._ID, Tweets.AUTHOR_ID }, null, null, null); try { c.moveToFirst(); String reply = "@" + c.getString(c.getColumnIndex(Tweets.AUTHOR_ID)) + " "; long replyId = c.getLong(c.getColumnIndex(Tweets._ID)); mTweetEditor.startEditing(reply, replyId); } catch (Exception e) { Log.e(TAG, "onContextItemSelected: " + e.toString()); return false; } finally { if (c != null && !c.isClosed()) c.close(); } return true; case CONTEXT_MENU_ITEM_RETWEET: uri = ContentUris.withAppendedId(Tweets.CONTENT_URI, info.id); c = getContentResolver().query(uri, new String[] { Tweets._ID, Tweets.AUTHOR_ID, Tweets.MESSAGE }, null, null, null); try { c.moveToFirst(); StringBuilder message = new StringBuilder(); String reply = "RT @" + c.getString(c.getColumnIndex(Tweets.AUTHOR_ID)) + " "; message.append(reply); CharSequence text = c.getString(c.getColumnIndex(Tweets.MESSAGE)); int len = 140 - reply.length() - 3; if (text.length() < len) { len = text.length(); } message.append(text, 0, len); if (message.length() == 137) { message.append("..."); } mTweetEditor.startEditing(message.toString(), 0); } catch (Exception e) { Log.e(TAG, "onContextItemSelected: " + e.toString()); return false; } finally { if (c != null && !c.isClosed()) c.close(); } return true; case CONTEXT_MENU_ITEM_DESTROY_STATUS: sendCommand(new CommandData(CommandEnum.DESTROY_STATUS, mCurrentId)); return true; case CONTEXT_MENU_ITEM_FAVORITE: sendCommand(new CommandData(CommandEnum.CREATE_FAVORITE, mCurrentId)); return true; case CONTEXT_MENU_ITEM_DESTROY_FAVORITE: sendCommand(new CommandData(CommandEnum.DESTROY_FAVORITE, mCurrentId)); return true; case CONTEXT_MENU_ITEM_SHARE: uri = ContentUris.withAppendedId(Tweets.CONTENT_URI, info.id); c = getContentResolver().query(uri, new String[] { Tweets._ID, Tweets.AUTHOR_ID, Tweets.MESSAGE }, null, null, null); try { c.moveToFirst(); StringBuilder subject = new StringBuilder(); StringBuilder text = new StringBuilder(); String message = c.getString(c.getColumnIndex(Tweets.MESSAGE)); subject.append(getText(R.string.button_create_tweet)); subject.append(" - " + message); int maxlength = 80; if (subject.length() > maxlength) { subject.setLength(maxlength); // Truncate at the last space subject.setLength(subject.lastIndexOf(" ")); subject.append("..."); } text.append(message); text.append("\n-- \n" + c.getString(c.getColumnIndex(Tweets.AUTHOR_ID))); text.append("\n URL: " + "http://twitter.com/" + c.getString(c.getColumnIndex(Tweets.AUTHOR_ID)) + "/status/" + c.getString(c.getColumnIndex(Tweets._ID))); Intent share = new Intent(android.content.Intent.ACTION_SEND); share.setType("text/plain"); share.putExtra(Intent.EXTRA_SUBJECT, subject.toString()); share.putExtra(Intent.EXTRA_TEXT, text.toString()); startActivity(Intent.createChooser(share, getText(R.string.menu_item_share))); } catch (Exception e) { Log.e(TAG, "onContextItemSelected: " + e.toString()); return false; } finally { if (c != null && !c.isClosed()) c.close(); } return true; case CONTEXT_MENU_ITEM_UNFOLLOW: case CONTEXT_MENU_ITEM_BLOCK: case CONTEXT_MENU_ITEM_DIRECT_MESSAGE: case CONTEXT_MENU_ITEM_PROFILE: Toast.makeText(this, R.string.unimplemented, Toast.LENGTH_SHORT).show(); return true; } return false; }
From source file:com.rs.TCOfflineStatementCollection.java
/** * get all statements that haven't been posted * @param limit/* w w w. j a va 2 s . 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:com.textuality.lifesaver2.Columns.java
public JSONObject cursorToJSON(Cursor cursor) { setColumns(cursor);// w ww . ja va2 s .c om JSONObject json = new JSONObject(); try { for (int i = 0; i < mNames.length; i++) { int col = mColumns[i]; if (cursor.isNull(col)) continue; switch (mTypes[i]) { case STRING: String str = cursor.getString(col); if (mNames[i].equals("number")) { json.put("name", mNameFinder.find(str)); } else if (mNames[i].equals("address")) { str = PhoneNumberUtils.formatNumber(str); str = PhoneNumberUtils.stripSeparators(str); json.put("name", mNameFinder.find(str)); } json.put(mNames[i], str); break; case INT: json.put(mNames[i], cursor.getInt(col)); break; case LONG: long val = cursor.getLong(col); json.put(mNames[i], val); if (mNames[i].equals("date")) { json.put("tzoffset", mTZ.getOffset(val)); } break; case FLOAT: json.put(mNames[i], cursor.getFloat(col)); break; case DOUBLE: json.put(mNames[i], cursor.getDouble(col)); break; } } } catch (JSONException e) { throw new RuntimeException(e); } return json; }
From source file:net.exclaimindustries.geohashdroid.wiki.WikiPictureEditor.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_PICTURE) { if (data != null) { Uri uri = data.getData();// w w w.ja v a 2s .c o m // If the uri's null, we failed. Don't change anything. if (uri != null) { Cursor cursor; cursor = getContentResolver().query(uri, new String[] { MediaStore.Images.ImageColumns.DATA, MediaStore.Images.ImageColumns.LATITUDE, MediaStore.Images.ImageColumns.LONGITUDE, MediaStore.Images.ImageColumns.DATE_TAKEN }, null, null, null); cursor.moveToFirst(); mCurrentFile = cursor.getString(0); mPictureDate = cursor.getLong(3); // These two could very well be null or empty. Nothing // wrong with that. But if they're good, make a Location // out of them. String lat = cursor.getString(1); String lon = cursor.getString(2); try { double llat = Double.parseDouble(lat); double llon = Double.parseDouble(lon); mPictureLocation = new Location(""); mPictureLocation.setLatitude(llat); mPictureLocation.setLongitude(llon); } catch (Exception ex) { // If we get an exception, we got it because of the // number parser. Assume it's invalid. mPictureLocation = null; } cursor.close(); } } else { mPictureLocation = null; mPictureDate = -1; } // Always rebuild the thumbnail and reset submit, just in case. buildThumbnail(); setThumbnail(); resetSubmitButton(); updateCoords(); // We'll decode the bitmap at upload time so as not to keep a // potentially big chunky Bitmap around at all times. } }
From source file:com.ichi2.libanki.Media.java
private Pair<List<String>, List<String>> _changes() { Map<String, Object[]> cache = new HashMap<String, Object[]>(); Cursor cur = null; try {/*from w ww.j ava 2 s . c o m*/ cur = mDb.getDatabase().rawQuery("select fname, csum, mtime from media where csum is not null", null); while (cur.moveToNext()) { String name = cur.getString(0); String csum = cur.getString(1); Long mod = cur.getLong(2); cache.put(name, new Object[] { csum, mod, false }); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (cur != null) { cur.close(); } } List<String> added = new ArrayList<String>(); List<String> removed = new ArrayList<String>(); // loop through on-disk files for (File f : new File(dir()).listFiles()) { // ignore folders and thumbs.db if (f.isDirectory()) { continue; } String fname = f.getName(); if (fname.equalsIgnoreCase("thumbs.db")) { continue; } // and files with invalid chars if (hasIllegal(fname)) { continue; } // empty files are invalid; clean them up and continue long sz = f.length(); if (sz == 0) { f.delete(); continue; } if (sz > 100 * 1024 * 1024) { mCol.log("ignoring file over 100MB", f); continue; } // check encoding String normf = HtmlUtil.nfcNormalized(fname); if (!fname.equals(normf)) { // wrong filename encoding which will cause sync errors File nf = new File(dir(), normf); if (nf.exists()) { f.delete(); } else { f.renameTo(nf); } } // newly added? if (!cache.containsKey(fname)) { added.add(fname); } else { // modified since last time? if (_mtime(f.getAbsolutePath()) != (Long) cache.get(fname)[1]) { // and has different checksum? if (!_checksum(f.getAbsolutePath()).equals(cache.get(fname)[0])) { added.add(fname); } } // mark as used cache.get(fname)[2] = true; } } // look for any entries in the cache that no longer exist on disk for (String fname : cache.keySet()) { if (!((Boolean) cache.get(fname)[2])) { removed.add(fname); } } return new Pair<List<String>, List<String>>(added, removed); }
From source file:com.hichinaschool.flashcards.libanki.sync.Syncer.java
/** * Deletions ******************************************************************** *///from w w w .jav a 2 s . c o m private JSONObject removed() { JSONArray cards = new JSONArray(); JSONArray notes = new JSONArray(); JSONArray decks = new JSONArray(); Cursor cur = null; try { cur = mCol.getDb().getDatabase().rawQuery( "SELECT oid, type FROM graves WHERE usn" + (mCol.getServer() ? (" >= " + mMinUsn) : (" = -1")), null); while (cur.moveToNext()) { int type = cur.getInt(1); switch (type) { case Sched.REM_CARD: cards.put(cur.getLong(0)); break; case Sched.REM_NOTE: notes.put(cur.getLong(0)); break; case Sched.REM_DECK: decks.put(cur.getLong(0)); break; } } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } if (!mCol.getServer()) { mCol.getDb().execute("UPDATE graves SET usn=" + mMaxUsn + " WHERE usn=-1"); } JSONObject o = new JSONObject(); try { o.put("cards", cards); o.put("notes", notes); o.put("decks", decks); } catch (JSONException e) { throw new RuntimeException(e); } return o; }
From source file:com.google.ytd.SubmitActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.submit); this.authorizer = new GlsAuthorizer.GlsAuthorizerFactory().getAuthorizer(this, GlsAuthorizer.YOUTUBE_AUTH_TOKEN_TYPE); dbHelper = new DbHelper(this); dbHelper = dbHelper.open();// w w w.jav a2s .c o m Intent intent = this.getIntent(); this.videoUri = intent.getData(); this.ytdDomain = intent.getExtras().getString(DbHelper.YTD_DOMAIN); this.assignmentId = intent.getExtras().getString(DbHelper.ASSIGNMENT_ID); this.title = intent.getExtras().getString(DbHelper.DESCRIPTION); this.instructions = intent.getExtras().getString(DbHelper.INSTRUCTIONS); this.domainHeader = (TextView) this.findViewById(R.id.domainHeader); domainHeader.setText(SettingActivity.getYtdDomains(this).get(this.ytdDomain)); this.preferences = this.getSharedPreferences(MainActivity.SHARED_PREF_NAME, Activity.MODE_PRIVATE); this.youTubeName = preferences.getString(DbHelper.YT_ACCOUNT, null); final Button submitButton = (Button) findViewById(R.id.submitButton); submitButton.setEnabled(false); submitButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showDialog(DIALOG_LEGAL); } }); Button cancelButton = (Button) findViewById(R.id.cancelButton); cancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }); EditText titleEdit = (EditText) findViewById(R.id.submitTitle); titleEdit.setText(title); titleEdit.setEnabled(false); enableSubmitIfReady(); EditText descriptionEdit = (EditText) findViewById(R.id.submitDescription); descriptionEdit.setText(instructions); descriptionEdit.setEnabled(false); Cursor cursor = this.managedQuery(this.videoUri, null, null, null, null); if (cursor.getCount() == 0) { Log.d(LOG_TAG, "not a valid video uri"); Toast.makeText(SubmitActivity.this, "not a valid video uri", Toast.LENGTH_LONG).show(); } else { getVideoLocation(); if (cursor.moveToFirst()) { long id = cursor.getLong(cursor.getColumnIndex(Video.VideoColumns._ID)); this.dateTaken = new Date(cursor.getLong(cursor.getColumnIndex(Video.VideoColumns.DATE_TAKEN))); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm aaa"); Configuration userConfig = new Configuration(); Settings.System.getConfiguration(getContentResolver(), userConfig); Calendar cal = Calendar.getInstance(userConfig.locale); TimeZone tz = cal.getTimeZone(); dateFormat.setTimeZone(tz); TextView dateTakenView = (TextView) findViewById(R.id.dateCaptured); dateTakenView.setText("Date captured: " + dateFormat.format(dateTaken)); ImageView thumbnail = (ImageView) findViewById(R.id.thumbnail); ContentResolver crThumb = getContentResolver(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 1; Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(crThumb, id, MediaStore.Video.Thumbnails.MICRO_KIND, options); thumbnail.setImageBitmap(curThumb); } } }