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:net.eledge.android.toolkit.db.abstracts.Dao.java

private List<E> mapToEntities(Cursor cursor) {
    List<E> list = new ArrayList<>();
    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {// w ww  . ja  v a2  s .c o  m
                try {
                    E instance = clazz.newInstance();
                    for (Field field : clazz.getFields()) {
                        if (field.isAnnotationPresent(Column.class)) {
                            int columnIndex = cursor.getColumnIndex(SQLBuilder.getFieldName(field));
                            if (!cursor.isNull(columnIndex)) {
                                FieldType fieldType = FieldType.getType(field.getType());
                                fieldType.convertToField(instance, field, cursor, columnIndex);
                            }
                        }
                    }
                    list.add(instance);
                } catch (IllegalArgumentException | IllegalAccessException | InstantiationException e) {
                    Log.e(this.getClass().getName(), e.getMessage(), e);
                }
            } while (cursor.moveToNext());
        }
        cursor.close();
    }
    return list;
}

From source file:idea.ruan.oksun.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/*  ww w. ja va2 s.c om*/
 * @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) {

    ContentResolver contentResolver = mContext.getContentResolver();

    Uri locationTableUri = WeatherContract.LocationEntry.CONTENT_URI;

    long locationId;
    Cursor c = contentResolver.query(locationTableUri, new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_CITY_NAME + " = ?", new String[] { cityName }, null);
    if (c.moveToFirst()) {

        int i = c.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = c.getLong(i);

    } else {

        ContentValues cv = new ContentValues();

        cv.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        cv.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        cv.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        cv.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        locationId = ContentUris.parseId(contentResolver.insert(locationTableUri, cv));

    }

    c.close();

    return locationId;
}

From source file:io.selendroid.server.ServerInstrumentation.java

public List<CallLogEntry> readCallLog() throws PermissionDeniedException {
    if (getTargetContext().checkCallingOrSelfPermission(
            Manifest.permission.READ_CALL_LOG) == PackageManager.PERMISSION_GRANTED) {
        List<CallLogEntry> logs = new ArrayList<CallLogEntry>();
        Cursor managedCursor = getTargetContext().getContentResolver().query(CallLog.Calls.CONTENT_URI, null,
                null, null, null);//from   w  w w. ja va  2  s.c om
        int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
        int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
        int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
        int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
        while (managedCursor.moveToNext()) {
            String phNumber = managedCursor.getString(number);
            String callType = managedCursor.getString(type);
            String callDate = managedCursor.getString(date);
            Date callDayTime = new Date(Long.valueOf(callDate));
            String callDuration = managedCursor.getString(duration);
            logs.add(new CallLogEntry(phNumber, Integer.parseInt(callDuration), callDayTime,
                    Integer.parseInt(callType)));
        }
        managedCursor.close();
        return logs;
    } else {
        throw new PermissionDeniedException(
                "Application under test does not have required READ_CALL_LOG permission for this feature.");
    }

}

From source file:com.example.cmput301.model.DatabaseManager.java

/**
 * Get the local task list.//  w  w  w.  ja  v  a2s . co  m
 *
 * @return A list of tasks in the local table of the database
 * @throws JSONException 
 */
