Example usage for android.database Cursor getColumnNames

List of usage examples for android.database Cursor getColumnNames

Introduction

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

Prototype

String[] getColumnNames();

Source Link

Document

Returns a string array holding the names of all of the columns in the result set in the order in which they were listed in the result.

Usage

From source file:com.jsonstore.api.JSONStoreCollection.java

/**
 * Find documents in the collection that are based on the given query.
 *
 * @param query/*from   www .ja  v  a 2  s . c o  m*/
 *             The find query that restricts the search.
 * @param options
 *             Additional options to modify the count operation.
 * @return   A list of documents.
 * @throws JSONStoreFindException
 *             An error occurred when trying to execute the find.
 * @throws JSONStoreFilterException
 *             An error occurred when trying to apply a filter to the query.
 * @throws JSONStoreDatabaseClosedException
 *             The JSONStore database is closed, and cannot be accessed to
 *             execute the find.
 */
public List<JSONObject> findDocuments(JSONStoreQueryParts query, JSONStoreFindOptions options)
        throws JSONStoreFindException, JSONStoreFilterException, JSONStoreDatabaseClosedException {
    JSONStoreAnalyticsLogInstance logInst = JSONStoreLogger.startAnalyticsInstance(getUsername(), getName(),
            JSONStoreLogger.OPERATION_FIND);
    try {
        getAccessor(); // This does some closed checks.
        if (options == null) {
            options = new JSONStoreFindOptions();
        }

        if (query == null) {
            query = new JSONStoreQueryParts();
        }

        QueryBuilderSelect selectQuery = new QueryBuilderSelect(this, query);
        selectQuery.setLimit(options.getLimit());
        selectQuery.setOffset(options.getOffset());
        selectQuery.setSort(options.getSort());

        if (options.shouldIncludeDeletedDocuments()) {
            selectQuery.setSearchIncludeDeleted();
        }

        LinkedHashMap<Integer, JSONObject> resultHash = new LinkedHashMap<Integer, JSONObject>();
        List<JSONObject> filterResults = new ArrayList<JSONObject>();

        // Set the fields to select in the query, if specified, otherwise default to _id and _json:
        Map<String, Boolean> filters = options.getSearchFilters();
        if (filters != null && filters.size() > 0) {
            for (String filter : filters.keySet()) {
                boolean isSpecial = filters.get(filter);
                selectQuery.addSelectStatement(filter, isSpecial);
            }
        } else {
            selectQuery.addSelectStatement(DatabaseConstants.FIELD_ID, false);
            selectQuery.addSelectStatement(DatabaseConstants.FIELD_JSON, false);
        }

        Cursor cursor = null;
        List<JSONObject> result = null;
        try {
            cursor = runQuery(selectQuery);
            if (cursor != null) {
                result = new LinkedList<JSONObject>();

                for (int j = 0; j < cursor.getCount(); ++j) {
                    JSONObject item = new JacksonSerializedJSONObject();

                    cursor.moveToNext();

                    for (int k = 0; k < cursor.getColumnNames().length; ++k) {
                        if (cursor.getColumnName(k).equals(DatabaseConstants.FIELD_ID)) {
                            item.put(cursor.getColumnName(k), cursor.getInt(k));
                        } else if (cursor.getColumnName(k).equals(DatabaseConstants.FIELD_JSON)) {
                            item.put(DatabaseConstants.FIELD_JSON,
                                    JsonOrgModule.deserializeJSONObject(cursor.getString(k)));
                        } else if (isJSONCreatedColumn(cursor.getColumnName(k))) {
                            item.put(cursor.getColumnName(k), cursor.getString(k));
                        } else {
                            item.put(cursor.getColumnName(k).replace("_", "."), cursor.getString(k)); //$NON-NLS-1$ //$NON-NLS-2$
                        }
                    }

                    result.add(item);
                }
            }
        } catch (Throwable e) {
            String message = "Error when attempting to find a document. An error occurred when reading from the database.";
            JSONStoreFindException jsException = new JSONStoreFindException(message, e);
            logger.logError(message, jsException);
            throw jsException;

        } finally {
            if (cursor != null)
                cursor.close();
        }

        if (options.getSearchFilters() != null) {
            for (JSONObject obj : result) {
                filterResults.add(obj);
            }
        } else {
            addNonDuplicates(resultHash, result);
        }

        List<JSONObject> results = null;

        if (options.getSearchFilters() != null) {
            results = removeFilterDuplicates(filterResults);
        } else {
            results = new ArrayList<JSONObject>(resultHash.values());
        }

        return results;
    } finally {
        logInst.end();
    }
}

