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.prey.json.actions.ContactsBackup.java

@TargetApi(Build.VERSION_CODES.ECLAIR)
public HashMap<String, String> contacts2(Context ctx) {
    HashMap<String, String> parametersMap = new HashMap<String, String>();
    String phoneNumber = null;// ww w  .ja  va  2 s  .c  om
    int phoneType;

    String email = null;
    int emailType;

    Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;

    String _ID = ContactsContract.Contacts._ID;

    String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;

    String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;

    Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

    String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;

    String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
    String NUMBER_TYPE = ContactsContract.CommonDataKinds.Phone.TYPE;

    Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;

    String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;

    String DATA = ContactsContract.CommonDataKinds.Email.DATA;
    String DATATYPE = ContactsContract.CommonDataKinds.Email.TYPE;

    Cursor cursor = ctx.getContentResolver().query(CONTENT_URI, null, null, null, null);

    // Loop for every contact in the phone

    if (cursor.getCount() > 0) {

        int i = 0;
        while (cursor.moveToNext()) {

            String contact_id = cursor.getString(cursor.getColumnIndex(_ID));

            String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));

            int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));

            if (hasPhoneNumber > 0) {

                PreyLogger.i("____________");
                parametersMap.put("contacts_backup[" + i + "][display_name]", name);
                parametersMap.put("contacts_backup[" + i + "][nickname][name]", name);
                parametersMap.put("contacts_backup[" + i + "][nickname][label]", name);

                PreyLogger.i("contacts_backup[" + i + "][display_name]" + name);
                PreyLogger.i("contacts_backup[" + i + "][nickname][name]" + name);
                PreyLogger.i("contacts_backup[" + i + "][nickname][label]" + name);

                // Query and loop for every phone number of the contact

                Cursor phoneCursor = ctx.getContentResolver().query(PhoneCONTENT_URI, null,
                        Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);

                int j = 0;
                while (phoneCursor.moveToNext()) {

                    phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
                    phoneType = phoneCursor.getInt(phoneCursor.getColumnIndex(NUMBER_TYPE));

                    parametersMap.put("contacts_backup[" + i + "][phones][" + j + "][number]", phoneNumber);
                    parametersMap.put("contacts_backup[" + i + "][phones][" + j + "][type]",
                            typePhone(phoneType));

                    PreyLogger.i("contacts_backup[" + i + "][phones][" + j + "][number]" + phoneNumber);
                    PreyLogger.i("contacts_backup[" + i + "][phones][" + j + "][type]" + typePhone(phoneType));

                    j++;

                } // while phone

                phoneCursor.close();

                // Query and loop for every email of the contact

                Cursor emailCursor = ctx.getContentResolver().query(EmailCONTENT_URI, null,
                        EmailCONTACT_ID + " = ?", new String[] { contact_id }, null);

                j = 0;
                while (emailCursor.moveToNext()) {

                    email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
                    emailType = emailCursor.getInt(emailCursor.getColumnIndex(DATATYPE));
                    parametersMap.put("contacts_backup[" + i + "][emails][" + j + "][address]", email);
                    parametersMap.put("contacts_backup[" + i + "][emails][" + j + "][type]",
                            typeMail(emailType));

                    PreyLogger.i("contacts_backup[" + i + "][emails][" + j + "][address]" + email);
                    PreyLogger.i("contacts_backup[" + i + "][emails][" + j + "][type]" + typeMail(emailType));
                    j++;
                } // while email

                emailCursor.close();
                i = i + 1;
            } // if hasPhoneNumber

        } // while cursor
          // 
    } // if cursor
    return parametersMap;

}

From source file:com.google.android.apps.santatracker.data.DestinationDbHelper.java

public long getLastArrival() {
    SQLiteDatabase db = getReadableDatabase();
    Cursor c = db.rawQuery("SELECT " + COLUMN_NAME_ARRIVAL + " FROM " + TABLE_NAME + " ORDER BY "
            + COLUMN_NAME_ARRIVAL + " DESC LIMIT 1", null);
    c.moveToFirst();//from   w ww  .  ja  v a2  s .  c om
    long l;
    if (c.isAfterLast()) {
        l = -1;
    } else {
        l = c.getLong(c.getColumnIndex(COLUMN_NAME_ARRIVAL));
    }
    c.close();
    return l;
}

