Example usage for android.database Cursor getColumnName

List of usage examples for android.database Cursor getColumnName

Introduction

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

Prototype

String getColumnName(int columnIndex);

Source Link

Document

Returns the column name at the given zero-based column index.

Usage

From source file:com.phonegap.plugins.sqlitePlugin.SQLitePlugin.java

/**
 * Process query results./*w ww . j a  va 2 s .  c  om*/
 *
 * @param cur
 *            Cursor into query results
 * @param tx_id
 *            Transaction id
 */
public void processResults(Cursor cur, String query_id, String tx_id) {

    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);
                    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));
                            break;
                        }
                    } else {
                        row.put(key, cur.getString(i));
                    }
                }
                fullresult.put(row);

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

        } while (cur.moveToNext());

        result = fullresult.toString();
    }
    if (query_id.length() > 0)
        this.sendJavascript(" SQLitePluginTransaction.queryCompleteCallback('" + tx_id + "','" + query_id
                + "', " + result + ");");

}

From source file:com.photowall.oauth.util.BaseHttpClient.java

/**
 * // ww  w. j  av  a2s  . com
 * @param mContext
 */
private void setProxy(Context mContext) {
    try {
        ContentValues values = new ContentValues();
        Cursor cur = mContext.getContentResolver().query(Uri.parse("content://telephony/carriers/preferapn"),
                null, null, null, null);
        if (cur != null && cur.getCount() > 0) {
            if (cur.moveToFirst()) {
                int colCount = cur.getColumnCount();
                for (int i = 0; i < colCount; i++) {
                    values.put(cur.getColumnName(i), cur.getString(i));
                }
            }
            cur.close();
        }
        String proxyHost = (String) values.get("proxy");
        if (!TextUtils.isEmpty(proxyHost) && !isWiFiConnected(mContext)) {
            int prot = Integer.parseInt(String.valueOf(values.get("port")));
            delegate.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, prot),
                    new UsernamePasswordCredentials((String) values.get("user"),
                            (String) values.get("password")));
            HttpHost proxy = new HttpHost(proxyHost, prot);
            delegate.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.w(TAG, "set proxy error+++++++++++++++++");
    }
}

From source file:com.triarc.sync.SyncAdapter.java

private void debugRow(Cursor cursor) {
    for (int index = 0; index < cursor.getColumnCount(); index++) {

        Log.d(TAG, cursor.getColumnName(index) + " => " + cursor.getString(index));
    }//from  w  ww. ja v a  2 s.  c  o m
}

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