From source file:com.roamprocess1.roaming4world.ui.messages.MessageAdapter.java

@SuppressLint("SdCardPath")
@Override//from  ww  w  .  j a  va2  s .  c o  m
public void bindView(View view, Context context, Cursor cursor) {
    System.out.println("MessageAdapter.java in bindView() ");
    final MessageListItemViews tagView = (MessageListItemViews) view.getTag();
    v = view;
    this.context = context;
    SipMessage msg = new SipMessage(cursor);
    // System.out.println("msg:"+msg);

    System.out.println("Cursor row count:" + cursor.getCount());

    String number = msg.getRemoteNumber();
    long date = msg.getDate();
    String message = msg.getBodyContent();
    subject = message;
    System.out.println("subject--" + subject);
    if (message.contains("[Offline message -") && !number.equals("sip:registrar@kamailio.org")) {
        System.out.println("offline message");
        String[] finalMessage = message.split("]");
        subject = finalMessage[finalMessage.length - 1];
    } else {
        subject = message;
    }

    String errorTxt = msg.getErrorContent();
    String mimeType = msg.getMimeType();
    int type = msg.getType();

    Log.setLogLevel(6);
    Log.d("Col count", cursor.getColumnCount() + " @");

    String[] columnname = cursor.getColumnNames();
    for (int i = 0; i < columnname.length; i++) {
        Log.d("columnname " + i, columnname[i] + " @");
        Log.d(columnname[i], cursor.getString(cursor.getColumnIndex(columnname[i])) + " @");

    }

    tv_msg_info = (TextView) view.findViewById(R.id.tv_msg_info);
    pb_uploading = (ProgressBar) view.findViewById(R.id.pb_uploading);

    String timestamp = "";
    if (System.currentTimeMillis() - date > 1000 * 60 * 60 * 24) {
        // If it was recieved one day ago or more display relative
        // timestamp - SMS like behavior
        int flags = DateUtils.FORMAT_ABBREV_RELATIVE;
        timestamp = (String) DateUtils.getRelativeTimeSpanString(date, System.currentTimeMillis(),
                DateUtils.MINUTE_IN_MILLIS, flags);
    } else {
        // If it has been recieved recently show time of reception - IM
        // like behavior
        timestamp = dateFormatter.format(new Date(date));
    }

    tagView.dateView.setText(timestamp);

    // Delivery state
    if (type == SipMessage.MESSAGE_TYPE_QUEUED) {
        tagView.deliveredIndicator.setVisibility(View.VISIBLE);
        tagView.deliveredIndicator.setImageResource(R.drawable.error_watch_not_send);
        tagView.deliveredIndicator.setContentDescription("");
    } else if (type == SipMessage.MESSAGE_TYPE_FAILED) {
        tagView.deliveredIndicator.setVisibility(View.VISIBLE);
        tagView.deliveredIndicator.setImageResource(R.drawable.error_watch_not_send);
        tagView.deliveredIndicator.setContentDescription("");
    } else {
        tagView.deliveredIndicator.setVisibility(View.VISIBLE);
        tagView.deliveredIndicator.setImageResource(R.drawable.todo_send);
        tagView.deliveredIndicator.setContentDescription("");
    }

    if (TextUtils.isEmpty(errorTxt)) {
        tagView.errorView.setVisibility(View.GONE);
    } else {
        tagView.errorView.setVisibility(View.GONE);
        tagView.errorView.setText(errorTxt);
    }

    // Subject
    tagView.contentView.setText(formatMessage(number, subject, mimeType));
    if (msg.isOutgoing()) {
        setPhotoSide(tagView, ArrowPosition.LEFT);
        LinearLayout linerLayout = (LinearLayout) view.findViewById(R.id.message_block);
        linerLayout.setBackgroundResource(R.drawable.chatedittextdesign);
        text_view = (TextView) view.findViewById(R.id.text_view);
        text_view.setTextColor(Color.BLACK);

        // Photo
        tagView.quickContactView.assignContactUri(personalInfo.contactContentUri);
        /*
        ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext, 
            tagView.quickContactView.getImageView(),
            personalInfo,
            R.drawable.ic_contact_picture_holo_dark);
         */

        System.out.println("msg adp out - 0");
        String path = "/sdcard/R4W/ProfilePic/ProfilePic.png";
        File user_imageFile = new File(path);
        if (user_imageFile.exists()) {
            try {
                if (bm != null) {
                    //      bm = null;
                }
                bm = BitmapFactory.decodeFile(path);
                bm = ImageHelperCircular.getRoundedCornerBitmap(bm, bm.getWidth());
                tagView.quickContactView.getImageView().setImageBitmap(bm);
            } catch (Exception e) {
                // TODO: handle exception
                try {
                    tagView.quickContactView.getImageView().setImageURI(Uri.parse(path));

                } catch (Exception e2) {
                    ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext,
                            tagView.quickContactView.getImageView(), personalInfo,
                            R.drawable.ic_contact_picture_holo_dark);
                    // TODO: handle exception
                }
            }
        } else {
            ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext,
                    tagView.quickContactView.getImageView(), personalInfo,
                    R.drawable.ic_contact_picture_holo_dark);

        }

        outgoingImage(number);

    } else {

        setPhotoSide(tagView, ArrowPosition.RIGHT);
        LinearLayout linerLayout = (LinearLayout) view.findViewById(R.id.message_block);
        linerLayout.setBackgroundResource(R.drawable.messagebodyleft);

        // Contact
        CallerInfo info = CallerInfo.getCallerInfoFromSipUri(mContext, msg.getFullFrom());

        text_view = (TextView) view.findViewById(R.id.text_view);
        text_view.setTextColor(Color.BLACK);
        pb_uploading.setVisibility(ProgressBar.GONE);

        // Photo
        tagView.quickContactView.assignContactUri(info.contactContentUri);
        /*
        ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext, 
            tagView.quickContactView.getImageView(),
            info,
            R.drawable.ic_contact_picture_holo_dark);
           */
        System.out.println("msg adp in - 1");
        String nu = stripNumber(number);
        String path = "/sdcard/R4W/ProfilePic/" + nu + ".png";
        System.out.println("msg adp out - path=" + path);
        File user_imageFile = new File(path);
        if (user_imageFile.exists()) {
            try {
                if (bm != null) {
                    //      bm = null;
                }
                bm = BitmapFactory.decodeFile(path);
                bm = ImageHelperCircular.getRoundedCornerBitmap(bm, bm.getWidth());
                tagView.quickContactView.getImageView().setImageBitmap(bm);
            } catch (Exception e) {
                // TODO: handle exception
                try {
                    tagView.quickContactView.getImageView().setImageURI(Uri.parse(path));

                } catch (Exception e2) {
                    ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext,
                            tagView.quickContactView.getImageView(), info,
                            R.drawable.ic_contact_picture_holo_dark); // TODO: handle exception
                }
            }
        } else {
            ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext,
                    tagView.quickContactView.getImageView(), info, R.drawable.ic_contact_picture_holo_dark);
        }
        incomingImage();
    }

}

