List of usage examples for android.database Cursor getColumnName
String getColumnName(int columnIndex);
From source file:org.mozilla.gecko.tests.BaseTest.java
public boolean CursorMatches(Cursor c, ContentValues cv) { for (int i = 0; i < c.getColumnCount(); i++) { String column = c.getColumnName(i); if (cv.containsKey(column)) { mAsserter.info("Comparing", "Column values for: " + column); Object value = cv.get(column); if (value == null) { if (!c.isNull(i)) { return false; }//from w w w.ja v a2s.c o m } else { if (c.isNull(i) || !value.toString().equals(c.getString(i))) { return false; } } } } return true; }
From source file:ibme.sleepap.history.ViewHistory.java
/** Called when the activity is first created. */ @Override//from w w w . j av a 2s. c o m protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.view_history); dbHelper = new DatabaseHelper(this); database = dbHelper.getWritableDatabase(); Cursor cursor = database.query(HistoryTable.TABLE_NAME, HistoryTable.ALL_COLUMNS, null, null, null, null, HistoryTable.COLUMN_START_DATE); String[] fromColumns = { HistoryTable.COLUMN_START_DATE_DISPLAY, HistoryTable.COLUMN_ODI, HistoryTable.COLUMN_QUESTIONNAIRE, HistoryTable.COLUMN_SVM_RESULT }; int[] toViews = { R.id.date, R.id.odi, R.id.questionnaire, R.id.svm }; if (cursor.getCount() > 0) { findViewById(R.id.noHistoryFound).setVisibility(View.GONE); SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.history_item, cursor, fromColumns, toViews, 0); adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { TextView textView = (TextView) view; String name = cursor.getColumnName(columnIndex); if (name.equals(HistoryTable.COLUMN_ODI)) { String odi = cursor.getString(columnIndex); textView.setText(odi); if (odi.equals("-")) { return true; } float odival = Float.parseFloat(odi); int color; if (odival < 5) { color = 0xFF00FF00; } else { color = 0xFFFF0000; } textView.setTextColor(color); return true; } if (name.equals(HistoryTable.COLUMN_QUESTIONNAIRE)) { String stopBangScore = cursor.getString(columnIndex); textView.setText(stopBangScore); if (stopBangScore.equals("-")) { return true; } int stopBangScoreVal = Integer.parseInt(stopBangScore); int color; if (stopBangScoreVal < 3) { color = 0xFF00FF00; } else { color = 0xFFFF0000; } textView.setTextColor(color); return true; } if (name.equals(HistoryTable.COLUMN_SVM_RESULT)) { String svmScore = cursor.getString(columnIndex); if (svmScore.equals("-")) { textView.setText(svmScore); return true; } Float stopBangScoreVal = Float.parseFloat(svmScore); textView.setText(String.format("%.0f%%", stopBangScoreVal * 100)); int color; if (stopBangScoreVal < 0.5) { color = 0xFF00FF00; } else { color = 0xFFFF0000; } textView.setTextColor(color); return true; } return false; } }); ListView listView = (ListView) findViewById(R.id.historyList); listView.setAdapter(adapter); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(ViewHistory.this, ViewAnalysis.class); intent.putExtra(Constants.EXTRA_RECORDING_ID, id); startActivity(intent); overridePendingTransition(R.anim.enteringfromright, R.anim.exitingtoleft); } }); } else { findViewById(R.id.columnHeadings).setVisibility(View.GONE); } }
From source file:com.jinrustar.sky.main.MainActivity.java
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 0x57 && resultCode == Activity.RESULT_OK) { content = data.getExtras().getString("result"); if (!TextUtils.isEmpty(content)) { connect();//from w w w . ja v a 2s . c o m // Toast.makeText(context, "ip:"+content, Toast.LENGTH_SHORT).show(); } } if (requestCode == 0x88 && resultCode == Activity.RESULT_OK) { // VideoInfo info = new VideoInfo(); VideoInfo info = (VideoInfo) data.getExtras().getSerializable("videoinfo"); itemClick(info); } if (requestCode == 0x55 && resultCode == Activity.RESULT_OK) { Uri uri = data.getData(); Cursor cursor = this.getContentResolver().query(uri, null, null, null, null); cursor.moveToFirst(); for (int i = 0; i < cursor.getColumnCount(); i++) {// ?uri??? System.out.println(i + "-" + cursor.getColumnName(i) + "-" + cursor.getString(i)); } //Intent Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(uri, "image/*"); // intent.setData(uri); startActivity(intent); } else if (requestCode == 0x56 && resultCode == Activity.RESULT_OK) { Uri uri = data.getData(); Cursor cursor = this.getContentResolver().query(uri, null, null, null, null); cursor.moveToFirst(); for (int i = 0; i < cursor.getColumnCount(); i++) {// ?uri??? System.out.println(i + "-" + cursor.getColumnName(i) + "-" + cursor.getString(i)); } //Intent Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(uri, "video/*"); // intent.setData(uri); startActivity(intent); } }
From source file:eu.operando.operandoapp.database.DatabaseHelper.java
public List<String> getStatistics() { SQLiteDatabase db = DatabaseHelper.this.getWritableDatabase(); List<String> result = new ArrayList(); Cursor c = db.rawQuery("SELECT * FROM " + TABLE_STATISTICS + " WHERE " + KEY_ID + " = 1", null); if (c.moveToFirst()) { for (int i = 1; i < c.getColumnCount(); i++) { //omit column 0 result.add(filterName(c.getColumnName(i)) + ": " + c.getInt(i) + (c.getInt(i) == 1 ? " time." : " times.")); }//w w w .java2 s . c o m } return result; }
From source file:org.restcomm.android.olympus.MessageFragment.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Use MessageActivity intent to retrieve the contact name final Intent intent = getActivity().getIntent(); String contactName = intent.getStringExtra(RCDevice.EXTRA_DID).replaceAll("^sip:", "").replaceAll("@.*$", "");/* ww w. java2s .co m*/ //listFragment = (MessageFragment) getSupportFragmentManager().findFragmentById(R.id.message_list); //Bundle args = new Bundle(); //args.putString("contact-name", shortname); //listFragment.setArguments(args); /* Bundle args = getArguments(); String contactName = args.getString("contact-name"); */ DatabaseManager.getInstance().open(getActivity().getApplicationContext()); // TODO: this must be done in the background Cursor cursor = DatabaseManager.getInstance().retrieveMessages(contactName); String[] fromColumns = { DatabaseContract.ContactEntry.COLUMN_NAME_NAME, DatabaseContract.MessageEntry.COLUMN_NAME_TEXT, DatabaseContract.MessageEntry.COLUMN_NAME_DELIVERY_STATUS }; int[] toViews = { R.id.message_username, R.id.message_text, R.id.message_status }; listViewAdapter = new SimpleCursorAdapter(getActivity().getApplicationContext(), R.layout.message_row_layout, cursor, fromColumns, toViews, 0); // Use a binder for the delivery status column which doesn't map 1-on-1 with the view: status in the db is an integer, while in the view it's a string listViewAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if (cursor.getColumnName(columnIndex) .equals(DatabaseContract.MessageEntry.COLUMN_NAME_DELIVERY_STATUS)) { TextView deliveryStatusView = (TextView) view; if (cursor.getString(cursor.getColumnIndex(DatabaseContract.MessageEntry.COLUMN_NAME_TYPE)) .equals("local")) { int deliveryStatus = cursor.getInt(columnIndex); if (deliveryStatus == DatabaseContract.MessageDeliveryStatus.TEXT_MESSAGE_PENDING .ordinal()) { deliveryStatusView.setText("..."); deliveryStatusView.setTextColor( ContextCompat.getColor(getActivity(), R.color.colorTextSecondary)); } else if (deliveryStatus == DatabaseContract.MessageDeliveryStatus.TEXT_MESSAGE_FAILED .ordinal()) { deliveryStatusView.setText("Failed"); deliveryStatusView .setTextColor(ContextCompat.getColor(getActivity(), R.color.colorError)); } else { deliveryStatusView.setText("Success"); deliveryStatusView.setTextColor( ContextCompat.getColor(getActivity(), R.color.colorTextSecondary)); } } else { // remote message deliveryStatusView.setText(""); } return true; } if (cursor.getColumnName(columnIndex).equals(DatabaseContract.ContactEntry.COLUMN_NAME_NAME)) { TextView usernameView = (TextView) view; if (cursor.getString(cursor.getColumnIndex(DatabaseContract.MessageEntry.COLUMN_NAME_TYPE)) .equals("local")) { usernameView.setText("Me"); return true; } } return false; } }); setListAdapter(listViewAdapter); }
From source file:com.ichi2.anki.tests.ContentProviderTest.java
/** * Check that a valid Cursor is returned when querying notes table with non-default projections *///ww w . j a v a 2 s . c o m public void testQueryNotesProjection() { final ContentResolver cr = getContext().getContentResolver(); // Query all available notes for (int i = 0; i < FlashCardsContract.Note.DEFAULT_PROJECTION.length; i++) { String[] projection = removeFromProjection(FlashCardsContract.Note.DEFAULT_PROJECTION, i); final Cursor allNotesCursor = cr.query(FlashCardsContract.Note.CONTENT_URI, projection, "tag:" + TEST_TAG, null, null); assertNotNull("Check that there is a valid cursor", allNotesCursor); try { assertEquals("Check number of results", mCreatedNotes.size(), allNotesCursor.getCount()); // Check columns assertEquals("Check column count", projection.length, allNotesCursor.getColumnCount()); for (int j = 0; j < projection.length; j++) { assertEquals("Check column name " + j, projection[j], allNotesCursor.getColumnName(j)); } } finally { allNotesCursor.close(); } } }
From source file:com.example.android.network.sync.basicsyncadapter.SyncAdapter.java
/** * Read XML 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./*from w ww . j a v 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 updateLocalFeedData(final InputStream stream, final SyncResult syncResult) throws IOException, XmlPullParserException, RemoteException, OperationApplicationException, ParseException { final ContentResolver contentResolver = getContext().getContentResolver(); Log.i(TAG, "Parsing stream as Atom feed"); final List<Transformer> entries = null; /*=this.parseTransformersResponse(stream)*/; ; Log.i(TAG, "Parsing complete. Found " + entries.size() + " entries"); ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Build hash table of incoming entries HashMap<String, Transformer> entryMap = new HashMap<String, Transformer>(); for (Transformer e : entries) { entryMap.put(e.transformerID, e); } Cursor c = null; try { // Get list of all items Log.i(TAG, "Fetching local entries for merge"); Uri uri = Transformer.CONTENT_URI; // Get all entries c = contentResolver.query(uri, null, null, null, null); assert c != null; Log.i(TAG, "Found " + c.getCount() + " local entries. Computing merge solution..."); } catch (Exception ex) { } // Find stale data String id; String name; String location; while (c.moveToNext()) { syncResult.stats.numEntries++; id = c.getColumnName(COLUMN_ID); name = c.getString(COLUMN_ENTRY_ID); location = c.getString(COLUMN_TITLE); Transformer match = entryMap.get(id); if (match != null) { // Entry exists. Remove from entry map to prevent insert later. entryMap.remove(id); // Check to see if the entry needs to be updated Uri existingUri = Transformer.CONTENT_URI.buildUpon().appendPath(id).build(); if ((match.trsName != null && !match.trsLocation.equals(name))) { // Update existing record Log.i(TAG, "Scheduling update: " + existingUri); batch.add(ContentProviderOperation.newUpdate(existingUri).withValue(Transformer.KEY_NAME, name) .withValue(Transformer.KEY_LOCATION, location) .build()); syncResult.stats.numUpdates++; } else { Log.i(TAG, "No action: " + existingUri); } } else { // Entry doesn't exist. Remove it from the database. Uri deleteUri = Transformer.CONTENT_URI.buildUpon().appendPath(id).build(); Log.i(TAG, "Scheduling delete: " + deleteUri); batch.add(ContentProviderOperation.newDelete(deleteUri).build()); syncResult.stats.numDeletes++; } } c.close(); // Add new items for (Transformer e : entryMap.values()) { Log.i(TAG, "Scheduling insert: entry_id=" + e.transformerID); batch.add(ContentProviderOperation.newInsert(Transformer.CONTENT_URI) .withValue(Transformer.KEY_TRANSFORMER_ID, e.transformerID) .withValue(Transformer.KEY_NAME, e.trsName).withValue(Transformer.KEY_LOCATION, e.trsLocation) .withValue(Transformer.KEY_CURRENT_TEMP, e.trsCurrentTemp) .withValue(Transformer.KEY_LAST_SERVER_SYNC_DATE, e.lastServerSyncDate) .withValue(Transformer.KEY_LAST_UPDATED_TIME, e.lastServerSyncDate) .withValue(Transformer.KEY_SYNC_STATUS, 0).withValue(Transformer.KEY_MAKE, e.trsMake) .withValue(Transformer.KEY_WINDING_MAKE, e.trsWindingMake) .withValue(Transformer.KEY_WINDING_COUNT, e.trsWindingCount) .withValue(Transformer.KEY_OIL_LEVEL, e.trsOilLevel) .withValue(Transformer.KEY_OPERATING_POWER, e.trsOperatingPower) .withValue(Transformer.KEY_TYPE, e.trsType) .build()); syncResult.stats.numInserts++; } Log.i(TAG, "Merge solution ready. Applying batch update"); mContentResolver.applyBatch(Transformer.CONTENT_AUTHORITY, batch); mContentResolver.notifyChange(Transformer.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.flowzr.export.flowzr.FlowzrSyncEngine.java
private static JSONObject cursorToDict(String tableName, Cursor c) { int totalColumn = c.getColumnCount(); JSONObject rowObject = new JSONObject(); if (c.getColumnIndex("_id") != -1) { try {/*from w w w . j a v a2 s. co m*/ rowObject.put("_id", c.getInt(c.getColumnIndex("_id"))); } catch (JSONException e) { e.printStackTrace(); } } for (int i = 0; i < totalColumn; i++) { if (c.getColumnName(i) != null) { String colName = c.getColumnName(i); try { if (c.getString(i) != null) { if (colName.endsWith("_id") || colName.equals("parent")) { if (tableName.equals(DatabaseHelper.BUDGET_TABLE)) { if (colName.equals("parent_budget_id")) { rowObject.put(colName, c.getInt(i)); } else if (!colName.equals("_id")) { String[] entities = c.getString(c.getColumnIndex(colName)).split(","); String keys = ""; for (String entity_id2 : entities) { keys += getRemoteKey(getTableForColName(colName), entity_id2) + ","; } if (keys.endsWith(",")) { keys = keys.substring(0, keys.length() - 1); } rowObject.put(colName, keys); } } else { if (!colName.equals("_id")) { String k = getRemoteKey(getTableForColName(colName), c.getString(i)); if (k != null) { rowObject.put(colName, k); } else { rowObject.put(colName, c.getInt(i)); } } } } else { rowObject.put(colName, c.getString(c.getColumnIndex(colName))); } /****/ if (tableName.equals(DatabaseHelper.ACCOUNT_TABLE)) { String sql = "select max(dateTime) as maxDate, min(dateTime) as minDate from " + DatabaseHelper.TRANSACTION_TABLE + " where from_account_id=" + c.getInt(c.getColumnIndex("_id")); Cursor c2 = db.rawQuery(sql, null); c2.moveToFirst(); rowObject.put("dateOfFirstTransaction", c2.getString(1)); rowObject.put("dateOfLastTransaction", c2.getString(0)); //each account can have a timezone so you can have a balance at closing day rowObject.put("tz", String.valueOf(TimeZone.getDefault().getRawOffset())); } else if (tableName.equals(DatabaseHelper.CATEGORY_TABLE)) { //load parent id Category cat = dba.getCategory(c.getInt(0)); // sql build/load parentId if (cat.getParentId() > 0) { Category pcat = em.load(Category.class, cat.getParentId()); rowObject.put("parent", pcat.remoteKey); rowObject.put("parent_id", pcat.id); } String attrPushString = ""; for (Attribute attr : dba.getAttributesForCategory(c.getInt(0))) { attrPushString = attrPushString + attr.remoteKey + ";"; } if (attrPushString != "") { rowObject.put("attributes", attrPushString); } } else if (tableName.equals(DatabaseHelper.TRANSACTION_TABLE)) { Map<Long, String> attributesMap = dba.getAllAttributesForTransaction(c.getInt(0)); String transaction_attribute = ""; for (long attributeId : attributesMap.keySet()) { transaction_attribute += dba.getAttribute(attributeId).remoteKey + "=" + attributesMap.get(attributeId) + ";"; } rowObject.put("transaction_attribute", transaction_attribute); } /****/ } else { rowObject.put(colName, ""); } } catch (JSONException e) { Log.d(TAG, e.getMessage()); } } } return rowObject; }
From source file:com.flowzr.budget.holo.export.flowzr.FlowzrSyncEngine.java
private static JSONObject cursorToDict(String tableName, Cursor c) { int totalColumn = c.getColumnCount(); JSONObject rowObject = new JSONObject(); if (c.getColumnIndex("_id") != -1) { try {/*w w w. j av a2s . c o m*/ rowObject.put("_id", c.getInt(c.getColumnIndex("_id"))); } catch (JSONException e) { e.printStackTrace(); } } for (int i = 0; i < totalColumn; i++) { if (c.getColumnName(i) != null) { String colName = c.getColumnName(i); try { if (c.getString(i) != null) { if (colName.endsWith("_id") || colName.equals("parent")) { if (tableName.equals(DatabaseHelper.BUDGET_TABLE)) { if (colName.equals("parent_budget_id")) { rowObject.put(colName, c.getInt(i)); } else if (!colName.equals("_id")) { String[] entities = c.getString(c.getColumnIndex(colName)).split(","); String keys = ""; for (String entity_id2 : entities) { keys += getRemoteKey(getTableForColName(colName), entity_id2) + ","; } if (keys.endsWith(",")) { keys = keys.substring(0, keys.length() - 1); } rowObject.put(colName, keys); } } else { if (!colName.equals("_id")) { String k = getRemoteKey(getTableForColName(colName), c.getString(i)); if (k != null) { rowObject.put(colName, k); } else { rowObject.put(colName, c.getInt(i)); } } } } else { rowObject.put(colName, c.getString(c.getColumnIndex(colName))); } /****/ if (tableName.equals(DatabaseHelper.ACCOUNT_TABLE)) { String sql = "select max(dateTime) as maxDate, min(dateTime) as minDate from " + DatabaseHelper.TRANSACTION_TABLE + " where from_account_id=" + c.getInt(c.getColumnIndex("_id")); Cursor c2 = db.rawQuery(sql, null); c2.moveToFirst(); rowObject.put("dateOfFirstTransaction", c2.getString(1)); rowObject.put("dateOfLastTransaction", c2.getString(0)); //each account can have a timezone so you can have a balance at closing day rowObject.put("tz", String.valueOf(TimeZone.getDefault().getRawOffset())); } else if (tableName.equals(DatabaseHelper.CATEGORY_TABLE)) { //load parent id Category cat = dba.getCategory(c.getInt(0)); // sql build/load parentId if (cat.getParentId() > 0) { Category pcat = em.load(Category.class, cat.getParentId()); rowObject.put("parent", pcat.remoteKey); rowObject.put("parent_id", pcat.id); } String attrPushString = ""; for (Attribute attr : dba.getAttributesForCategory(c.getInt(0))) { attrPushString = attrPushString + attr.remoteKey + ";"; } if (attrPushString != "") { rowObject.put("attributes", attrPushString); } } else if (tableName.equals(DatabaseHelper.TRANSACTION_TABLE)) { Map<Long, String> attributesMap = dba.getAllAttributesForTransaction(c.getInt(0)); String transaction_attribute = ""; for (long attributeId : attributesMap.keySet()) { transaction_attribute += dba.getAttribute(attributeId).remoteKey + "=" + attributesMap.get(attributeId) + ";"; } rowObject.put("transaction_attribute", transaction_attribute); } /****/ } else { rowObject.put(colName, ""); } } catch (JSONException e) { Log.d(TAG, e.getMessage()); } } } return rowObject; }
From source file:com.ichi2.anki.tests.ContentProviderTest.java
/** * Test that a query for all the notes added in setup() looks correct *///from w w w .ja va 2s . c om public void testQueryNoteIds() { final ContentResolver cr = getContext().getContentResolver(); // Query all available notes final Cursor allNotesCursor = cr.query(FlashCardsContract.Note.CONTENT_URI, null, "tag:" + TEST_TAG, null, null); assertNotNull(allNotesCursor); try { assertEquals("Check number of results", mCreatedNotes.size(), allNotesCursor.getCount()); while (allNotesCursor.moveToNext()) { // Check that it's possible to leave out columns from the projection for (int i = 0; i < FlashCardsContract.Note.DEFAULT_PROJECTION.length; i++) { String[] projection = removeFromProjection(FlashCardsContract.Note.DEFAULT_PROJECTION, i); String noteId = allNotesCursor .getString(allNotesCursor.getColumnIndex(FlashCardsContract.Note._ID)); Uri noteUri = Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI, noteId); final Cursor singleNoteCursor = cr.query(noteUri, projection, null, null, null); assertNotNull("Check that there is a valid cursor for detail data", singleNoteCursor); try { assertEquals("Check that there is exactly one result", 1, singleNoteCursor.getCount()); assertTrue("Move to beginning of cursor after querying for detail data", singleNoteCursor.moveToFirst()); // Check columns assertEquals("Check column count", projection.length, singleNoteCursor.getColumnCount()); for (int j = 0; j < projection.length; j++) { assertEquals("Check column name " + j, projection[j], singleNoteCursor.getColumnName(j)); } } finally { singleNoteCursor.close(); } } } } finally { allNotesCursor.close(); } }