Example usage for android.database Cursor getColumnCount

List of usage examples for android.database Cursor getColumnCount

Introduction

In this page you can find the example usage for android.database Cursor getColumnCount.

Prototype

int getColumnCount();

Source Link

Document

Return total number of columns

Usage

From source file:de.uni_koblenz_landau.apow.db.SyncDBHelper.java

/**
 * Gets modified rows of a table.//from  ww  w .  j  av  a  2 s  .c  o  m
  * @param table Table
 * @return List of rows as JSONObject 
 * @throws JSONException
 */
public List<JSONObject> getDirtyRows(String table) throws JSONException {
    String query = null;
    switch (table) {
    case "patient":
        query = "SELECT pa.tribe, pa.creator, pa.date_created, pa.changed_by, pa.date_changed,"
                + " pa.voided, pa.voided_by, pa.date_voided, pa.void_reason, pe.uuid FROM patient"
                + " pa INNER JOIN person pe ON pe.person_id = pa.patient_id " + " WHERE pa.dirty = 1";
        break;
    case "person":
        query = "SELECT pe.gender, pe.birthdate, pe.birthdate_estimated, pe.dead, pe.death_date,"
                + " pe.cause_of_death, pe.creator, pe.date_created, pe.changed_by, pe.date_changed,"
                + " pe.voided, pe.voided_by, pe.date_voided, pe.void_reason, pe.uuid FROM person pe"
                + " WHERE pe.dirty = 1";
        break;
    case "patient_identifier":
        query = "SELECT pe.uuid AS patient_id, pi.identifier, pi.identifier_type, pi.preferred,"
                + " pi.location_id, pi.creator, pi.date_created, pi.date_changed, pi.changed_by, pi.voided,"
                + " pi.voided_by, pi.date_voided, pi.void_reason, pi.uuid FROM patient_identifier pi"
                + " INNER JOIN person pe ON pi.patient_id = pe.person_id" + " WHERE pi.dirty = 1";
        break;
    case "person_address":
        query = "SELECT pe.uuid AS person_id, pa.preferred, pa.address1, pa.address2, pa.city_village,"
                + " pa.state_province, pa.postal_code, pa.country, pa.latitude, pa.longitude, pa.start_date,"
                + " pa.end_date, pa.creator, pa.date_created, pa.voided, pa.voided_by, pa.date_voided,"
                + " pa.void_reason, pa.county_district, pa.address3, pa.address4, pa.address5, pa.address6,"
                + " pa.date_changed, pa.changed_by, pa.uuid FROM person_address pa"
                + " INNER JOIN person pe ON pa.person_id = pe.person_id" + " WHERE pa.dirty = 1";
        break;
    case "person_name":
        query = "SELECT pn.preferred, pe.uuid AS person_id, pn.prefix, pn.given_name, pn.middle_name,"
                + " pn.family_name_prefix, pn.family_name, pn.family_name2, pn.family_name_suffix, pn.degree,"
                + " pn.creator, pn.date_created, pn.voided, pn.voided_by, pn.date_voided, pn.void_reason,"
                + " pn.changed_by, pn.date_changed, pn.uuid FROM person_name pn"
                + " INNER JOIN person pe ON pn.person_id = pe.person_id" + " WHERE pn.dirty = 1";
        break;
    case "encounter":
        query = "SELECT en.encounter_type, pe.uuid AS patient_id, en.location_id, en.form_id,"
                + " en.encounter_datetime, en.creator, en.date_created, en.voided, en.voided_by,"
                + " en.date_voided, en.void_reason, en.changed_by, en.date_changed, en.visit_id,"
                + " en.uuid FROM encounter en INNER JOIN person pe ON en.patient_id = pe.person_id"
                + " WHERE en.dirty = 1";
        break;
    case "obs":
        query = "SELECT pe.uuid AS person_id, o.concept_id, en.uuid AS encounter_id, o.order_id,"
                + " o.obs_datetime, o.location_id, o2.uuid AS obs_group_id, o.accession_number,"
                + " o.value_group_id, o.value_boolean, o.value_coded, o.value_coded_name_id, o.value_drug,"
                + " o.value_datetime, o.value_numeric, o.value_modifier, o.value_text, o.value_complex,"
                + " o.comments, o.creator, o.date_created, o.voided, o.voided_by, o.date_voided, o.void_reason,"
                + " o.uuid, o.previous_version FROM obs o INNER JOIN person pe ON o.person_id = pe.person_id"
                + " INNER JOIN encounter en ON en.encounter_id = o.encounter_id"
                + " LEFT JOIN obs o2 ON o2.obs_id = o.obs_group_id"
                + " WHERE o.dirty = 1 ORDER BY o.obs_group_id";
        break;
    }

    Cursor cursor = mDatabase.rawQuery(query, new String[] {});

    cursor.moveToFirst();
    List<JSONObject> items = new ArrayList<>();
    JSONObject root;
    JSONObject obj;
    // For every row
    while (!cursor.isAfterLast()) {
        root = new JSONObject();
        obj = new JSONObject();
        // For every column
        for (int i = 0; i < cursor.getColumnCount(); i++) {
            String key = cursor.getColumnName(i);
            // Convert value to JSON type
            if (cursor.isNull(i)) {
                obj.put(key, JSONObject.NULL);
            } else {
                obj.put(key, cursor.getString(i));
            }
        }
        root.put("table", table);
        root.put("values", obj);
        items.add(root);
        cursor.moveToNext();
    }
    cursor.close();
    return items;
}