From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java

/**
 * Return all the columns in the given table, including any metadata columns.
 * This does a direct query against the database and is suitable for accessing
 * non-managed tables. It does not access any metadata and therefore will not
 * report non-unit-of-retention (grouping) columns.
 * //from  w ww .  j  a  v  a  2  s  .  com
 * @param db
 * @param tableId
 * @return
 */
public String[] getAllColumnNames(SQLiteDatabase db, String tableId) {
    Cursor cursor = db.rawQuery("SELECT * FROM " + tableId + " LIMIT 1", null);
    String[] colNames = cursor.getColumnNames();

    return colNames;
}

From source file:org.opendatakit.services.database.utilities.ODKDatabaseImplUtils.java

/**
 * Return all the columns in the given table, including any metadata columns.
 * This does a direct query against the database and is suitable for accessing
 * non-managed tables. It does not access any metadata and therefore will not
 * report non-unit-of-retention (grouping) columns.
 *
 * @param db/*from   ww  w .j a v  a 2 s .  co  m*/
 * @param tableId
 * @return
 */
public String[] getAllColumnNames(OdkConnectionInterface db, String tableId) {
    Cursor cursor = null;
    try {
        StringBuilder b = new StringBuilder();
        b.append(K_SELECT_FROM).append(tableId).append(K_LIMIT).append("1");
        cursor = db.rawQuery(b.toString(), null);
        // If this query has been executed before, the cursor is created using the
        // previously-constructed PreparedStatement for the query. There is no actual
        // interaction with the database itself at the time the Cursor is constructed.
        // The first database interaction is when the content of the cursor is fetched.
        //
        // This can be triggered by a call to getCount().
        // At that time, if the table does not exist, it will throw an exception.
        cursor.moveToFirst();
        cursor.getCount();
        // Otherwise, when cached, getting the column names doesn't call into the database
        // and will not, itself, detect that the table has been dropped.
        String[] colNames = cursor.getColumnNames();
        return colNames;
    } finally {
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
    }
}