From source file:org.maikelwever.droidpile.SendMailActivity.java

public ArrayList<AutocompleteContact> getContacts() {
    ArrayList<AutocompleteContact> alContacts = new ArrayList<AutocompleteContact>();
    ContentResolver contResv = getApplication().getContentResolver();
    Cursor cursor = contResv.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    if (cursor.moveToFirst()) {
        do {//from w  ww . jav  a 2  s. c  om
            String name = cursor
                    .getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

            AutocompleteContact contact = new AutocompleteContact(id, name);

            Cursor emails = contResv.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contact.id, null, null);
            while (emails.moveToNext()) {
                contact.addEmail(
                        emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
                break;
            }
            emails.close();

            alContacts.add(contact);

        } while (cursor.moveToNext());
    }

    cursor.close();
    return alContacts;
}

From source file:it.ms.theing.loquitur.functions.PhoneDir.java

/**
 * This function returns the best matching object
 * @return//  w  w w . java 2 s .c  om
 * structure : { name:... , phone: ... , email: ... }
 */
@JavascriptInterface
public String match(String compare, float minscore) {
    Cursor cursor = null;
    try {
        JSONArray obj = new JSONArray();
        cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null,
                null);
        String ID = null;
        String name = null;
        while (cursor.moveToNext()) {

            String nam = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

            float score = Utils.match(nam, compare);
            if (score > minscore) {
                minscore = score;
                ID = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                name = nam;
            }
        }
        cursor.close();
        cursor = null;
        if (ID == null)
            return "";

        String phone = getPhone(ID);
        String email = getEmail(ID);

        JSONObject jo = new JSONObject();
        jo.put("name", name.toLowerCase());
        jo.put("phone", phone);
        jo.put("email", email);

        return jo.toString();
    } catch (Exception e) {
        Utils.safe(e);
    }

    if (cursor != null) {
        try {
            cursor.close();
        } catch (Exception e) {
        }
    }
    return "";
}

From source file:com.google.android.apps.santatracker.data.DestinationDbHelper.java

public long getFirstDeparture() {
    SQLiteDatabase db = getReadableDatabase();
    Cursor c = db.rawQuery("SELECT " + COLUMN_NAME_DEPARTURE + " FROM " + TABLE_NAME + " ORDER BY "
            + COLUMN_NAME_DEPARTURE + " ASC LIMIT 1", null);
    c.moveToFirst();/*  ww  w .j av a 2  s.co  m*/
    long l;
    if (c.isAfterLast()) {
        l = -1;
    } else {
        l = c.getLong(c.getColumnIndex(COLUMN_NAME_DEPARTURE));
    }
    c.close();
    return l;
}

From source file:com.google.android.apps.santatracker.data.DestinationDbHelper.java

public long getLastDeparture() {
    SQLiteDatabase db = getReadableDatabase();
    Cursor c = db.rawQuery("SELECT " + COLUMN_NAME_DEPARTURE + " FROM " + TABLE_NAME + " ORDER BY "
            + COLUMN_NAME_DEPARTURE + " DESC LIMIT 1", null);
    c.moveToFirst();/*from w  w w  .j ava 2 s  .c om*/
    long l;
    if (c.isAfterLast()) {
        l = -1;
    } else {
        l = c.getLong(c.getColumnIndex(COLUMN_NAME_DEPARTURE));
    }
    c.close();
    return l;
}

From source file:com.rvl.android.getnzb.LocalNZB.java

public void removeFromDatabase(String filename) {
    LocalNZBMetadata.openDatabase();/*w  ww  .  ja v  a  2 s .  com*/
    // Get file _id
    Cursor cur = LocalNZBMetadata.myDatabase.query("file", new String[] { "_id" }, "name='" + filename + "'",
            null, null, null, null);
    if (cur.moveToFirst()) {

        int idIndex = cur.getColumnIndex("_id");

        Log.d(Tags.LOG, "removeFromDatabase(): Deleting file entry in DB (file).");
        LocalNZBMetadata.myDatabase.delete("file", "_id='" + cur.getString(idIndex) + "'", null);

        Log.d(Tags.LOG, "removeFromDatabase(): Deleting file metadata in DB (meta).");
        LocalNZBMetadata.myDatabase.delete("meta", "file_id='" + cur.getString(idIndex) + "'", null);
    }
    LocalNZBMetadata.close();
}

