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.facebook.stetho.inspector.protocol.module.Database.java

@ChromeDevtoolsMethod
public JsonRpcResult executeSQL(JsonRpcPeer peer, JSONObject params) {
    ExecuteSQLRequest request = mObjectMapper.convertValue(params, ExecuteSQLRequest.class);
    try {// w  w  w.  j  a  va 2s.co  m
        return mDatabasePeerManager.executeSQL(request.databaseId, request.query,
                new DatabasePeerManager.ExecuteResultHandler<ExecuteSQLResponse>() {
                    @Override
                    public ExecuteSQLResponse handleRawQuery() throws SQLiteException {
                        ExecuteSQLResponse response = new ExecuteSQLResponse();
                        // This is done because the inspector UI likes to delete rows if you give them no
                        // name/value list
                        response.columnNames = Arrays.asList("success");
                        response.values = Arrays.asList((Object) "true");
                        return response;
                    }

                    @Override
                    public ExecuteSQLResponse handleSelect(Cursor result) throws SQLiteException {
                        ExecuteSQLResponse response = new ExecuteSQLResponse();
                        response.columnNames = Arrays.asList(result.getColumnNames());
                        response.values = flattenRows(result, MAX_EXECUTE_RESULTS);
                        return response;
                    }

                    @Override
                    public ExecuteSQLResponse handleInsert(long insertedId) throws SQLiteException {
                        ExecuteSQLResponse response = new ExecuteSQLResponse();
                        response.columnNames = Arrays.asList("ID of last inserted row");
                        response.values = Arrays.asList((Object) insertedId);
                        return response;
                    }

                    @Override
                    public ExecuteSQLResponse handleUpdateDelete(int count) throws SQLiteException {
                        ExecuteSQLResponse response = new ExecuteSQLResponse();
                        response.columnNames = Arrays.asList("Modified rows");
                        response.values = Arrays.asList((Object) count);
                        return response;
                    }
                });
    } catch (SQLiteException e) {
        Error error = new Error();
        error.code = 0;
        error.message = e.getMessage();
        ExecuteSQLResponse response = new ExecuteSQLResponse();
        response.sqlError = error;
        return response;
    }
}

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

/**
 * Exactly as per <a href=/*from   w ww  . j  a  v  a2  s.c  om*/
 * "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:io.v.android.apps.syncslides.SignInActivity.java

private void fetchUserNameFromContacts() {
    // Get the user's full name from Contacts.
    Cursor c = getContentResolver().query(ContactsContract.Profile.CONTENT_URI, null, null, null, null);
    String[] columnNames = c.getColumnNames();
    String userName = "Anonymous User";
    while (c.moveToNext()) {
        for (int j = 0; j < columnNames.length; j++) {
            String columnName = columnNames[j];
            if (!columnName.equals(ContactsContract.Contacts.DISPLAY_NAME)) {
                continue;
            }//from  w w  w .j  a  v  a 2  s . c o  m
            userName = c.getString(c.getColumnIndex(columnName));
        }
    }
    c.close();
    SharedPreferences.Editor editor = mPrefs.edit();
    editor.putString(PREF_USER_NAME_FROM_CONTACTS, userName);
    editor.commit();
}

From source file:com.android.messaging.FakeContentProvider.java