From source file:android.support.content.InMemoryCursor.java

/**
 * @param cursor source of data to copy. Ownership is reserved to the called, meaning
 *               we won't ever close it.
 *///  w  ww .j  ava  2  s.  c o m
InMemoryCursor(Cursor cursor, int offset, int length, int disposition) {
    checkArgument(offset < cursor.getCount());

    // NOTE: The cursor could simply be saved to a field, but we choose to wrap
    // in a dedicated relay class to avoid hanging directly onto a reference
    // to the cursor...so future authors are not enticed to think there's
    // a live link between the delegate cursor and this cursor.
    mObserverRelay = new ObserverRelay(cursor);

    mColumnNames = cursor.getColumnNames();
    mRowCount = Math.min(length, cursor.getCount() - offset);
    int numColumns = cursor.getColumnCount();

    mExtras = ContentPager.buildExtras(cursor.getExtras(), cursor.getCount(), disposition);

    mColumnType = new int[numColumns];
    mTypedColumnIndex = new int[NUM_TYPES][numColumns];
    mColumnTypeCount = new int[NUM_TYPES];

    if (!cursor.moveToFirst()) {
        throw new RuntimeException("Can't position cursor to first row.");
    }

    for (int col = 0; col < numColumns; col++) {
        int type = cursor.getType(col);
        mColumnType[col] = type;
        mTypedColumnIndex[type][col] = mColumnTypeCount[type]++;
    }

    mLongs = new long[mRowCount * mColumnTypeCount[FIELD_TYPE_INTEGER]];
    mDoubles = new double[mRowCount * mColumnTypeCount[FIELD_TYPE_FLOAT]];
    mBlobs = new byte[mRowCount * mColumnTypeCount[FIELD_TYPE_BLOB]][];
    mStrings = new String[mRowCount * mColumnTypeCount[FIELD_TYPE_STRING]];

    for (int row = 0; row < mRowCount; row++) {
        if (!cursor.moveToPosition(offset + row)) {
            throw new RuntimeException("Unable to position cursor.");
        }

        // Now copy data from the row into primitive arrays.
        for (int col = 0; col < mColumnType.length; col++) {
            int type = mColumnType[col];
            int position = getCellPosition(row, col, type);

            switch (type) {
            case FIELD_TYPE_NULL:
                throw new UnsupportedOperationException("Not implemented.");
            case FIELD_TYPE_INTEGER:
                mLongs[position] = cursor.getLong(col);
                break;
            case FIELD_TYPE_FLOAT:
                mDoubles[position] = cursor.getDouble(col);
                break;
            case FIELD_TYPE_BLOB:
                mBlobs[position] = cursor.getBlob(col);
                break;
            case FIELD_TYPE_STRING:
                mStrings[position] = cursor.getString(col);
                break;
            }
        }
    }
}

From source file:org.de.jmg.jmgphotouploader._MainActivity.java

