Example usage for android.database Cursor getColumnIndex

List of usage examples for android.database Cursor getColumnIndex

Introduction

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

Prototype

int getColumnIndex(String columnName);

Source Link

Document

Returns the zero-based index for the given column name, or -1 if the column doesn't exist.

Usage

From source file:com.riasayu.gosuke.sunshine.FetchWeatherTask.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName A human-readable city name, e.g "Mountain View"
 * @param lat the latitude of the city//from  www.  ja  v  a  2 s .  com
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
public long addLocation(String locationSetting, String cityName, double lat, double lon) {
    // Students: First, check if the location with this city name exists in the db
    // If it exists, return the current ID
    // Otherwise, insert it using the content resolver and the base URI
    long locationRowId = -1;
    Cursor cursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI, null,
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting },
            null);
    if (cursor.moveToFirst()) {
        locationRowId = cursor.getLong(cursor.getColumnIndex(WeatherContract.LocationEntry._ID));
    } else {
        ContentValues locationValues = new ContentValues();
        locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        Uri locationUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                locationValues);
        locationRowId = ContentUris.parseId(locationUri);
    }
    return locationRowId;
}

From source file:com.intel.xdk.contacts.Contacts.java

@SuppressWarnings("deprecation")
public void contactsAdderActivityResult(int requestCode, int resultCode, Intent intent) {

    //Contact Added
    if (resultCode == Activity.RESULT_OK) {
        Cursor cursor = activity.managedQuery(intent.getData(), null, null, null, null);
        cursor.moveToNext();/* w ww .  ja  va 2  s .  c om*/
        String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));

        getAllContacts();
        String js = String.format(
                "var e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.add',true,true);e.success=true;e.contactid='%s';document.dispatchEvent(e);",
                contactId);

        injectJS("javascript:" + js);
        busy = false;
    }
    //Contact not Added
    else {
        String js = "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.add',true,true);e.success=false;e.cancelled=true;document.dispatchEvent(e);";
        injectJS(js);
        busy = false;
    }

}

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

String getAppDataFromDb(String column, String packagename) {
    if (packagename == null || column == null) {
        Log.i(DBTAG, "packagename or column is null");
        return null;
    }/* ww  w. j a v  a2  s.  com*/
    if (column != DATA_COL && column != URL_COL) {
        Log.i(DBTAG, "Not an acceptable query column");
        return null;
    }

    synchronized (sAppTableLock) {
        String ret_data = null;
        Cursor cursor = null;
        try {
            cursor = sDatabase.query(APP_TABLE_NAME, null, PACKAGE_COL + "='" + packagename + "'", null, null,
                    null, null, null);
            if (cursor.moveToFirst()) {
                ret_data = new String(cursor.getString(cursor.getColumnIndex(column)));
            }

        } catch (IllegalStateException e) {
            Log.e(DBTAG, "getAppDataFromDB failed", e);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
        Log.i(DBTAG, "DB Query: return data:" + ret_data);
        return ret_data;
    }
}

From source file:org.opensmc.mytracks.cyclesmc.TripUploader.java

private JSONObject getCoordsJSON(long tripId) throws JSONException {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);

    mDb.openReadOnly();//  ww  w  .j  ava2 s  .  c o m
    Cursor tripCoordsCursor = mDb.fetchAllCoordsForTrip(tripId);

    // Build the map between JSON fieldname and phone db fieldname:
    Map<String, Integer> fieldMap = new HashMap<String, Integer>();
    fieldMap.put(TRIP_COORDS_TIME, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_TIME));
    fieldMap.put(TRIP_COORDS_LAT, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LAT));
    fieldMap.put(TRIP_COORDS_LON, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LGT));
    fieldMap.put(TRIP_COORDS_ALT, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ALT));
    fieldMap.put(TRIP_COORDS_SPEED, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_SPEED));
    fieldMap.put(TRIP_COORDS_HACCURACY, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC));
    fieldMap.put(TRIP_COORDS_VACCURACY, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC));

    // Build JSON objects for each coordinate:
    JSONObject tripCoords = new JSONObject();
    while (!tripCoordsCursor.isAfterLast()) {
        JSONObject coord = new JSONObject();

        coord.put(TRIP_COORDS_TIME, df.format(tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_TIME))));
        coord.put(TRIP_COORDS_LAT, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LAT)));
        coord.put(TRIP_COORDS_LON, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LON)));
        coord.put(TRIP_COORDS_ALT, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_ALT)));
        coord.put(TRIP_COORDS_SPEED, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_SPEED)));
        coord.put(TRIP_COORDS_HACCURACY, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_HACCURACY)));
        coord.put(TRIP_COORDS_VACCURACY, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_VACCURACY)));

        tripCoords.put(coord.getString("rec"), coord);
        tripCoordsCursor.moveToNext();
    }
    tripCoordsCursor.close();
    mDb.close();
    return tripCoords;
}

From source file:com.wso2.mobile.mdm.api.TrackCallSMS.java