public ArrayList<Task> getLocalTaskList() {
    try {
        ArrayList<Task> out = new ArrayList<Task>();

        Cursor c = db.rawQuery("SELECT * FROM " + StringRes.LOCAL_TASK_TABLE_NAME, new String[] {});
        if (c.moveToFirst()) {
            while (c.isAfterLast() == false) {
                JSONObject obj = toJsonTask(c.getString(c.getColumnIndex(StringRes.COL_CONTENT)));
                out.add(toTask(obj));
                c.moveToNext();
            }
            return out;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.udacity.sunshine.FetchWeatherTask.java

private long addLocation(String locationSetting, String cityName, double lat, double lon) {

    Log.v(LOG_TAG, "inserting " + cityName + ", with coord: " + lat + ", " + lon);

    String[] projection = { LocationEntry._ID }; // whichever column doesn't matter, but don't need to return all
    String[] selectionArgs = { locationSetting };
    String selection = LocationEntry.COLUMN_LOCATION_SETTING + " = ? ";
    // Check to see if location setting exists in db
    Cursor cursor = mContext.getContentResolver().query(LocationEntry.CONTENT_URI, projection, selection,
            selectionArgs, null);/*from  w  w w. j  a v  a  2  s . c om*/

    long locationRowId;

    if (cursor.moveToFirst()) {
        Log.v(LOG_TAG, "Found it in the database!");
        int locationIdIndex = cursor.getColumnIndex(LocationEntry._ID);
        locationRowId = cursor.getLong(locationIdIndex);
    } else {
        Log.v(LOG_TAG, "Didn't find it in the database, inserting now!");

        ContentValues locationValues = new ContentValues();
        locationValues.put(LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(LocationEntry.COLUMN_COORD_LONG, lon);

        Uri locationUri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, locationValues);
        locationRowId = ContentUris.parseId(locationUri);
    }
    cursor.close();

    return locationRowId;
}

From source file:com.klinker.android.twitter.utils.NotificationUtils.java

public static void favUsersNotification(int account, Context context) {

    ArrayList<String[]> tweets = new ArrayList<String[]>();

    HomeDataSource data = HomeDataSource.getInstance(context);
    Cursor cursor = data.getUnreadCursor(account);

    FavoriteUsersDataSource favs = FavoriteUsersDataSource.getInstance(context);

    if (cursor.moveToFirst()) {
        do {//from w w w  . j  a v a 2 s  . c  o  m
            String screenname = cursor.getString(cursor.getColumnIndex(HomeSQLiteHelper.COLUMN_SCREEN_NAME));

            if (favs.isFavUser(account, screenname)) {
                String name = cursor.getString(cursor.getColumnIndex(HomeSQLiteHelper.COLUMN_NAME));
                String text = cursor.getString(cursor.getColumnIndex(HomeSQLiteHelper.COLUMN_TEXT));
                String time = cursor.getLong(cursor.getColumnIndex(HomeSQLiteHelper.COLUMN_TIME)) + "";
                String picUrl = cursor.getString(cursor.getColumnIndex(HomeSQLiteHelper.COLUMN_PIC_URL));
                String otherUrl = cursor.getString(cursor.getColumnIndex(HomeSQLiteHelper.COLUMN_URL));
                String users = cursor.getString(cursor.getColumnIndex(HomeSQLiteHelper.COLUMN_USERS));
                String hashtags = cursor.getString(cursor.getColumnIndex(HomeSQLiteHelper.COLUMN_HASHTAGS));
                String id = cursor.getLong(cursor.getColumnIndex(HomeSQLiteHelper.COLUMN_TWEET_ID)) + "";
                String profilePic = cursor.getString(cursor.getColumnIndex(HomeSQLiteHelper.COLUMN_PRO_PIC));
                String otherUrls = cursor.getString(cursor.getColumnIndex(HomeSQLiteHelper.COLUMN_URL));
                String userss = cursor.getString(cursor.getColumnIndex(HomeSQLiteHelper.COLUMN_USERS));
                String hashtagss = cursor.getString(cursor.getColumnIndex(HomeSQLiteHelper.COLUMN_HASHTAGS));
                String retweeter;
                try {
                    retweeter = cursor.getString(cursor.getColumnIndex(HomeSQLiteHelper.COLUMN_RETWEETER));
                } catch (Exception e) {
                    retweeter = "";
                }
                String link = "";

                boolean displayPic = !picUrl.equals("") && !picUrl.contains("youtube");
                if (displayPic) {
                    link = picUrl;
                } else {
                    link = otherUrls.split("  ")[0];
                }

                tweets.add(new String[] { name, text, screenname, time, retweeter, link,
                        displayPic ? "true" : "false", id, profilePic, userss, hashtagss, otherUrls });
            }
        } while (cursor.moveToNext());
    }

    cursor.close();

    if (tweets.size() > 0) {
        if (tweets.size() == 1) {
            makeFavsNotificationToActivity(tweets, context);
        } else {
            AppSettings settings = AppSettings.getInstance(context);
            makeFavsNotification(tweets, context, settings.liveStreaming || settings.pushNotifications);
        }
    }
}

From source file:com.money.manager.ex.datalayer.StockRepository.java

/**
 * Retrieves all record ids which refer the given symbol.
 * @return array of ids of records which contain the symbol.
 *//*w  w w . j  a  v  a2s .c om*/
public int[] findIdsBySymbol(String symbol) {
    int[] result;

    Cursor cursor = getContext().getContentResolver().query(this.getUri(), new String[] { StockFields.STOCKID },
            StockFields.SYMBOL + "=?", new String[] { symbol }, null);
    if (cursor == null)
        return null;

    int records = cursor.getCount();
    result = new int[records];

    for (int i = 0; i < records; i++) {
        cursor.moveToNext();
        result[i] = cursor.getInt(cursor.getColumnIndex(StockFields.STOCKID));
    }
    cursor.close();

    return result;
}

From source file:com.example.cmput301.model.DatabaseManager.java

/**
 * Get the remote task list.//from w w w . j  a  v  a2s. c om
 *
 * @return A list of tasks in the remote table of the database
 * @throws JSONException 
 */
//fixed
public ArrayList<Task> getRemoteTaskList() {
    try {
        Log.d("refresh", "STARTING REMOTE TASK LIST");
        ArrayList<Task> out = new ArrayList<Task>();
        Cursor c = db.rawQuery("SELECT * FROM " + StringRes.REMOTE_TASK_TABLE_NAME, new String[] {});
        if (c.moveToFirst()) {
            while (c.isAfterLast() == false) {
                JSONObject obj = toJsonTask(c.getString(c.getColumnIndex(StringRes.COL_CONTENT)));
                out.add(toTask(obj));
                c.moveToNext();
            }
        }
        Log.d("refresh", "sizeof remotetasklist = " + out.size());
        return out;

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

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

public void listTableContents() {
    Cursor cursor = null;
    try {/* ww  w  . ja  va 2s  .com*/
        cursor = sDatabase.query(APP_TABLE_NAME, null, null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            while (true) {
                Log.v(DBTAG,
                        "Row: Package=" + cursor.getString(cursor.getColumnIndex(PACKAGE_COL)) + " | URL="
                                + cursor.getString(cursor.getColumnIndex(URL_COL)) + " | DATA="
                                + cursor.getString(cursor.getColumnIndex(DATA_COL)));
                if (cursor.isLast())
                    break;
                cursor.moveToNext();
            }
        }

    } catch (IllegalStateException e) {
        Log.e(DBTAG, "getAppDataFromDB failed", e);
    } finally {
        if (cursor != null)
            cursor.close();
    }
}

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

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

    if (resultCode == Activity.RESULT_OK) {
        Cursor cursor = activity.managedQuery(intent.getData(), null, null, null, null);
        cursor.moveToNext();//from   w  w w.ja va2s . co m
        String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
        String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));

        getAllContacts();
        String js = String.format(
                " var e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.choose',true,true);e.success=true;e.contactid='%s';document.dispatchEvent(e);",
                contactId);
        injectJS("javascript:" + js);
        busy = false;
    } else {
        String js = "var e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.choose',true,true);e.success=false;e.message='User canceled';document.dispatchEvent(e);";
        injectJS("javascript:" + js);
        busy = false;
    }

}