List of usage examples for android.database Cursor getColumnIndex
int getColumnIndex(String columnName);
From source file:com.swisscom.android.sunshine.data.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 . j av a 2 s. co m*/ * @param lon the longitude of the city * @return the row ID of the added location. */ private long addLocation(String locationSetting, String cityName, double lat, double lon) { Log.v(LOG_TAG, "inserting " + cityName + ", with coord: " + lat + ", " + lon); // First, check if the location with this city name exists in the db Cursor cursor = mContext.getContentResolver().query(LocationEntry.CONTENT_URI, new String[] { LocationEntry._ID }, LocationEntry.COLUMN_LOCATION_SETTINGS + " = ?", new String[] { locationSetting }, null); if (cursor.moveToFirst()) { Log.v(LOG_TAG, "Found it in the database!"); int locationIdIndex = cursor.getColumnIndex(LocationEntry._ID); return 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_SETTINGS, locationSetting); locationValues.put(LocationEntry.COLUMN_CITY_NAME, cityName); locationValues.put(LocationEntry.COLUMN_LATITUDE, lat); locationValues.put(LocationEntry.COLUMN_LONGITUDE, lon); Uri locationInsertUri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, locationValues); return ContentUris.parseId(locationInsertUri); } }
From source file:com.prashantpal.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//from w w w . ja v a 2 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) { // Students: First, check if the location with this city name exists in the db // If it exists, return the current ID long locationId; ContentResolver resolver = mContext.getContentResolver(); Cursor cursor = resolver.query(WeatherContract.LocationEntry.CONTENT_URI, new String[] { WeatherContract.LocationEntry._ID }, WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + "= ?", new String[] { locationSetting }, null); if (cursor.moveToFirst()) { int locationIdIndex = cursor.getColumnIndex(WeatherContract.LocationEntry._ID); locationId = cursor.getLong(locationIdIndex); } else { ContentValues contentValues = new ContentValues(); contentValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName); contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat); contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon); contentValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); Uri uri = resolver.insert(WeatherContract.LocationEntry.CONTENT_URI, contentValues); locationId = ContentUris.parseId(uri); } cursor.close(); // Otherwise, insert it using the content resolver and the base URI return locationId; }
From source file:com.digipom.manteresting.android.fragment.NailFragment.java
private int calculateInitialOffsetForNextFetch() { int offsetToReturn = -1; if (listView != null) { try {//w w w.j a va 2s . co m final int listViewCount = listView.getCount(); if (listViewCount > 2) { // Get the first and last nail IDs, and subtract the 2 // to get the initial offset. final Cursor firstCursor = (Cursor) listView.getItemAtPosition(1); if (firstCursor != null && !firstCursor.isClosed()) { final int columnIndex = firstCursor.getColumnIndex(Nails.NAIL_ID); final int firstNailId = Integer.parseInt(firstCursor.getString(columnIndex)); final Cursor lastCursor = (Cursor) listView.getItemAtPosition(listViewCount - 2); if (lastCursor != null && !lastCursor.isClosed()) { final int lastNailId = Integer.parseInt(firstCursor.getString(columnIndex)); offsetForNextPage = firstNailId - lastNailId; return firstNailId - lastNailId; } } } } catch (Exception e) { if (LoggerConfig.canLog(Log.ERROR)) { Log.e(TAG, "getOffsetForNextFetch()", e); } } } return offsetToReturn; }
From source file:com.arminkale.android.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/*from www .j av a 2s . com*/ * @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 locationId; // First, check if the location with this city name exists in the db Cursor locationCursor = mContext.getContentResolver().query(LocationEntry.CONTENT_URI, new String[] { LocationEntry._ID }, LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting }, null); if (locationCursor.moveToFirst()) { int locationIdIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID); locationId = locationCursor.getLong(locationIdIndex); } else { // Now that the content provider is set up, inserting rows of data is pretty simple. // First create a ContentValues object to hold the data you want to insert. ContentValues locationValues = new ContentValues(); // Then add the data, along with the corresponding name of the data type, // so the content provider knows what kind of value is being inserted. locationValues.put(LocationEntry.COLUMN_CITY_NAME, cityName); locationValues.put(LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); locationValues.put(LocationEntry.COLUMN_COORD_LAT, lat); locationValues.put(LocationEntry.COLUMN_COORD_LONG, lon); // Finally, insert location data into the database. Uri insertedUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI, locationValues); // The resulting URI contains the ID for the row. Extract the locationId from the Uri. locationId = ContentUris.parseId(insertedUri); } // Close the cursor and return the new ID. locationCursor.close(); return locationId; }
From source file:com.radioactiveyak.location_best_practices.services.PlaceCheckinService.java
/** * {@inheritDoc}// w w w . j av a2s . com * Perform a checkin the specified venue. If the checkin fails, add it to the queue and * set an alarm to retry. * * Query the checkin queue to see if there are pending checkins to be retried. */ @Override protected void onHandleIntent(Intent intent) { // Retrieve the details for the checkin to perform. String reference = intent.getStringExtra(PlacesConstants.EXTRA_KEY_REFERENCE); String id = intent.getStringExtra(PlacesConstants.EXTRA_KEY_ID); long timeStamp = intent.getLongExtra(PlacesConstants.EXTRA_KEY_TIME_STAMP, 0); // Check if we're running in the foreground, if not, check if // we have permission to do background updates. boolean backgroundAllowed = cm.getBackgroundDataSetting(); boolean inBackground = sharedPreferences.getBoolean(PlacesConstants.EXTRA_KEY_IN_BACKGROUND, true); if (reference != null && !backgroundAllowed && inBackground) { addToQueue(timeStamp, reference, id); return; } // Check to see if we are connected to a data network. NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); // If we're not connected then disable the retry Alarm, enable the Connectivity Changed Receiver // and add the new checkin directly to the queue. The Connectivity Changed Receiver will listen // for when we connect to a network and start this service to retry the checkins. if (!isConnected) { // No connection so no point triggering an alarm to retry until we're connected. alarmManager.cancel(retryQueuedCheckinsPendingIntent); // Enable the Connectivity Changed Receiver to listen for connection to a network // so we can commit the pending checkins. PackageManager pm = getPackageManager(); ComponentName connectivityReceiver = new ComponentName(this, ConnectivityChangedReceiver.class); pm.setComponentEnabledSetting(connectivityReceiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); // Add this checkin to the queue. addToQueue(timeStamp, reference, id); } else { // Execute the checkin. If it fails, add it to the retry queue. if (reference != null) { if (!checkin(timeStamp, reference, id)) addToQueue(timeStamp, reference, id); } // Retry the queued checkins. ArrayList<String> successfulCheckins = new ArrayList<String>(); Cursor queuedCheckins = contentResolver.query(QueuedCheckinsContentProvider.CONTENT_URI, null, null, null, null); try { // Retry each checkin. while (queuedCheckins.moveToNext()) { long queuedTimeStamp = queuedCheckins .getLong(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_TIME_STAMP)); String queuedReference = queuedCheckins .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_REFERENCE)); String queuedId = queuedCheckins .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_ID)); if (queuedReference == null || checkin(queuedTimeStamp, queuedReference, queuedId)) successfulCheckins.add(queuedReference); } // Delete the queued checkins that were successful. if (successfulCheckins.size() > 0) { StringBuilder sb = new StringBuilder("(" + QueuedCheckinsContentProvider.KEY_REFERENCE + "='" + successfulCheckins.get(0) + "'"); for (int i = 1; i < successfulCheckins.size(); i++) sb.append(" OR " + QueuedCheckinsContentProvider.KEY_REFERENCE + " = '" + successfulCheckins.get(i) + "'"); sb.append(")"); int deleteCount = contentResolver.delete(QueuedCheckinsContentProvider.CONTENT_URI, sb.toString(), null); Log.d(TAG, "Deleted: " + deleteCount); } // If there are still queued checkins then set a non-waking alarm to retry them. queuedCheckins.requery(); if (queuedCheckins.getCount() > 0) { long triggerAtTime = System.currentTimeMillis() + PlacesConstants.CHECKIN_RETRY_INTERVAL; alarmManager.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime, retryQueuedCheckinsPendingIntent); } else alarmManager.cancel(retryQueuedCheckinsPendingIntent); } finally { queuedCheckins.close(); } } }
From source file:com.remobile.contacts.ContactManager.java
/** * Called when user picks contact.//from w w w . j av a 2 s. c o m * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). * @throws JSONException */ public void onActivityResult(int requestCode, int resultCode, final Intent intent) { if (requestCode == cordova.CONTACT_PICKER_RESULT) { if (resultCode == Activity.RESULT_OK) { String contactId = intent.getData().getLastPathSegment(); // to populate contact data we require Raw Contact ID // so we do look up for contact raw id first Cursor c = this.cordova.getActivity().getContentResolver().query(RawContacts.CONTENT_URI, new String[] { RawContacts._ID }, RawContacts.CONTACT_ID + " = " + contactId, null, null); if (!c.moveToFirst()) { this.callbackContext.error("Error occured while retrieving contact raw id"); return; } String id = c.getString(c.getColumnIndex(RawContacts._ID)); c.close(); try { JSONObject contact = contactAccessor.getContactById(id); this.callbackContext.success(contact); return; } catch (JSONException e) { Log.e(LOG_TAG, "JSON fail.", e); } } else if (resultCode == Activity.RESULT_CANCELED) { this.callbackContext .sendPluginResult(new PluginResult(PluginResult.Status.NO_RESULT, UNKNOWN_ERROR)); return; } this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, UNKNOWN_ERROR)); } }
From source file:com.android.transmart.services.PlaceCheckinService.java
/** * {@inheritDoc}/*from ww w .j av a 2 s . c o m*/ * Perform a checkin the specified venue. If the checkin fails, add it to the queue and * set an alarm to retry. * * Query the checkin queue to see if there are pending checkins to be retried. */ @Override protected void onHandleIntent(Intent intent) { // Retrieve the details for the checkin to perform. String reference = intent.getStringExtra(LocationConstants.EXTRA_KEY_REFERENCE); String id = intent.getStringExtra(LocationConstants.EXTRA_KEY_ID); long timeStamp = intent.getLongExtra(LocationConstants.EXTRA_KEY_TIME_STAMP, 0); // Check if we're running in the foreground, if not, check if // we have permission to do background updates. boolean backgroundAllowed = cm.getBackgroundDataSetting(); boolean inBackground = sharedPreferences.getBoolean(LocationConstants.EXTRA_KEY_IN_BACKGROUND, true); if (reference != null && !backgroundAllowed && inBackground) { addToQueue(timeStamp, reference, id); return; } // Check to see if we are connected to a data network. NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); // If we're not connected then disable the retry Alarm, enable the Connectivity Changed Receiver // and add the new checkin directly to the queue. The Connectivity Changed Receiver will listen // for when we connect to a network and start this service to retry the checkins. if (!isConnected) { // No connection so no point triggering an alarm to retry until we're connected. alarmManager.cancel(retryQueuedCheckinsPendingIntent); // Enable the Connectivity Changed Receiver to listen for connection to a network // so we can commit the pending checkins. PackageManager pm = getPackageManager(); ComponentName connectivityReceiver = new ComponentName(this, ConnectivityChangedReceiver.class); pm.setComponentEnabledSetting(connectivityReceiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); // Add this checkin to the queue. addToQueue(timeStamp, reference, id); } else { // Execute the checkin. If it fails, add it to the retry queue. if (reference != null) { if (!checkin(timeStamp, reference, id)) addToQueue(timeStamp, reference, id); } // Retry the queued checkins. ArrayList<String> successfulCheckins = new ArrayList<String>(); Cursor queuedCheckins = contentResolver.query(QueuedCheckinsContentProvider.CONTENT_URI, null, null, null, null); try { // Retry each checkin. while (queuedCheckins.moveToNext()) { long queuedTimeStamp = queuedCheckins .getLong(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_TIME_STAMP)); String queuedReference = queuedCheckins .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_REFERENCE)); String queuedId = queuedCheckins .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_ID)); if (queuedReference == null || checkin(queuedTimeStamp, queuedReference, queuedId)) successfulCheckins.add(queuedReference); } // Delete the queued checkins that were successful. if (successfulCheckins.size() > 0) { StringBuilder sb = new StringBuilder("(" + QueuedCheckinsContentProvider.KEY_REFERENCE + "='" + successfulCheckins.get(0) + "'"); for (int i = 1; i < successfulCheckins.size(); i++) sb.append(" OR " + QueuedCheckinsContentProvider.KEY_REFERENCE + " = '" + successfulCheckins.get(i) + "'"); sb.append(")"); int deleteCount = contentResolver.delete(QueuedCheckinsContentProvider.CONTENT_URI, sb.toString(), null); Log.d(TAG, "Deleted: " + deleteCount); } // If there are still queued checkins then set a non-waking alarm to retry them. queuedCheckins.requery(); if (queuedCheckins.getCount() > 0) { long triggerAtTime = System.currentTimeMillis() + LocationConstants.CHECKIN_RETRY_INTERVAL; alarmManager.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime, retryQueuedCheckinsPendingIntent); } else alarmManager.cancel(retryQueuedCheckinsPendingIntent); } finally { queuedCheckins.close(); } } }
From source file:com.trellmor.berrymotes.sync.EmoteDownloader.java
public void deleteSubreddit(String subreddit, ContentResolver contentResolver) throws IOException { Log.info(" Removing emotes of " + subreddit); Cursor c = contentResolver.query(EmotesContract.Emote.CONTENT_URI_DISTINCT, new String[] { EmotesContract.Emote.COLUMN_IMAGE }, EmotesContract.Emote.COLUMN_SUBREDDIT + "=?", new String[] { subreddit }, null); if (c.moveToFirst()) { final int POS_IMAGE = c.getColumnIndex(EmotesContract.Emote.COLUMN_IMAGE); do {//www . j a v a 2s. c om checkStorageAvailable(); File file = new File(c.getString(POS_IMAGE)); if (file.exists()) { file.delete(); } } while (c.moveToNext()); } c.close(); int deletes = mContentResolver.delete(EmotesContract.Emote.CONTENT_URI, EmotesContract.Emote.COLUMN_SUBREDDIT + "=?", new String[] { subreddit }); Log.info("Removed emotes: " + Integer.toString(deletes)); synchronized (mSyncResult) { mSyncResult.stats.numDeletes += deletes; } }
From source file:com.moez.QKSMS.mmssms.Transaction.java
public static MessageInfo getBytes(Context context, boolean saveMessage, String[] recipients, MMSPart[] parts, String subject) throws MmsException { final SendReq sendRequest = new SendReq(); // create send request addresses for (int i = 0; i < recipients.length; i++) { final EncodedStringValue[] phoneNumbers = EncodedStringValue.extract(recipients[i]); if (phoneNumbers != null && phoneNumbers.length > 0) { sendRequest.addTo(phoneNumbers[0]); }/* w w w . j a v a2s . c om*/ } if (subject != null) { sendRequest.setSubject(new EncodedStringValue(subject)); } sendRequest.setDate(Calendar.getInstance().getTimeInMillis() / 1000L); try { sendRequest.setFrom(new EncodedStringValue(Utils.getMyPhoneNumber(context))); } catch (Exception e) { // my number is nothing } final PduBody pduBody = new PduBody(); // assign parts to the pdu body which contains sending data if (parts != null) { for (int i = 0; i < parts.length; i++) { MMSPart part = parts[i]; if (part != null) { try { PduPart partPdu = new PduPart(); partPdu.setName(part.Name.getBytes()); partPdu.setContentType(part.MimeType.getBytes()); if (part.MimeType.startsWith("text")) { partPdu.setCharset(CharacterSets.UTF_8); } partPdu.setData(part.Data); pduBody.addPart(partPdu); } catch (Exception e) { } } } } ByteArrayOutputStream out = new ByteArrayOutputStream(); SmilXmlSerializer.serialize(SmilHelper.createSmilDocument(pduBody), out); PduPart smilPart = new PduPart(); smilPart.setContentId("smil".getBytes()); smilPart.setContentLocation("smil.xml".getBytes()); smilPart.setContentType(ContentType.APP_SMIL.getBytes()); smilPart.setData(out.toByteArray()); pduBody.addPart(0, smilPart); sendRequest.setBody(pduBody); // create byte array which will actually be sent final PduComposer composer = new PduComposer(context, sendRequest); final byte[] bytesToSend; try { bytesToSend = composer.make(); } catch (OutOfMemoryError e) { throw new MmsException("Out of memory!"); } MessageInfo info = new MessageInfo(); info.bytes = bytesToSend; if (saveMessage) { try { PduPersister persister = PduPersister.getPduPersister(context); info.location = persister.persist(sendRequest, Uri.parse("content://mms/outbox"), true, settings.getGroup(), null); } catch (Exception e) { if (LOCAL_LOGV) Log.v(TAG, "error saving mms message"); Log.e(TAG, "exception thrown", e); // use the old way if something goes wrong with the persister insert(context, recipients, parts, subject); } } try { Cursor query = context.getContentResolver().query(info.location, new String[] { "thread_id" }, null, null, null); if (query != null && query.moveToFirst()) { info.token = query.getLong(query.getColumnIndex("thread_id")); } else { // just default sending token for what I had before info.token = 4444L; } } catch (Exception e) { Log.e(TAG, "exception thrown", e); info.token = 4444L; } return info; }
From source file:com.rjfun.cordova.sms.SMSPlugin.java
private PluginResult deleteSMS(JSONObject filter, CallbackContext callbackContext) { Log.d(LOGTAG, ACTION_DELETE_SMS);//from ww w. j av a 2 s.c om String uri_filter = filter.has(BOX) ? filter.optString(BOX) : "inbox"; int fread = filter.has(READ) ? filter.optInt(READ) : -1; int fid = filter.has("_id") ? filter.optInt("_id") : -1; String faddress = filter.optString(ADDRESS); String fcontent = filter.optString(BODY); Activity ctx = this.cordova.getActivity(); int n = 0; try { Uri uri = Uri.parse((SMS_URI_ALL + uri_filter)); Cursor cur = ctx.getContentResolver().query(uri, (String[]) null, "", (String[]) null, null); while (cur.moveToNext()) { int id = cur.getInt(cur.getColumnIndex("_id")); boolean matchId = fid > -1 && fid == id; int read = cur.getInt(cur.getColumnIndex(READ)); boolean matchRead = fread > -1 && fread == read; String address = cur.getString(cur.getColumnIndex(ADDRESS)).trim(); boolean matchAddr = faddress.length() > 0 && address.equals(faddress); String body = cur.getString(cur.getColumnIndex(BODY)).trim(); boolean matchContent = fcontent.length() > 0 && body.equals(fcontent); if (!matchId && !matchRead && !matchAddr && !matchContent) continue; ctx.getContentResolver().delete(uri, "_id=" + id, (String[]) null); ++n; } callbackContext.success(n); } catch (Exception e) { callbackContext.error(e.toString()); } return null; }