private void initDB(JMPPPApplication app) {
    if (app.dbpp != null) {
        lib.dbpp = app.dbpp;/*from   w w w. j a  v a 2s  .  c  o  m*/
        lib.dbpp = new dbpp(this);
        lib.dbpp.createDataBase();
        app.dbpp = lib.dbpp;
    } else {
        lib.dbpp = new dbpp(this);
        lib.dbpp.createDataBase();
        app.dbpp = lib.dbpp;
    }
    String SQL = "ALTER TABLE Services ADD COLUMN visible BOOL NOT NULL DEFAULT true";
    try {
        Cursor c = lib.dbpp.query("Select * FROM Services");
        if (c.getColumnCount() < 5)
            lib.dbpp.DataBase.execSQL(SQL);
        boolean first = true;
        lib.setgstatus("enumerate Services");
        while ((first) ? (c.moveToFirst()) : (c.moveToNext())) {
            first = false;
            String service = c.getString(c.getColumnIndex("Name"));
            String Package = c.getString(c.getColumnIndex("package"));
            if (service.contains("Facebook")) {
                if (Package == null || Package.equals("")) {
                    String p = "com.facebook.katana";
                    String sql = "Update Services SET package = \"" + p + "\" WHERE _id = " + c.getInt(0);
                    lib.dbpp.DataBase.execSQL(sql);
                    p = "https://www.facebook.com/mobile/";
                    sql = "Update Services SET URL = \"" + p + "\" WHERE _id = " + c.getInt(0);
                    lib.dbpp.DataBase.execSQL(sql);
                }
            } else if (service.contains("Twitter")) {
                if (Package == null || Package.equals("")) {
                    String p = "com.twitter." + "android,com." + "twidroid,com.handmark."
                            + "tweetcaster,com.thedeck.android";
                    String sql = "Update Services SET package = \"" + p + "\" WHERE _id = " + c.getInt(0);
                    lib.dbpp.DataBase.execSQL(sql);

                    p = "https://about.twitter.com/de/products/list";
                    sql = "Update Services SET URL = \"" + p + "\" WHERE _id = " + c.getInt(0);
                    lib.dbpp.DataBase.execSQL(sql);

                }
            } else if (service.contains("Instagram")) {
                if (Package == null || Package.equals("")) {
                    String p = "com.instagram.android";
                    String sql = "Update Services SET package = \"" + p + "\" WHERE _id = " + c.getInt(0);
                    lib.dbpp.DataBase.execSQL(sql);
                    p = "http://instagram.de.uptodown.com/android";
                    ;
                    sql = "Update Services SET URL = \"" + p + "\" WHERE _id = " + c.getInt(0);
                    lib.dbpp.DataBase.execSQL(sql);
                }
            } else if (service.contains("Pinterest")) {
            }
            //c = lib.dbpp.query("Select * FROM Services");

        }
        if (c.getCount() < 6) {
            String sql = "INSERT INTO Services ('Name','URL','package') VALUES('Flickr','http://flickr.com','com.yahoo.mobile.client.android.flickr')";
            lib.dbpp.DataBase.execSQL(sql);
            sql = "INSERT INTO Services ('Name','URL','package') VALUES('Tumblr','http://tumblr.com','com.tumblr')";
            lib.dbpp.DataBase.execSQL(sql);
        }
        if (c.getCount() < 7) {
            String sql = "INSERT INTO Services ('Name','URL','package') VALUES('Photobucket','http://photobucket.com','com.photobucket.android')";
            lib.dbpp.DataBase.execSQL(sql);
        }
        if (c.getCount() < 8) {
            String sql = "INSERT INTO Services ('Name','URL','package') VALUES('Google+','https://plus.google.com','com.google.android.apps.plus')";
            lib.dbpp.DataBase.execSQL(sql);
        }

        lib.getContentProviders(this, lib.getUriToDrawable(this, R.drawable.res));
    } catch (Throwable ex) {
        System.out.println(ex.getMessage());
    }

}

From source file:com.android.server.MaybeDatabaseHelper.java