/**
 * Convert results cursor to JSON string.
 *
 * @param cur/*  ww w.  j  a  va2  s  .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:fr.unix_experience.owncloud_sms.engine.SmsFetcher.java

private void bufferizeMailboxMessages(MailboxID mbID) {
    String mbURI = mapMailboxIDToURI(mbID);

    if (_context == null || mbURI == null) {
        return;/*from  w  w  w  .  j  av  a2s .  com*/
    }

    if (mbID != MailboxID.INBOX && mbID != MailboxID.SENT && mbID != MailboxID.DRAFTS) {
        Log.e(TAG, "Unhandled MailboxID " + mbID.ordinal());
        return;
    }

    // We generate a ID list for this message box
    String existingIDs = buildExistingMessagesString(mbID);

    Cursor c = null;
    if (existingIDs.length() > 0) {
        c = (new SmsDataProvider(_context)).query(mbURI, "_id NOT IN (" + existingIDs + ")");
    } else {
        c = (new SmsDataProvider(_context)).query(mbURI);
    }

    // Reading mailbox
    if (c != null && c.getCount() > 0) {
        c.moveToFirst();
        do {
            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 {
                        // Special case for date, we need to record last without searching
                        if (colName.equals(new String("date"))) {
                            final Long tmpDate = c.getLong(idx);
                            if (tmpDate > _lastMsgDate) {
                                _lastMsgDate = tmpDate;
                            }
                        }
                        entry.put(colName, c.getString(idx));
                    }
                }

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

                _jsonDataDump.put(entry);

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

        Log.d(TAG, c.getCount() + " messages read from " + mbURI);

        c.close();
    }
}

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();// www  . java2  s. com
    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.zetaDevelopment.phonegap.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Convert results cursor to JSON string.
 *
 * @param cur/*from www  . j a va2 s  . 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;
}

From source file:com.nextgis.mobile.fragment.AttributesFragment.java

private String parseAttributes(String data) throws RuntimeException {
    String selection = Constants.FIELD_ID + " = ?";
    Cursor attributes = mLayer.query(null, selection, new String[] { mItemId + "" }, null, null);
    if (null == attributes || attributes.getCount() == 0)
        return data;

    if (attributes.moveToFirst()) {
        for (int i = 0; i < attributes.getColumnCount(); i++) {
            String column = attributes.getColumnName(i);
            String text, alias;/*from  w  ww.j a  va  2s  . c  o  m*/

            if (column.startsWith(Constants.FIELD_GEOM_))
                continue;

            if (column.equals(Constants.FIELD_GEOM)) {
                switch (mLayer.getGeometryType()) {
                case GTPoint:
                    try {
                        GeoPoint pt = (GeoPoint) GeoGeometryFactory.fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.coordinates), formatCoordinates(pt));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTMultiPoint:
                    try {
                        GeoMultiPoint mpt = (GeoMultiPoint) GeoGeometryFactory.fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.center),
                                formatCoordinates(mpt.getEnvelope().getCenter()));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTLineString:
                    try {
                        GeoLineString line = (GeoLineString) GeoGeometryFactory.fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.length),
                                LocationUtil.formatLength(getContext(), line.getLength(), 3));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTMultiLineString:
                    try {
                        GeoMultiLineString multiline = (GeoMultiLineString) GeoGeometryFactory
                                .fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.length),
                                LocationUtil.formatLength(getContext(), multiline.getLength(), 3));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTPolygon:
                    try {
                        GeoPolygon polygon = (GeoPolygon) GeoGeometryFactory.fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.perimeter),
                                LocationUtil.formatLength(getContext(), polygon.getPerimeter(), 3));
                        data += getRow(getString(R.string.area),
                                LocationUtil.formatArea(getContext(), polygon.getArea()));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTMultiPolygon:
                    try {
                        GeoMultiPolygon polygon = (GeoMultiPolygon) GeoGeometryFactory
                                .fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.perimeter),
                                LocationUtil.formatLength(getContext(), polygon.getPerimeter(), 3));
                        data += getRow(getString(R.string.area),
                                LocationUtil.formatArea(getContext(), polygon.getArea()));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                default:
                    continue;
                }
            }

            Field field = mLayer.getFieldByName(column);
            int fieldType = field != null ? field.getType() : Constants.NOT_FOUND;
            switch (fieldType) {
            case GeoConstants.FTInteger:
                text = attributes.getInt(i) + "";
                break;
            case GeoConstants.FTReal:
                NumberFormat nf = NumberFormat.getInstance();
                nf.setMaximumFractionDigits(4);
                nf.setGroupingUsed(false);
                text = nf.format(attributes.getDouble(i));
                break;
            case GeoConstants.FTDate:
            case GeoConstants.FTTime:
            case GeoConstants.FTDateTime:
                text = formatDateTime(attributes.getLong(i), fieldType);
                break;
            default:
                text = toString(attributes.getString(i));
                Pattern pattern = Pattern.compile(URL_PATTERN);
                Matcher match = pattern.matcher(text);
                while (match.matches()) {
                    String url = text.substring(match.start(), match.end());
                    text = text.replaceFirst(URL_PATTERN, "<a href = '" + url + "'>" + url + "</a>");
                    match = pattern.matcher(text.substring(match.start() + url.length() * 2 + 17));
                }
                break;
            }

            if (field != null)
                alias = field.getAlias();
            else if (column.equals(Constants.FIELD_ID))
                alias = Constants.FIELD_ID;
            else
                alias = "";

            data += getRow(alias, text);
        }
    }

    attributes.close();
    return data;
}

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

/**
 * Gets modified rows of a table.//from   w w w. ja v a 2  s  . c om
  * @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:com.android.server.MaybeDatabaseHelper.java

public boolean hasEntries(String packagename) {
    if (!checkInitialized()) {
        return false;
    }/*from  ww  w .  jav  a 2s  . 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;
}