@Override
public Cursor query(final Uri uri, final String[] projection, final String selection,
        final String[] selectionArgs, final String sortOrder) {
    LogUtil.w(LogUtil.BUGLE_TAG,// w  w  w.  ja va2s  .  c  o  m
            "FakeContentProvider: query " + uri.toString() + " for "
                    + (projection == null ? null : TextUtils.join(",", projection)) + " where " + selection
                    + " with " + (selectionArgs == null ? null : TextUtils.join(";", selectionArgs)));

    for (final ContentOverride content : mOverrides) {
        if (content.match(uri.toString(), selection, selectionArgs)) {
            return new FakeCursor(projection, content.columns, content.data);
        }
    }
    if (mProvider != null) {
        try {
            LogUtil.w(LogUtil.BUGLE_TAG, "FakeContentProvider: delgating");

            final Cursor cursor = mProvider.query(uri, projection, selection, selectionArgs, sortOrder);

            LogUtil.w(LogUtil.BUGLE_TAG,
                    "FakeContentProvider: response size " + cursor.getCount() + " contains "
                            + TextUtils.join(",", cursor.getColumnNames()) + " type(0) " + cursor.getType(0));

            return cursor;
        } catch (final RemoteException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.futureplatforms.kirin.extensions.databases.DatabasesBackend.java

private String[] columnNames(Cursor cursor) {
    String[] cols = cursor.getColumnNames();

    for (int i = 0, count = cols.length; i < count; i++) {
        String columnName = cols[i];

        int dot = columnName.indexOf('.');
        if (dot >= 0) {
            // assume that the column name will never end in dot.
            columnName = columnName.substring(dot + 1);
        }//from  w w w  .jav a 2  s .  c o m
        cols[i] = columnName;

    }
    return cols;
}

From source file:com.cloudstudio.camera.ForegroundCameraLauncher.java

/**
 * Queries the media store to find out what the file path is for the Uri we
 * supply/*from  ww w.j a v a2  s.c  om*/
 * 
 * @param contentUri
 *            the Uri of the audio/image/video
 * @param ctx
 *            the current applicaiton context
 * @return the full path to the file
 */
private String getRealPathFromURI(Uri contentUri, CordovaInterface ctx) {
    String[] proj = { _DATA };
    Cursor cursor = cordova.getActivity().managedQuery(contentUri, proj, null, null, null);
    String[] dd = cursor.getColumnNames();
    int column_index = cursor.getColumnIndexOrThrow(_DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

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

private String findPhone(String id) {
    String result = null;//from  ww  w . j  av  a 2  s  . com
    if (id == null || id.equals("")) {
        return result;
    }
    try {
        if (Integer.parseInt(id) > 0) {
            Cursor pCur = mContentResolver.query(mPhoneContent, new String[] { mPhoneNumber },
                    mContactId + " = ? and " + mPrimary + "=1", new String[] { id }, null);
            if (pCur != null) {
                pCur.getColumnNames();
                while (pCur.moveToNext()) {
                    result = pCur.getString(0);
                    break;
                }
            }
            pCur.close();
        }
    } catch (Exception e) {
        return null;
    }
    return result;
}

From source file:com.taobao.weex.devtools.inspector.protocol.module.Database.java

@ChromeDevtoolsMethod
public JsonRpcResult executeSQL(JsonRpcPeer peer, JSONObject params) {
    ExecuteSQLRequest request = mObjectMapper.convertValue(params, ExecuteSQLRequest.class);

    String databaseId = request.databaseId;
    String query = request.query;

    DatabaseDriver databaseDriver = getDatabasePeer(databaseId);

    try {//from  w ww . j av a2s .  c  o  m
        return databaseDriver.executeSQL(request.databaseId, request.query,
                new DatabaseDriver.ExecuteResultHandler<ExecuteSQLResponse>() {
                    @Override
                    public ExecuteSQLResponse handleRawQuery() throws SQLiteException {
                        ExecuteSQLResponse response = new ExecuteSQLResponse();
                        // This is done because the inspector UI likes to delete rows if you give them no
                        // name/value list
                        response.columnNames = Collections.singletonList("success");
                        response.values = Collections.singletonList("true");
                        return response;
                    }

                    @Override
                    public ExecuteSQLResponse handleSelect(Cursor result) throws SQLiteException {
                        ExecuteSQLResponse response = new ExecuteSQLResponse();
                        response.columnNames = Arrays.asList(result.getColumnNames());
                        response.values = flattenRows(result, MAX_EXECUTE_RESULTS);
                        return response;
                    }

                    @Override
                    public ExecuteSQLResponse handleInsert(long insertedId) throws SQLiteException {
                        ExecuteSQLResponse response = new ExecuteSQLResponse();
                        response.columnNames = Collections.singletonList("ID of last inserted row");
                        response.values = Collections.singletonList(String.valueOf(insertedId));
                        return response;
                    }

                    @Override
                    public ExecuteSQLResponse handleUpdateDelete(int count) throws SQLiteException {
                        ExecuteSQLResponse response = new ExecuteSQLResponse();
                        response.columnNames = Collections.singletonList("Modified rows");
                        response.values = Collections.singletonList(String.valueOf(count));
                        return response;
                    }
                });
    } catch (SQLiteException e) {
        Error error = new Error();
        error.code = 0;
        error.message = e.getMessage();
        ExecuteSQLResponse response = new ExecuteSQLResponse();
        response.sqlError = error;
        return response;
    }
}

From source file:com.aware.utils.WebserviceHelper.java

@Override
protected void onHandleIntent(Intent intent) {

    WEBSERVER = Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER);
    DEVICE_ID = Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID);
    DEBUG = Aware.getSetting(getApplicationContext(), Aware_Preferences.DEBUG_FLAG).equals("true");
    DATABASE_TABLE = intent.getStringExtra(EXTRA_TABLE);
    TABLES_FIELDS = intent.getStringExtra(EXTRA_FIELDS);
    CONTENT_URI = Uri.parse(intent.getStringExtra(EXTRA_CONTENT_URI));

    //Fixed: not using webservices
    if (WEBSERVER.length() == 0)
        return;/*from   ww  w . ja va 2  s  .c o  m*/

    if (intent.getAction().equals(ACTION_AWARE_WEBSERVICE_SYNC_TABLE)) {

        //Check if we should do this only over Wi-Fi
        boolean wifi_only = Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_WIFI_ONLY)
                .equals("true");
        if (wifi_only) {
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo active_network = cm.getActiveNetworkInfo();
            if (active_network != null && active_network.getType() != ConnectivityManager.TYPE_WIFI) {
                if (DEBUG) {
                    Log.i("AWARE", "User not connected to Wi-Fi, skipping data sync.");
                }
                return;
            }
        }

        //Check first if we have database table remotely, otherwise create it!
        ArrayList<NameValuePair> fields = new ArrayList<NameValuePair>();
        fields.add(new BasicNameValuePair(Aware_Preferences.DEVICE_ID, DEVICE_ID));
        fields.add(new BasicNameValuePair(EXTRA_FIELDS, TABLES_FIELDS));

        //Create table if doesn't exist on the remote webservice server
        HttpResponse response = new Https(getApplicationContext())
                .dataPOST(WEBSERVER + "/" + DATABASE_TABLE + "/create_table", fields);
        if (response != null && response.getStatusLine().getStatusCode() == 200) {
            if (DEBUG) {
                HttpResponse copy = response;
                try {
                    if (DEBUG)
                        Log.d(Aware.TAG, EntityUtils.toString(copy.getEntity()));
                } catch (ParseException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            String[] columnsStr = new String[] {};
            Cursor columnsDB = getContentResolver().query(CONTENT_URI, null, null, null, null);
            if (columnsDB != null && columnsDB.moveToFirst()) {
                columnsStr = columnsDB.getColumnNames();
                if (DEBUG)
                    Log.d(Aware.TAG, "Total records on " + DATABASE_TABLE + ": " + columnsDB.getCount());
            }
            if (columnsDB != null && !columnsDB.isClosed())
                columnsDB.close();

            try {
                ArrayList<NameValuePair> request = new ArrayList<NameValuePair>();
                request.add(new BasicNameValuePair(Aware_Preferences.DEVICE_ID, DEVICE_ID));

                //check the latest entry in remote database
                HttpResponse latest = new Https(getApplicationContext())
                        .dataPOST(WEBSERVER + "/" + DATABASE_TABLE + "/latest", request);
                if (latest == null)
                    return;

                String data = "[]";
                try {
                    data = EntityUtils.toString(latest.getEntity());
                } catch (IllegalStateException e) {
                    Log.d(Aware.TAG, "Unable to connect to webservices...");
                }

                if (DEBUG) {
                    Log.d(Aware.TAG, "Webservice response: " + data);
                }

                //If in a study, get from joined date onwards
                String study_condition = "";
                if (Aware.getSetting(getApplicationContext(), "study_id").length() > 0
                        && Aware.getSetting(getApplicationContext(), "study_start").length() > 0) {
                    String study_start = Aware.getSetting(getApplicationContext(), "study_start");
                    study_condition = " AND timestamp > " + Long.parseLong(study_start);
                }
                if (DATABASE_TABLE.equalsIgnoreCase("aware_device"))
                    study_condition = "";

                JSONArray remoteData = new JSONArray(data);

                Cursor context_data;
                if (remoteData.length() == 0) {
                    if (exists(columnsStr, "double_end_timestamp")) {
                        context_data = getContentResolver().query(CONTENT_URI, null,
                                "double_end_timestamp != 0" + study_condition, null, "timestamp ASC");
                    } else if (exists(columnsStr, "double_esm_user_answer_timestamp")) {
                        context_data = getContentResolver().query(CONTENT_URI, null,
                                "double_esm_user_answer_timestamp != 0" + study_condition, null,
                                "timestamp ASC");
                    } else {
                        context_data = getContentResolver().query(CONTENT_URI, null, "1" + study_condition,
                                null, "timestamp ASC");
                    }
                } else {
                    long last = 0;
                    if (exists(columnsStr, "double_end_timestamp")) {
                        last = remoteData.getJSONObject(0).getLong("double_end_timestamp");
                        context_data = getContentResolver().query(CONTENT_URI, null,
                                "timestamp > " + last + " AND double_end_timestamp != 0" + study_condition,
                                null, "timestamp ASC");
                    } else if (exists(columnsStr, "double_esm_user_answer_timestamp")) {
                        last = remoteData.getJSONObject(0).getLong("double_esm_user_answer_timestamp");
                        context_data = getContentResolver().query(
                                CONTENT_URI, null, "timestamp > " + last
                                        + " AND double_esm_user_answer_timestamp != 0" + study_condition,
                                null, "timestamp ASC");
                    } else {
                        last = remoteData.getJSONObject(0).getLong("timestamp");
                        context_data = getContentResolver().query(CONTENT_URI, null,
                                "timestamp > " + last + study_condition, null, "timestamp ASC");
                    }
                }

                JSONArray context_data_entries = new JSONArray();
                if (context_data != null && context_data.moveToFirst()) {
                    if (DEBUG)
                        Log.d(Aware.TAG, "Uploading " + context_data.getCount() + " from " + DATABASE_TABLE);

                    do {
                        JSONObject entry = new JSONObject();

                        String[] columns = context_data.getColumnNames();
                        for (String c_name : columns) {

                            //Skip local database ID
                            if (c_name.equals("_id"))
                                continue;

                            if (c_name.equals("timestamp") || c_name.contains("double")) {
                                entry.put(c_name, context_data.getDouble(context_data.getColumnIndex(c_name)));
                            } else if (c_name.contains("float")) {
                                entry.put(c_name, context_data.getFloat(context_data.getColumnIndex(c_name)));
                            } else if (c_name.contains("long")) {
                                entry.put(c_name, context_data.getLong(context_data.getColumnIndex(c_name)));
                            } else if (c_name.contains("blob")) {
                                entry.put(c_name, context_data.getBlob(context_data.getColumnIndex(c_name)));
                            } else if (c_name.contains("integer")) {
                                entry.put(c_name, context_data.getInt(context_data.getColumnIndex(c_name)));
                            } else {
                                entry.put(c_name, context_data.getString(context_data.getColumnIndex(c_name)));
                            }
                        }
                        context_data_entries.put(entry);

                        if (context_data_entries.length() == 1000) {
                            request = new ArrayList<NameValuePair>();
                            request.add(new BasicNameValuePair(Aware_Preferences.DEVICE_ID, DEVICE_ID));
                            request.add(new BasicNameValuePair("data", context_data_entries.toString()));
                            new Https(getApplicationContext())
                                    .dataPOST(WEBSERVER + "/" + DATABASE_TABLE + "/insert", request);

                            context_data_entries = new JSONArray();
                        }
                    } while (context_data.moveToNext());

                    if (context_data_entries.length() > 0) {
                        request = new ArrayList<NameValuePair>();
                        request.add(new BasicNameValuePair(Aware_Preferences.DEVICE_ID, DEVICE_ID));
                        request.add(new BasicNameValuePair("data", context_data_entries.toString()));
                        new Https(getApplicationContext())
                                .dataPOST(WEBSERVER + "/" + DATABASE_TABLE + "/insert", request);
                    }
                } else {
                    if (DEBUG)
                        Log.d(Aware.TAG,
                                "Nothing new in " + DATABASE_TABLE + "!" + " URI=" + CONTENT_URI.toString());
                }

                if (context_data != null && !context_data.isClosed())
                    context_data.close();

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

    //Clear database table remotely
    if (intent.getAction().equals(ACTION_AWARE_WEBSERVICE_CLEAR_TABLE)) {
        ArrayList<NameValuePair> request = new ArrayList<NameValuePair>();
        request.add(new BasicNameValuePair(Aware_Preferences.DEVICE_ID, DEVICE_ID));
        new Https(getApplicationContext()).dataPOST(WEBSERVER + "/" + DATABASE_TABLE + "/clear_table", request);
    }
}

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  w  w  w. j  a  v  a 2 s  .  co 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;
}