public boolean hasEntries(String packagename) {
    if (!checkInitialized()) {
        return false;
    }/*from w  w  w .  ja  v a2  s.c  o m*/

    Cursor cursor = null;
    boolean ret = false;

    try {
        /* cursor = sDatabase.query(APP_TABLE_NAME, new String[]{DATA_COL}, PACKAGE_COL+"="+packagename,
           null, null, null, null, null);
         */
        cursor = sDatabase.rawQuery("SELECT count(*) FROM " + APP_TABLE_NAME + " where " + PACKAGE_COL + " = ?",
                new String[] { packagename });
        /*
        if(cursor == null){
          Log.v(DBTAG, "cursor is null");
          return false;
        }
        ret = (cursor.moveToFirst() == true);
        */
        Log.v(DBTAG, "num columns|column" + cursor.getColumnCount() + "|" + cursor.getColumnName(0) + "|");
        cursor.moveToFirst();
        ret = (cursor.getInt(cursor.getColumnIndex("count(*)")) > 0);
        Log.v(DBTAG, "Package exists: Count:" + ret + cursor.getCount());
    } catch (IllegalStateException e) {
        Log.e(DBTAG, "IllegalStateException in hasEntries", e);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return ret;
}

From source file:com.DorsetEggs.waver.communicatorService.java

private void loadAnimation(int animOption) {
    //First, load the animation to use
    String[] projectionAnimToActions = { globals.AnimToActions.COLUMN_NAME_ACTION,
            globals.AnimToActions.COLUMN_NAME_ANIMATION, };
    String sortOrderAnimToActions = globals.AnimToActions.COLUMN_NAME_ACTION + " DESC";
    Cursor cAnimToActions = db.query(globals.AnimToActions.TABLE_NAME, // The table to query
            projectionAnimToActions, // The columns to return
            globals.AnimToActions.COLUMN_NAME_ACTION + " = " + animOption, // The columns for the WHERE clause
            null, // The values for the WHERE clause
            null, // don't group the rows
            null, // don't filter by row groups
            sortOrderAnimToActions // The sort order
    );/*from w  w w.  j  a v  a  2 s .com*/

    if (cAnimToActions.getColumnCount() == 0) {
        Toast.makeText(this, "Animation not found for action", Toast.LENGTH_LONG).show();
    }

    //Next load the selected animation
    String[] projectionAnimations = { globals.Animations.COLUMN_NAME_POSITION,
            globals.Animations.COLUMN_NAME_TIME, };
    String sortOrderAnimations = globals.Animations.COLUMN_NAME_KEYFRAME + " DESC";

    //Finally place the animation into the array for later processing
    for (Integer i = 0; i < ServoTypes.NUMOFSERVOS.ordinal(); ++i) {
        String whereClause = globals.Animations.COLUMN_NAME_TITLE + " = "
                + cAnimToActions
                        .getString(cAnimToActions.getColumnIndex(globals.AnimToActions.COLUMN_NAME_ANIMATION))
                + " AND " + globals.Animations.COLUMN_NAME_MOTOR + " = " + i.toString();

        Cursor cAnimations = db.query(globals.Animations.TABLE_NAME, // The table to query
                projectionAnimations, // The columns to return
                whereClause, // The columns for the WHERE clause
                null, // The values for the WHERE clause
                null, // don't group the rows
                null, // don't filter by row groups
                sortOrderAnimations // The sort order
        );
        if (cAnimations.getColumnCount() == 0) {
            Toast.makeText(this, "Animation not found", Toast.LENGTH_LONG).show();
        }

        if (cAnimations != null) {
            if (cAnimations.moveToFirst()) {
                int positionColumn = cAnimations.getColumnIndex(globals.Animations.COLUMN_NAME_POSITION);
                int timeColumn = cAnimations.getColumnIndex(globals.Animations.COLUMN_NAME_TIME);
                Vector<KeyframePacket> servoAnimation = new Vector<KeyframePacket>();
                do {
                    KeyframePacket keyframe = new KeyframePacket();
                    keyframe.servoToApplyTo = i.byteValue();
                    keyframe.degreesToReach = (byte) cAnimations.getInt(positionColumn);
                    keyframe.timeToPosition = (short) cAnimations.getInt(timeColumn);
                    servoAnimation.add(keyframe);
                } while (cAnimations.moveToNext());
                servoAnimations.add(i, servoAnimation);
            }
        }
    }
}

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 www. java2 s  .  c o m*/
            } else {
                if (c.isNull(i) || !value.toString().equals(c.getString(i))) {
                    return false;
                }
            }
        }
    }
    return true;
}

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   ww  w  .  j  a v  a 2  s.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:com.sourceallies.android.zonebeacon.data.DataSource.java

/**
 * Creates a json array where each item is a row in the database. Each row contains all fields
 * from that table in a comma separated order.
 *
 * @param query the sql string to get the data.
 * @return the json array of data./*from   ww w  . j av a  2s.com*/
 */
private JSONArray sqlToJson(String query) {
    JSONArray array = new JSONArray();

    Cursor cursor = database.rawQuery(query, null);

    if (cursor != null && cursor.moveToFirst()) {
        do {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < cursor.getColumnCount(); i++) {
                builder.append(cursor.getString(i));
                if (i != cursor.getColumnCount() - 1) {
                    builder.append(",");
                }
            }

            array.put(builder.toString());
        } while (cursor.moveToNext());

        cursor.close();
    }

    return array;
}

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 . ja  va2 s.  c om*/
            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

/**
 * Check that a valid Cursor is returned when querying notes table with non-default projections
 *//* w w w . j a v  a2 s. com*/
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();
        }
    }
}