/**
 * Returns a JSONArray of SMS objects Ex: [{number:"0772345666", date:"dd/MM/yyyy hh:mm:ss.SSS", content:"Hello"}]
 * //from  w w w . j  ava  2s. co  m
 * @param type
 *            - Folder type should be passed in (1 for Inbox, 2 for Sent box)
 */
public JSONArray getSMS(int type) {
    JSONArray jsonArray = null;
    try {
        Uri uriSms = Uri.parse("content://sms");

        Cursor cursor = cr.query(uriSms, new String[] { "_id", "address", "date", "body", "type", "read" },
                "type=" + type, null, "date" + " COLLATE LOCALIZED ASC");

        if (cursor != null) {
            cursor.moveToLast();
            if (cursor.getCount() > 0) {
                jsonArray = new JSONArray();
                do {
                    JSONObject jsonObj = new JSONObject();
                    String date = cursor.getString(cursor.getColumnIndex("date"));
                    Long timestamp = Long.parseLong(date);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(timestamp);
                    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
                    jsonObj.put("number", cursor.getString(cursor.getColumnIndex("address")));
                    jsonObj.put("date", formatter.format(calendar.getTime()));
                    /*jsonObj.put("content",
                          cursor.getString(cursor.getColumnIndex("body")));*/
                    //jsonObj.put("content","Testing SMS");
                    jsonArray.add(jsonObj);
                } while (cursor.moveToPrevious());
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return jsonArray;

}

From source file:com.ritul.truckshare.RegisterActivity.DriverLicenseActivity.java

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == Utility.GALLERY_PICTURE && data != null) {
        isImage = true;//from  ww w .  j a v  a  2 s . c o  m
        // data contains result
        // Do some task
        Image_Selecting_Task(data);
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = DriverLicenseActivity.this.getContentResolver().query(selectedImage, filePathColumn,
                null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        selectedpath = cursor.getString(columnIndex);
        cursor.close();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 8;
        final Bitmap bitmap = BitmapFactory.decodeFile(selectedpath, options);
        convertimagetobyte();
        imagedata = Base64.encodeToString(imageByte, Base64.DEFAULT);
    } else if (requestCode == Utility.CAMERA_PICTURE && data != null) {
        isImage = true;
        // Do some task
        //Image_Selecting_Task(data);
        if (requestCode == Utility.CAMERA_PICTURE && resultCode == RESULT_OK && data != null) {
            Bitmap photo = (Bitmap) data.getExtras().get("data");
            preview.setImageBitmap(photo);

            Bitmap bitmap = ((BitmapDrawable) preview.getDrawable()).getBitmap();
            imagedata = Base64.encodeToString(getBytesFromBitmap(bitmap), Base64.DEFAULT);

        }
    }
}

From source file:org.noorganization.instalistsynch.controller.local.dba.impl.ClientLogDbController.java

@Override
public Date getLeastRecentUpdateTimeForUuid(String _clientUuid) {
    Cursor cursor = mContentResolver.query(Uri.withAppendedPath(InstalistProvider.BASE_CONTENT_URI, "log"),
            LogInfo.COLUMN.ALL_COLUMNS, LogInfo.COLUMN.ITEM_UUID + " LIKE ? ", new String[] { _clientUuid },
            LogInfo.COLUMN.ACTION_DATE + " DESC ");
    if (cursor == null) {
        return null;
    }//  w w  w .  j  a va 2  s .c o m
    if (cursor.getCount() == 0) {
        cursor.close();
        return null;
    }
    cursor.moveToFirst();

    String date = cursor.getString(cursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE));
    try {
        return ISO8601Utils.parse(date, new ParsePosition(0));
    } catch (ParseException e) {
        e.printStackTrace();
        return null;
    } finally {
        cursor.close();
    }
}

From source file:com.openerp.base.res.Res_PartnerSyncHelper.java

public void syncContacts(Context context, Account account) {
    HashMap<String, SyncEntry> localContacts = new HashMap<String, SyncEntry>();
    mContentResolver = context.getContentResolver();
    int company_id = Integer.parseInt(OpenERPAccountManager.currentUser(context).getCompany_id());

    RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true")
            .build();//from   ww w.  ja va 2 s  . com

    // Load the local contacts
    Uri rawContactUri = RawContacts.CONTENT_URI.buildUpon()
            .appendQueryParameter(RawContacts.ACCOUNT_NAME, account.name)
            .appendQueryParameter(RawContacts.ACCOUNT_TYPE, account.type).build();
    Cursor cursor = mContentResolver.query(rawContactUri, new String[] { BaseColumns._ID, SYNC1_PARTNER_ID },
            null, null, null);

    while (cursor.moveToNext()) {
        SyncEntry entry = new SyncEntry();
        entry.partner_id = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
        localContacts.put(cursor.getString(1), entry);
    }
    cursor.close();

    try {
        Res_PartnerDBHelper dbHelper = new Res_PartnerDBHelper(context);
        HashMap<String, Object> res = dbHelper.search(dbHelper,
                new String[] { "phone != ? ", "OR", "mobile != ? ", "OR", "email != ?" },
                new String[] { "false", "false", "false" });
        // checking if records exist?
        int total = Integer.parseInt(res.get("total").toString());

        if (total > 0) {
            @SuppressWarnings("unchecked")
            List<HashMap<String, Object>> rows = (List<HashMap<String, Object>>) res.get("records");

            for (HashMap<String, Object> row_data : rows) {

                if (!(row_data.get("company_id").toString()).equalsIgnoreCase("false")) {
                    JSONArray db_company_id = new JSONArray(row_data.get("company_id").toString());
                    String com_id = db_company_id.getJSONArray(0).getString(0).toString();

                    if (com_id.equalsIgnoreCase(String.valueOf(company_id))) {
                        String partnerID = row_data.get("id").toString();
                        String name = (row_data.get("name").toString()).replaceAll("[^\\w\\s]", "");
                        String mail = row_data.get("email").toString();
                        String number = row_data.get("phone").toString();
                        String mobile = row_data.get("mobile").toString();
                        String website = row_data.get("website").toString();
                        String street = row_data.get("street").toString();
                        String street2 = row_data.get("street2").toString();
                        String city = row_data.get("city").toString();
                        String zip = row_data.get("zip").toString();
                        String company = "OpenERP";
                        String image = row_data.get("image_small").toString();
                        if (localContacts.get(row_data.get("id").toString()) == null) {
                            addContact(context, account, partnerID, name, mail, number, mobile, website, street,
                                    street2, city, zip, company, image);
                        }
                    }
                }

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

From source file:net.mutina.uclimb.ForegroundCameraLauncher.java

/**
 * Used to find out if we are in a situation where the Camera Intent adds to images
 * to the content store. If we are using a FILE_URI and the number of images in the DB 
 * increases by 2 we have a duplicate, when using a DATA_URL the number is 1.
 *//*ww w .j  a  v a 2 s .c  o m*/
private void checkForDuplicateImage() {
    int diff = 2;
    Cursor cursor = queryImgDB();
    int currentNumOfImages = cursor.getCount();

    // delete the duplicate file if the difference is 2 for file URI or 1 for Data URL
    if ((currentNumOfImages - numPics) == diff) {
        cursor.moveToLast();
        int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))) - 1;
        Uri uri = Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/" + id);
        this.ctx.getContentResolver().delete(uri, null, null);
    }
}

From source file:com.nonninz.robomodel.RoboModel.java

private void loadField(Field field, Cursor query) throws DatabaseNotUpToDateException {
    final Class<?> type = field.getType();
    final boolean wasAccessible = field.isAccessible();
    final int columnIndex = query.getColumnIndex(field.getName());
    field.setAccessible(true);//from w  ww . j  a  v  a2 s  .  com

    /*
     * TODO: There is the potential of a problem here:
     * What happens if the developer changes the type of a field between releases?
     *
     * If he saves first, then the column type will be changed (In the future).
     * If he loads first, we don't know if an Exception will be thrown if the
     * types are incompatible, because it's undocumented in the Cursor documentation.
     */

    try {
        if (type == String.class) {
            field.set(this, query.getString(columnIndex));
        } else if (type == Boolean.TYPE) {
            final boolean value = query.getInt(columnIndex) == 1 ? true : false;
            field.setBoolean(this, value);
        } else if (type == Byte.TYPE) {
            field.setByte(this, (byte) query.getShort(columnIndex));
        } else if (type == Double.TYPE) {
            field.setDouble(this, query.getDouble(columnIndex));
        } else if (type == Float.TYPE) {
            field.setFloat(this, query.getFloat(columnIndex));
        } else if (type == Integer.TYPE) {
            field.setInt(this, query.getInt(columnIndex));
        } else if (type == Long.TYPE) {
            field.setLong(this, query.getLong(columnIndex));
        } else if (type == Short.TYPE) {
            field.setShort(this, query.getShort(columnIndex));
        } else if (type.isEnum()) {
            final String string = query.getString(columnIndex);
            if (string != null && string.length() > 0) {
                final Object[] constants = type.getEnumConstants();
                final Method method = type.getMethod("valueOf", Class.class, String.class);
                final Object value = method.invoke(constants[0], type, string);
                field.set(this, value);
            }
        } else {
            // Try to de-json it (db column must be of type text)
            try {
                final Object value = mMapper.readValue(query.getString(columnIndex), field.getType());
                field.set(this, value);
            } catch (final Exception e) {
                final String msg = String.format("Type %s is not supported for field %s", type,
                        field.getName());
                Ln.w(e, msg);
                throw new IllegalArgumentException(msg);
            }
        }
    } catch (final IllegalAccessException e) {
        final String msg = String.format("Field %s is not accessible", type, field.getName());
        throw new IllegalArgumentException(msg);
    } catch (final NoSuchMethodException e) {
        // Should not happen
        throw new RuntimeException(e);
    } catch (final InvocationTargetException e) {
        // Should not happen
        throw new RuntimeException(e);
    } catch (IllegalStateException e) {
        // This is when there is no column in db, but there is in the model
        throw new DatabaseNotUpToDateException(e);
    } finally {
        field.setAccessible(wasAccessible);
    }
}