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:us.dustinj.locationstore.io.LocationExporter.java

private JSONArray getJSON(Cursor queryCursor) {
    JSONArray locations = new JSONArray();

    try {/*from w w  w  .j  a  va 2s.c  om*/
        while (!queryCursor.isAfterLast()) {
            JSONObject location = new JSONObject();
            HashMap<String, DatabaseField> databaseFields = LocationDatabase.GetColumnDefinitions();

            for (int columnIndex = 0; columnIndex < queryCursor.getColumnCount(); columnIndex++) {
                DatabaseField currentField = databaseFields.get(queryCursor.getColumnName(columnIndex));

                if (currentField.Type.equals("TEXT")) {
                    location.put(queryCursor.getColumnName(columnIndex), queryCursor.getString(columnIndex));
                } else if (currentField.Type.equals("REAL")) {
                    location.put(queryCursor.getColumnName(columnIndex), queryCursor.getDouble(columnIndex));
                } else if (currentField.Type.equals("INTEGER")) {
                    location.put(queryCursor.getColumnName(columnIndex), queryCursor.getInt(columnIndex));
                } else {
                    Log.e(this.getClass().getSimpleName(), "Read unsupported type from the database");
                }
            }
            queryCursor.moveToNext();

            locations.put(location);
        }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return locations;
}

From source file:at.bitfire.ical4android.AndroidTask.java

public Task getTask() throws FileNotFoundException, CalendarStorageException {
    if (task != null)
        return task;

    try {//from w  ww.j  av  a2 s.  com
        task = new Task();
        @Cleanup
        final Cursor cursor = taskList.provider.client.query(taskSyncURI(), null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            ContentValues values = new ContentValues(cursor.getColumnCount());
            DatabaseUtils.cursorRowToContentValues(cursor, values);
            populateTask(values);
        } else
            throw new FileNotFoundException("Couldn't load details of task #" + id);
        return task;
    } catch (RemoteException e) {
        throw new CalendarStorageException("Couldn't read locally stored event", e);
    } catch (ParseException e) {
        throw new CalendarStorageException("Couldn't parse locally stored event", e);
    }
}

From source file:com.nolanlawson.cordova.sqlite.SQLitePlugin.java

private SQLitePLuginResult doSelectInBackgroundAndPossiblyThrow(String sql, String[] bindArgs,
        SQLiteDatabase db) {// w w  w .j  av a  2  s  . co m
    debug("\"all\" query: %s", sql);
    Cursor cursor = null;
    try {
        cursor = db.rawQuery(sql, bindArgs);
        int numRows = cursor.getCount();
        if (numRows == 0) {
            return EMPTY_RESULT;
        }
        int numColumns = cursor.getColumnCount();
        Object[][] rows = new Object[numRows][];
        String[] columnNames = cursor.getColumnNames();
        for (int i = 0; cursor.moveToNext(); i++) {
            Object[] row = new Object[numColumns];
            for (int j = 0; j < numColumns; j++) {
                row[j] = getValueFromCursor(cursor, j, cursor.getType(j));
            }
            rows[i] = row;
        }
        debug("returning %d rows", numRows);
        return new SQLitePLuginResult(rows, columnNames, 0, 0, null);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.rjfun.cordova.sms.SMSPlugin.java

private JSONObject getJsonFromCursor(Cursor cur) {
    JSONObject json = new JSONObject();

    int nCol = cur.getColumnCount();
    String keys[] = cur.getColumnNames();

    try {//from   www . j  a  v  a  2s .  c o  m
        for (int j = 0; j < nCol; j++) {
            switch (cur.getType(j)) {
            case Cursor.FIELD_TYPE_NULL:
                json.put(keys[j], null);
                break;
            case Cursor.FIELD_TYPE_INTEGER:
                json.put(keys[j], cur.getLong(j));
                break;
            case Cursor.FIELD_TYPE_FLOAT:
                json.put(keys[j], cur.getFloat(j));
                break;
            case Cursor.FIELD_TYPE_STRING:
                json.put(keys[j], cur.getString(j));
                break;
            case Cursor.FIELD_TYPE_BLOB:
                json.put(keys[j], cur.getBlob(j));
                break;
            }
        }
    } catch (Exception e) {
        return null;
    }

    return json;
}

From source file:com.googlecode.android_scripting.facade.ContactsFacade.java

/**
 * Exactly as per <a href=/*from  ww w. j  a v a 2  s  .  co  m*/
 * "http://developer.android.com/reference/android/content/ContentResolver.html#query%28android.net.Uri,%20java.lang.String[],%20java.lang.String,%20java.lang.String[],%20java.lang.String%29"
 * >ContentResolver.query</a>
 */
@Rpc(description = "Content Resolver Query", returns = "result of query as Maps")
public List<JSONObject> queryContent(
        @RpcParameter(name = "uri", description = "The URI, using the content:// scheme, for the content to retrieve.") String uri,
        @RpcParameter(name = "attributes", description = "A list of which columns to return. Passing null will return all columns") @RpcOptional JSONArray attributes,
        @RpcParameter(name = "selection", description = "A filter declaring which rows to return") @RpcOptional String selection,
        @RpcParameter(name = "selectionArgs", description = "You may include ?s in selection, which will be replaced by the values from selectionArgs") @RpcOptional JSONArray selectionArgs,
        @RpcParameter(name = "order", description = "How to order the rows") @RpcOptional String order)
        throws JSONException {
    List<JSONObject> result = new ArrayList<JSONObject>();
    String[] columns = jsonToArray(attributes);
    String[] args = jsonToArray(selectionArgs);
    Cursor cursor = mContentResolver.query(Uri.parse(uri), columns, selection, args, order);
    if (cursor != null) {
        String[] names = cursor.getColumnNames();
        while (cursor.moveToNext()) {
            JSONObject message = new JSONObject();
            for (int i = 0; i < cursor.getColumnCount(); i++) {
                String key = names[i];
                String value = cursor.getString(i);
                message.put(key, value);
            }
            result.add(message);
        }
        cursor.close();
    }
    return result;
}

From source file:fr.unix_experience.owncloud_sms.engine.SmsFetcher.java

public JSONArray getLastMessage(MailboxID mbID) {
    String mbURI = mapMailboxIDToURI(mbID);

    if (_context == null || mbURI == null) {
        return null;
    }//from   ww  w . j av  a 2  s  .c om

    // Fetch Sent SMS Message from Built-in Content Provider
    Cursor c = (new SmsDataProvider(_context)).query(mbURI);

    c.moveToNext();

    // We create a list of strings to store results
    JSONArray results = new JSONArray();

    JSONObject entry = new JSONObject();

    try {
        for (int idx = 0; idx < c.getColumnCount(); idx++) {
            String colName = c.getColumnName(idx);

            // Id column is must be an integer
            if (colName.equals(new String("_id")) || colName.equals(new String("type"))) {
                entry.put(colName, c.getInt(idx));

                // bufferize Id for future use
                if (colName.equals(new String("_id"))) {
                }
            }
            // Seen and read must be pseudo boolean
            else if (colName.equals(new String("read")) || colName.equals(new String("seen"))) {
                entry.put(colName, c.getInt(idx) > 0 ? "true" : "false");
            } else {
                entry.put(colName, c.getString(idx));
            }
        }

        // Mailbox ID is required by server
        entry.put("mbox", mbID.ordinal());

        results.put(entry);
    } catch (JSONException e) {
        Log.e(TAG, "JSON Exception when reading SMS Mailbox", e);
        c.close();
    }

    c.close();

    return results;
}

From source file:com.denimgroup.android.training.pandemobium.stocktrader.ManageTipsActivity.java

private void doSendTipData(String symbol) {
    StockDatabase dbHelper = new StockDatabase(this.getApplicationContext());
    SQLiteDatabase db = dbHelper.openDatabase();

    StringBuilder sb = new StringBuilder();

    String sql = "SELECT * FROM tip WHERE symbol = '" + symbol + "'";

    Log.d("ManageTipsActivity", "SQL to execute is: " + sql);

    Cursor tips = db.rawQuery(sql, null);

    //   Take all the data returned and package it up for sending
    int numTips = tips.getCount();
    Log.d("ManageTipsActivity", "Got " + numTips + " tips to send");
    tips.moveToFirst();/*w w w  .  jav a2s  .  c o  m*/
    for (int i = 0; i < numTips; i++) {
        sb.append("TIP");
        sb.append(i);
        sb.append(":");
        int columnCount = tips.getColumnCount();
        Log.d("ManageTipsActivity", "Tip " + i + " has " + columnCount + " columns");
        for (int j = 0; j < columnCount; j++) {
            if (j > 0) {
                sb.append("&");
            }
            sb.append(tips.getColumnName(j));
            sb.append("=");
            sb.append(tips.getString(j));
        }
        tips.moveToNext();
        sb.append("\n");
    }

    tips.close();
    db.close();

    Log.d("ManageTipsActivity", "Tip data to post is: " + sb.toString());

    String accountId = AccountUtils.retrieveAccountId(getApplicationContext());
    String tradeServiceUrl = getResources().getString(R.string.tip_service);

    String fullUrl = tradeServiceUrl + "?method=submitTips&id=" + accountId;

    Log.d("ManageTipsActivity", "Full URL for tip sending is: " + fullUrl);

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(fullUrl);
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("tipData", sb.toString()));
    try {
        post.setEntity(new UrlEncodedFormEntity(pairs));
        HttpResponse response = client.execute(post);
        tvTipStatus.setText("Tip data for " + etSymbol.getText().toString() + " sent!");

    } catch (Exception e) {
        Log.e("ManageTipsActivity", "Error when encoding or sending tip data: " + e.toString());
        e.printStackTrace();
    }
}

From source file:com.dgsd.android.ShiftTracker.Adapter.WeekAdapter.java

@Override
public Cursor swapCursor(Cursor cursor) {
    clearCaches();//w  ww. j a v a2  s  .co m

    if (cursor == null)
        return super.swapCursor(null);

    MatrixCursor mc = new MatrixCursor(DbTable.SHIFTS.getFieldNames(), cursor.getCount() + 7);

    int jd = mStartingJulianDay;
    final int colCount = cursor.getColumnCount();

    SparseArray<List<Object[]>> jdToRowArray = new SparseArray<List<Object[]>>();

    if (cursor.moveToFirst()) {
        final int jdIndex = cursor.getColumnIndex(DbField.JULIAN_DAY.name);
        do {
            Object[] row = new Object[colCount];
            for (int i = 0; i < colCount; i++)
                row[i] = cursor.getString(i);

            final int shiftDay = cursor.getInt(jdIndex);

            List<Object[]> rowsOnSameJd = jdToRowArray.get(shiftDay, null);
            if (rowsOnSameJd == null)
                rowsOnSameJd = new ArrayList<Object[]>();

            rowsOnSameJd.add(row);

            jdToRowArray.put(shiftDay, rowsOnSameJd);
        } while (cursor.moveToNext());
    }

    for (int i = jd; i < jd + 7; i++) {
        List<Object[]> rows = jdToRowArray.get(i);
        if (rows != null)
            for (Object[] row : rows)
                mc.addRow(row);

        //Add a 'Add Shift' row
        Object[] row = new Object[colCount];
        row[0] = mRand.nextInt(Integer.MAX_VALUE); // DbField.ID
        row[1] = i; // DbField.JULIAN_DAY
        row[2] = i; // DbField.END_JULIAN_DAY
        row[3] = -1; // DbField.START_TIME
        row[4] = -1; // DbField.END_TIME
        row[5] = -1; // DbField.PAY_RATE
        row[6] = NEW_ROW_KEY; // DbField.NAME
        row[7] = null; // DbField.NOTE
        row[8] = -1; // DbField.BREAK_DURATION
        row[9] = 0; // DbField.IS_TEMPLATE
        row[10] = -1; // DbField.REMINDER

        mc.addRow(row);
    }

    return super.swapCursor(mc);
}

From source file:com.digicorp.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Convert results cursor to JSON string.
 *
 * @param cur// w ww.  ja va 2s . c o m
 *            Cursor into query results
 *
 * @return results in string form
 *
 */
@SuppressLint("NewApi")
private String results2string(Cursor cur) {
    String result = "[]";

    // If query result has rows
    if (cur.moveToFirst()) {
        JSONArray fullresult = new JSONArray();
        String key = "";
        int colCount = cur.getColumnCount();

        // Build up JSON result object for each row
        do {
            JSONObject row = new JSONObject();
            try {
                for (int i = 0; i < colCount; ++i) {
                    key = cur.getColumnName(i);

                    // for old Android SDK remove lines from HERE:
                    if (android.os.Build.VERSION.SDK_INT >= 11) {
                        switch (cur.getType(i)) {
                        case Cursor.FIELD_TYPE_NULL:
                            row.put(key, null);
                            break;
                        case Cursor.FIELD_TYPE_INTEGER:
                            row.put(key, cur.getInt(i));
                            break;
                        case Cursor.FIELD_TYPE_FLOAT:
                            row.put(key, cur.getFloat(i));
                            break;
                        case Cursor.FIELD_TYPE_STRING:
                            row.put(key, cur.getString(i));
                            break;
                        case Cursor.FIELD_TYPE_BLOB:
                            row.put(key, new String(Base64.encode(cur.getBlob(i), Base64.DEFAULT)));
                            break;
                        }
                    } else // to HERE.
                    {
                        row.put(key, cur.getString(i));
                    }
                }

                fullresult.put(row);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } while (cur.moveToNext());

        result = fullresult.toString();
    }

    return result;
}

From source file:com.zetaDevelopment.phonegap.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Convert results cursor to JSON string.
 *
 * @param cur/*from www .j a v  a2s  .  co m*/
 *            Cursor into query results
 *
 * @return results in string form
 *
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private String results2string(Cursor cur) {
    String result = "[]";

    // If query result has rows
    if (cur.moveToFirst()) {
        JSONArray fullresult = new JSONArray();
        String key = "";
        int colCount = cur.getColumnCount();

        // Build up JSON result object for each row
        do {
            JSONObject row = new JSONObject();
            try {
                for (int i = 0; i < colCount; ++i) {
                    key = cur.getColumnName(i);

                    // for old Android SDK remove lines from HERE:
                    if (android.os.Build.VERSION.SDK_INT >= 11) {
                        switch (cur.getType(i)) {
                        case Cursor.FIELD_TYPE_NULL:
                            row.put(key, null);
                            break;
                        case Cursor.FIELD_TYPE_INTEGER:
                            row.put(key, cur.getInt(i));
                            break;
                        case Cursor.FIELD_TYPE_FLOAT:
                            row.put(key, cur.getFloat(i));
                            break;
                        case Cursor.FIELD_TYPE_STRING:
                            row.put(key, cur.getString(i));
                            break;
                        case Cursor.FIELD_TYPE_BLOB:
                            //row.put(key, cur.getBlob(i));
                            row.put(key, new String(Base64.encode(cur.getBlob(i), Base64.DEFAULT)));
                            break;
                        }
                    } else // to HERE.
                    {
                        row.put(key, cur.getString(i));
                    }
                }

                fullresult.put(row);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } while (cur.moveToNext());

        result = fullresult.toString();
    }

    return result;
}