From source file:li.barter.fragments.ChatsFragment.java

@Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {

    if (parent.getId() == R.id.list_chats) {

        final Cursor cursor = (Cursor) mChatsAdapter.getItem(position);

        loadChat(cursor.getString(cursor.getColumnIndex(DatabaseColumns.USER_ID)),
                cursor.getString(cursor.getColumnIndex(DatabaseColumns.CHAT_ID)), true, null);
    }/* w  w  w .  java  2 s .  com*/
}

From source file:cn.edu.wyu.documentviewer.RecentsProvider.java

/**
 * Purge all internal data whose authority matches the given
 * {@link Predicate}./*from w  w  w.j av a2s .  c  om*/
 */
private void purgeByAuthority(Predicate<String> predicate) {
    final SQLiteDatabase db = mHelper.getWritableDatabase();
    final DocumentStack stack = new DocumentStack();

    Cursor cursor = db.query(TABLE_RECENT, null, null, null, null, null, null);
    try {
        while (cursor.moveToNext()) {
            try {
                final byte[] rawStack = cursor.getBlob(cursor.getColumnIndex(RecentColumns.STACK));
                DurableUtils.readFromArray(rawStack, stack);

                if (stack.root != null && predicate.apply(stack.root.authority)) {
                    final String key = getCursorString(cursor, RecentColumns.KEY);
                    db.delete(TABLE_RECENT, RecentColumns.KEY + "=?", new String[] { key });
                }
            } catch (IOException ignored) {
            }
        }
    } finally {
        //IoUtils.closeQuietly(cursor);
        IOUtils.closeQuietly(cursor);
    }

    cursor = db.query(TABLE_STATE, new String[] { StateColumns.AUTHORITY }, null, null, StateColumns.AUTHORITY,
            null, null);
    try {
        while (cursor.moveToNext()) {
            final String authority = getCursorString(cursor, StateColumns.AUTHORITY);
            if (predicate.apply(authority)) {
                db.delete(TABLE_STATE, StateColumns.AUTHORITY + "=?", new String[] { authority });
                Log.d(TAG, "Purged state for " + authority);
            }
        }
    } finally {
        //IoUtils.closeQuietly(cursor);
        IOUtils.closeQuietly(cursor);
    }

    cursor = db.query(TABLE_RESUME, null, null, null, null, null, null);
    try {
        while (cursor.moveToNext()) {
            try {
                final byte[] rawStack = cursor.getBlob(cursor.getColumnIndex(ResumeColumns.STACK));
                DurableUtils.readFromArray(rawStack, stack);

                if (stack.root != null && predicate.apply(stack.root.authority)) {
                    final String packageName = getCursorString(cursor, ResumeColumns.PACKAGE_NAME);
                    db.delete(TABLE_RESUME, ResumeColumns.PACKAGE_NAME + "=?", new String[] { packageName });
                }
            } catch (IOException ignored) {
            }
        }
    } finally {
        //IoUtils.closeQuietly(cursor);
        IOUtils.closeQuietly(cursor);
    }
}

From source file:com.example.gaurav.sunshine.app.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/*w  ww . j a  v  a2 s. co m*/
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
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 rowId;
    final ContentResolver resolver = mContext.getContentResolver();
    Uri uri = Uri.parse(WeatherContract.BASE_CONTENT_URI + "/" + WeatherContract.PATH_LOCATION);
    String selectionArgs[] = { WeatherContract.LocationEntry.COLUMN_CITY_NAME };
    String selection = WeatherContract.LocationEntry.COLUMN_CITY_NAME + " =? ";

    //First, query database to check if this location already exists.
    Cursor cursor = resolver.query(uri, null, selection, new String[] { cityName }, null);

    if (cursor.moveToNext())
        return Long.parseLong(cursor.getString(cursor.getColumnIndex(WeatherContract.LocationEntry._ID)));
    else {
        ContentValues values = new ContentValues();
        values.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        values.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        values.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        values.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
        //resolver.insert(uri, values);
        return Long.parseLong(resolver.insert(uri, values).getLastPathSegment());
    }
    // return -1;
}