List of usage examples for android.database Cursor getLong
long getLong(int columnIndex);
From source file:org.devtcg.five.provider.FiveSyncAdapter.java
private void getImageData(SyncContext context, AbstractSyncProvider serverDiffs, String feedType, long modifiedSince) { if (context.hasError() == true || context.hasCanceled() == true) return;/*ww w. ja v a 2 s . co m*/ Uri localFeedUri = getLocalFeedUri(feedType); String tablePrefix = (feedType.equals(FEED_ALBUMS) ? "a." : ""); Cursor newRecords = serverDiffs.query(localFeedUri, new String[] { AbstractTableMerger.SyncableColumns._ID, AbstractTableMerger.SyncableColumns._SYNC_ID }, tablePrefix + AbstractTableMerger.SyncableColumns._SYNC_TIME + " > " + modifiedSince, null, null); Resources res = getContext().getResources(); int thumbWidth = res.getDimensionPixelSize(R.dimen.image_thumb_width); int thumbHeight = res.getDimensionPixelSize(R.dimen.image_thumb_height); int fullWidth = res.getDimensionPixelSize(R.dimen.large_artwork_width); int fullHeight = res.getDimensionPixelSize(R.dimen.large_artwork_height); try { while (newRecords.moveToNext() && !context.hasError() && !context.hasCanceled()) { long id = newRecords.getLong(0); long syncId = newRecords.getLong(1); try { Uri localFeedItemUri = ContentUris.withAppendedId(localFeedUri, id); if (feedType.equals(FEED_ARTISTS)) { downloadFileAndUpdateProvider(context, serverDiffs, mSource.getImageUrl(feedType, syncId, thumbWidth, thumbHeight), Five.makeArtistPhotoUri(id), localFeedItemUri, Five.Music.Artists.PHOTO); } else if (feedType.equals(FEED_ALBUMS)) { downloadFileAndUpdateProvider(context, serverDiffs, mSource.getImageUrl(feedType, syncId, thumbWidth, thumbHeight), Five.makeAlbumArtworkUri(id), localFeedItemUri, Five.Music.Albums.ARTWORK); downloadFileAndUpdateProvider(context, serverDiffs, mSource.getImageUrl(feedType, syncId, fullWidth, fullHeight), Five.makeAlbumArtworkBigUri(id), localFeedItemUri, Five.Music.Albums.ARTWORK_BIG); } } catch (IOException e) { markErrorUnlessCanceled(context, e); } } } finally { newRecords.close(); } }
From source file:com.ubuntuone.android.files.service.MetaService.java
/** * Given parents resource path and {@link ArrayList} of {@link NodeInfo}s of * its children, syncs cached info of these children. Updating children in * one method enables us to make use of database transaction.<br /> * <ul>// w ww . j a va 2 s .c o m * <li>- inserts if child is new</li> * <li>- updates if child has changed [thus marks is_cached = false]</li> * <li>- deletes if child is missing [dead node]</li> * </ul> * * @param parentResourcePath * the resource path of childrens parent * @param children * {@link NodeInfo}s of the parents children * @throws OperationApplicationException * @throws RemoteException */ public void getDirectoryNode(final String resourcePath, final ResultReceiver receiver) { Log.i(TAG, "getDirectoryNode()"); final String[] projection = new String[] { Nodes._ID, Nodes.NODE_RESOURCE_PATH, Nodes.NODE_GENERATION, Nodes.NODE_DATA }; final String selection = Nodes.NODE_RESOURCE_PATH + "=?"; final Set<Integer> childrenIds = MetaUtilities.getChildrenIds(resourcePath); final ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(); final Bundle data = new Bundle(); data.putString(EXTRA_RESOURCE_PATH, resourcePath); api.listDirectory(resourcePath, new U1NodeListener() { @Override public void onStart() { if (receiver != null) receiver.send(Status.RUNNING, data); } @Override public void onSuccess(U1Node node) { if (node.getKind() == U1NodeKind.FILE && ((U1File) node).getSize() == null) { // Ignore files with null size. return; } final String[] selectionArgs = new String[] { node.getResourcePath() }; final Cursor c = contentResolver.query(Nodes.CONTENT_URI, projection, selection, selectionArgs, null); try { ContentValues values = Nodes.valuesFromRepr(node); if (c.moveToFirst()) { final int id = c.getInt(c.getColumnIndex(Nodes._ID)); // Node is live. childrenIds.remove(id); // Update node. final long generation = c.getLong(c.getColumnIndex(Nodes.NODE_GENERATION)); final long newGeneration = node.getGeneration(); if (generation < newGeneration) { Log.v(TAG, "updating child node, new generation"); values.put(Nodes.NODE_IS_CACHED, false); values.put(Nodes.NODE_DATA, ""); String data = c.getString(c.getColumnIndex(Nodes.NODE_DATA)); FileUtilities.removeSilently(data); Uri uri = MetaUtilities.buildNodeUri(id); ContentProviderOperation op = ContentProviderOperation.newUpdate(uri).withValues(values) .build(); operations.add(op); if (operations.size() > 10) { try { contentResolver.applyBatch(MetaContract.CONTENT_AUTHORITY, operations); operations.clear(); } catch (RemoteException e) { Log.e(TAG, "Remote exception", e); } catch (OperationApplicationException e) { MetaUtilities.setIsCached(resourcePath, false); return; } Thread.yield(); } } else { Log.v(TAG, "child up to date"); } } else { // Insert node. Log.v(TAG, "inserting child"); ContentProviderOperation op = ContentProviderOperation.newInsert(Nodes.CONTENT_URI) .withValues(values).build(); operations.add(op); if (operations.size() > 10) { try { contentResolver.applyBatch(MetaContract.CONTENT_AUTHORITY, operations); operations.clear(); } catch (RemoteException e) { Log.e(TAG, "Remote exception", e); } catch (OperationApplicationException e) { MetaUtilities.setIsCached(resourcePath, false); return; } Thread.yield(); } } } finally { c.close(); } } @Override public void onUbuntuOneFailure(U1Failure failure) { MetaService.this.onUbuntuOneFailure(failure, receiver); } @Override public void onFailure(U1Failure failure) { MetaService.this.onFailure(failure, receiver); } @Override public void onFinish() { if (receiver != null) receiver.send(Status.FINISHED, data); } }); // Remove nodes, which ids are left in childrenIds set. if (!childrenIds.isEmpty()) { Log.v(TAG, "childrenIDs not empty: " + childrenIds.size()); final Iterator<Integer> it = childrenIds.iterator(); while (it.hasNext()) { int id = it.next(); Uri uri = MetaUtilities.buildNodeUri(id); ContentProviderOperation op = ContentProviderOperation.newDelete(uri).build(); operations.add(op); } } else { Log.v(TAG, "childrenIDs empty"); } try { long then = System.currentTimeMillis(); contentResolver.applyBatch(MetaContract.CONTENT_AUTHORITY, operations); MetaUtilities.setIsCached(resourcePath, true); long now = System.currentTimeMillis(); Log.d(TAG, "time to update children: " + (now - then)); contentResolver.notifyChange(Nodes.CONTENT_URI, null); } catch (RemoteException e) { Log.e(TAG, "", e); } catch (OperationApplicationException e) { MetaUtilities.setIsCached(resourcePath, false); return; } }
From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java
private void sendDisasterDM(Long last) { Uri uriQuery = Uri.parse("content://" + DirectMessages.DM_AUTHORITY + "/" + DirectMessages.DMS + "/" + DirectMessages.DMS_LIST + "/" + DirectMessages.DMS_SOURCE_DISASTER); Cursor c = getContentResolver().query(uriQuery, null, null, null, null); Log.i(TAG, "c.getCount: " + c.getCount()); if (c.getCount() > 0) { c.moveToFirst();//from ww w.j ava 2 s . c o m while (!c.isAfterLast()) { if (c.getLong(c.getColumnIndex(DirectMessages.COL_RECEIVED)) > (last - 1 * 30 * 1000L)) { JSONObject dmToSend; try { dmToSend = getDmJSON(c); if (dmToSend != null) { Log.i(TAG, "sending dm"); bluetoothHelper.write(dmToSend.toString()); } } catch (JSONException ex) { } } c.moveToNext(); } } c.close(); }
From source file:com.flowzr.budget.holo.export.flowzr.FlowzrSyncEngine.java
public static void pushAllBlobs() { if (db == null) { if (context == null) { context = MainActivity.activity; }/* w w w.j a va 2 s .c om*/ db = new DatabaseAdapter(context).db(); } String sql = "select attached_picture,datetime,remote_key,blob_key " + "from transactions " + "where attached_picture is not null " + "and blob_key is null"; Cursor cursorCursor = db.rawQuery(sql, null); int i = 0; if (cursorCursor.moveToFirst()) { do { i = i + 10; notifyUser(cursorCursor.getString(0) + " >> Google Drive. " + context.getString(R.string.hint_run_background), i); if (i == 100) { i = 10; } saveFileToDrive(cursorCursor.getString(0), cursorCursor.getLong(1), cursorCursor.getString(2)); } while (cursorCursor.moveToNext()); } cursorCursor.close(); notifyUser(context.getString(R.string.googledrive_upload) + " " + context.getString(R.string.ok), 100); }
From source file:com.geniusgithub.contact.contact.model.ContactLoader.java
/** * Loads groups meta-data for all groups associated with all constituent raw contacts' * accounts./*from ww w .java 2s . co m*/ */ private void loadGroupMetaData(Contact result) { StringBuilder selection = new StringBuilder(); ArrayList<String> selectionArgs = new ArrayList<String>(); for (RawContact rawContact : result.getRawContacts()) { final String accountName = rawContact.getAccountName(); final String accountType = rawContact.getAccountTypeString(); final String dataSet = rawContact.getDataSet(); if (accountName != null && accountType != null) { if (selection.length() != 0) { selection.append(" OR "); } selection.append("(" + Groups.ACCOUNT_NAME + "=? AND " + Groups.ACCOUNT_TYPE + "=?"); selectionArgs.add(accountName); selectionArgs.add(accountType); if (dataSet != null) { selection.append(" AND " + Groups.DATA_SET + "=?"); selectionArgs.add(dataSet); } else { selection.append(" AND " + Groups.DATA_SET + " IS NULL"); } selection.append(")"); } } final ImmutableList.Builder<GroupMetaData> groupListBuilder = new ImmutableList.Builder<GroupMetaData>(); final Cursor cursor = getContext().getContentResolver().query(Groups.CONTENT_URI, GroupQuery.COLUMNS, selection.toString(), selectionArgs.toArray(new String[0]), null); if (cursor != null) { try { while (cursor.moveToNext()) { final String accountName = cursor.getString(GroupQuery.ACCOUNT_NAME); final String accountType = cursor.getString(GroupQuery.ACCOUNT_TYPE); final String dataSet = cursor.getString(GroupQuery.DATA_SET); final long groupId = cursor.getLong(GroupQuery.ID); final String title = cursor.getString(GroupQuery.TITLE); final boolean defaultGroup = cursor.isNull(GroupQuery.AUTO_ADD) ? false : cursor.getInt(GroupQuery.AUTO_ADD) != 0; final boolean favorites = cursor.isNull(GroupQuery.FAVORITES) ? false : cursor.getInt(GroupQuery.FAVORITES) != 0; groupListBuilder.add(new GroupMetaData(accountName, accountType, dataSet, groupId, title, defaultGroup, favorites)); } } finally { cursor.close(); } } result.setGroupMetaData(groupListBuilder.build()); }
From source file:com.sferadev.etic.tasks.DownloadTasksTask.java
private void updateTaskStatusToServer(FileDbAdapter fda, String source, String username, String password, String serverUrl) throws Exception { Log.i("updateTaskStatusToServer", "Enter"); Cursor taskListCursor = fda.fetchTasksForSource(source, false); taskListCursor.moveToFirst();/*from w w w .ja v a2 s.c o m*/ DefaultHttpClient client = new DefaultHttpClient(); HttpResponse getResponse = null; // Add credentials if (username != null && password != null) { client.getCredentialsProvider().setCredentials(new AuthScope(null, -1, null), new UsernamePasswordCredentials(username, password)); } while (!taskListCursor.isAfterLast()) { if (isCancelled()) { return; } ; // Return if the user cancels String newStatus = taskListCursor.getString(taskListCursor.getColumnIndex(FileDbAdapter.KEY_T_STATUS)); String syncStatus = taskListCursor .getString(taskListCursor.getColumnIndex(FileDbAdapter.KEY_T_IS_SYNC)); long aid = taskListCursor.getLong(taskListCursor.getColumnIndex(FileDbAdapter.KEY_T_ASSIGNMENTID)); long tid = taskListCursor.getLong(taskListCursor.getColumnIndex(FileDbAdapter.KEY_T_ID)); Log.i("updateTaskStatusToServer", "aId:" + aid + " -- status:" + newStatus + " -- syncStatus:" + syncStatus); // Call the update service if (newStatus != null && syncStatus.equals(FileDbAdapter.STATUS_SYNC_NO)) { Log.i(getClass().getSimpleName(), "Updating server with status of " + aid + " to " + newStatus); Assignment a = new Assignment(); a.assignment_id = (int) aid; a.assignment_status = newStatus; // Call the service String taskURL = serverUrl + "/surveyKPI/myassignments/" + aid; HttpPost postRequest = new HttpPost(taskURL); ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("assignInput", "{assignment_status: " + newStatus + "}")); postRequest.setEntity(new UrlEncodedFormEntity(postParameters)); getResponse = client.execute(postRequest); int statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(getClass().getSimpleName(), "Error:" + statusCode + " for URL " + taskURL); } else { Log.w("updateTaskStatusToServer", "Status updated"); fda.setTaskSynchronized(tid); // Mark the task status as synchronised } } taskListCursor.moveToNext(); } taskListCursor.close(); }
From source file:org.gege.caldavsyncadapter.syncadapter.SyncAdapter.java
/** * checks the android events for the dirty flag. * the flag is set by android when the event has been changed. * the dirty flag is removed when an android event has been updated from calendar event * @param provider//from w ww.j av a2 s . c o m * @param account * @param calendarUri * @param facade * @param caldavCalendarUri * @param stats * @param notifyList * @return count of dirty events */ private int checkDirtyAndroidEvents(ContentProviderClient provider, Account account, Uri calendarUri, CaldavFacade facade, URI caldavCalendarUri, SyncStats stats, ArrayList<Uri> notifyList) { Cursor curEvent = null; Cursor curAttendee = null; Cursor curReminder = null; Long EventID; Long CalendarID; AndroidEvent androidEvent = null; int rowDirty = 0; int rowInsert = 0; int rowUpdate = 0; int rowDelete = 0; try { CalendarID = ContentUris.parseId(calendarUri); String selection = "(" + Events.DIRTY + " = ?) AND (" + Events.CALENDAR_ID + " = ?)"; String[] selectionArgs = new String[] { "1", CalendarID.toString() }; curEvent = provider.query(Events.CONTENT_URI, null, selection, selectionArgs, null); while (curEvent.moveToNext()) { EventID = curEvent.getLong(curEvent.getColumnIndex(Events._ID)); Uri returnedUri = ContentUris.withAppendedId(Events.CONTENT_URI, EventID); androidEvent = new AndroidEvent(account, provider, returnedUri, calendarUri); androidEvent.readContentValues(curEvent); selection = "(" + Attendees.EVENT_ID + " = ?)"; selectionArgs = new String[] { String.valueOf(EventID) }; curAttendee = provider.query(Attendees.CONTENT_URI, null, selection, selectionArgs, null); selection = "(" + Reminders.EVENT_ID + " = ?)"; selectionArgs = new String[] { String.valueOf(EventID) }; curReminder = provider.query(Reminders.CONTENT_URI, null, selection, selectionArgs, null); androidEvent.readAttendees(curAttendee); androidEvent.readReminder(curReminder); curAttendee.close(); curReminder.close(); String SyncID = androidEvent.ContentValues.getAsString(Events._SYNC_ID); boolean Deleted = false; int intDeleted = 0; intDeleted = curEvent.getInt(curEvent.getColumnIndex(Events.DELETED)); Deleted = (intDeleted == 1); if (SyncID == null) { // new Android event String newGUID = java.util.UUID.randomUUID().toString() + "-caldavsyncadapter"; String calendarPath = caldavCalendarUri.getPath(); if (!calendarPath.endsWith("/")) calendarPath += "/"; SyncID = calendarPath + newGUID + ".ics"; androidEvent.createIcs(newGUID); if (facade.createEvent(URI.create(SyncID), androidEvent.getIcsEvent().toString())) { //HINT: bugfix for google calendar if (SyncID.contains("@")) SyncID = SyncID.replace("@", "%40"); ContentValues values = new ContentValues(); values.put(Events._SYNC_ID, SyncID); //google doesn't send the etag after creation //HINT: my SabreDAV send always the same etag after putting a new event //String LastETag = facade.getLastETag(); //if (!LastETag.equals("")) { // values.put(Event.ETAG, LastETag); //} else { //so get the etag with a new REPORT CalendarEvent calendarEvent = new CalendarEvent(account, provider); calendarEvent.calendarURL = caldavCalendarUri.toURL(); URI SyncURI = new URI(SyncID); calendarEvent.setUri(SyncURI); CaldavFacade.getEvent(calendarEvent); values.put(Event.ETAG, calendarEvent.getETag()); //} values.put(Event.UID, newGUID); values.put(Events.DIRTY, 0); values.put(Event.RAWDATA, androidEvent.getIcsEvent().toString()); int rowCount = provider.update( asSyncAdapter(androidEvent.getUri(), account.name, account.type), values, null, null); if (rowCount == 1) { rowInsert += 1; notifyList.add(androidEvent.getUri()); } } } else if (Deleted) { // deleted Android event if (facade.deleteEvent(URI.create(SyncID), androidEvent.getETag())) { String mSelectionClause = "(" + Events._ID + "= ?)"; String[] mSelectionArgs = { String.valueOf(EventID) }; int countDeleted = provider.delete( asSyncAdapter(Events.CONTENT_URI, account.name, account.type), mSelectionClause, mSelectionArgs); if (countDeleted == 1) { rowDelete += 1; notifyList.add(androidEvent.getUri()); } } } else { //update the android event to the server String uid = androidEvent.getUID(); if ((uid == null) || (uid.equals(""))) { //COMPAT: this is needed because in the past, the UID was not stored in the android event CalendarEvent calendarEvent = new CalendarEvent(account, provider); URI syncURI = new URI(SyncID); calendarEvent.setUri(syncURI); calendarEvent.calendarURL = caldavCalendarUri.toURL(); if (calendarEvent.fetchBody()) { calendarEvent.readContentValues(); uid = calendarEvent.getUID(); } } if (uid != null) { androidEvent.createIcs(uid); if (facade.updateEvent(URI.create(SyncID), androidEvent.getIcsEvent().toString(), androidEvent.getETag())) { selection = "(" + Events._ID + "= ?)"; selectionArgs = new String[] { EventID.toString() }; androidEvent.ContentValues.put(Events.DIRTY, 0); //google doesn't send the etag after update String LastETag = facade.getLastETag(); if (!LastETag.equals("")) { androidEvent.ContentValues.put(Event.ETAG, LastETag); } else { //so get the etag with a new REPORT CalendarEvent calendarEvent = new CalendarEvent(account, provider); calendarEvent.calendarURL = caldavCalendarUri.toURL(); URI SyncURI = new URI(SyncID); calendarEvent.setUri(SyncURI); CaldavFacade.getEvent(calendarEvent); androidEvent.ContentValues.put(Event.ETAG, calendarEvent.getETag()); } androidEvent.ContentValues.put(Event.RAWDATA, androidEvent.getIcsEvent().toString()); int RowCount = provider.update( asSyncAdapter(androidEvent.getUri(), account.name, account.type), androidEvent.ContentValues, null, null); if (RowCount == 1) { rowUpdate += 1; notifyList.add(androidEvent.getUri()); } } else { rowDirty += 1; } } else { rowDirty += 1; } } } curEvent.close(); /*if ((rowInsert > 0) || (rowUpdate > 0) || (rowDelete > 0) || (rowDirty > 0)) { Log.i(TAG,"Android Rows inserted: " + String.valueOf(rowInsert)); Log.i(TAG,"Android Rows updated: " + String.valueOf(rowUpdate)); Log.i(TAG,"Android Rows deleted: " + String.valueOf(rowDelete)); Log.i(TAG,"Android Rows dirty: " + String.valueOf(rowDirty)); }*/ stats.numInserts += rowInsert; stats.numUpdates += rowUpdate; stats.numDeletes += rowDelete; stats.numSkippedEntries += rowDirty; stats.numEntries += rowInsert + rowUpdate + rowDelete; } catch (RemoteException e) { e.printStackTrace(); } catch (URISyntaxException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } catch (IOException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } catch (CaldavProtocolException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } catch (ParserException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } return rowDirty; }
From source file:org.gege.caldavsyncadapter.caldav.entities.CalendarEvent.java
/** * searches for an android event//w ww . j a va 2 s.c o m * @param androidCalendar * @return the android event * @throws RemoteException */ public AndroidEvent getAndroidEvent(DavCalendar androidCalendar) throws RemoteException { boolean Error = false; Uri uriEvents = Events.CONTENT_URI; Uri uriAttendee = Attendees.CONTENT_URI; Uri uriReminder = Reminders.CONTENT_URI; AndroidEvent androidEvent = null; String selection = "(" + Events._SYNC_ID + " = ?)"; String[] selectionArgs = new String[] { this.getUri().toString() }; Cursor curEvent = this.mProvider.query(uriEvents, null, selection, selectionArgs, null); Cursor curAttendee = null; Cursor curReminder = null; if (curEvent == null) { Error = true; } if (!Error) { if (curEvent.getCount() == 0) { Error = true; } } if (!Error) { curEvent.moveToNext(); long EventID = curEvent.getLong(curEvent.getColumnIndex(Events._ID)); Uri returnedUri = ContentUris.withAppendedId(uriEvents, EventID); androidEvent = new AndroidEvent(this.mAccount, this.mProvider, returnedUri, androidCalendar.getAndroidCalendarUri()); androidEvent.readContentValues(curEvent); selection = "(" + Attendees.EVENT_ID + " = ?)"; selectionArgs = new String[] { String.valueOf(EventID) }; curAttendee = this.mProvider.query(uriAttendee, null, selection, selectionArgs, null); selection = "(" + Reminders.EVENT_ID + " = ?)"; selectionArgs = new String[] { String.valueOf(EventID) }; curReminder = this.mProvider.query(uriReminder, null, selection, selectionArgs, null); androidEvent.readAttendees(curAttendee); androidEvent.readReminder(curReminder); curAttendee.close(); curReminder.close(); } curEvent.close(); return androidEvent; }
From source file:com.piusvelte.sonet.core.SonetCreatePost.java
@Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.menu_post_accounts) chooseAccounts();/*from w ww . j av a2 s . co m*/ else if (itemId == R.id.menu_post_photo) { boolean supported = false; Iterator<Integer> services = mAccountsService.values().iterator(); while (services.hasNext() && ((supported = sPhotoSupported.contains(services.next())) == false)) ; if (supported) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), PHOTO); } else unsupportedToast(sPhotoSupported); // } else if (itemId == R.id.menu_post_tags) { // if (mAccountsService.size() == 1) { // if (sTaggingSupported.contains(mAccountsService.values().iterator().next())) // selectFriends(mAccountsService.keySet().iterator().next()); // else // unsupportedToast(sTaggingSupported); // } else { // // dialog to select an account // Iterator<Long> accountIds = mAccountsService.keySet().iterator(); // HashMap<Long, String> accountEntries = new HashMap<Long, String>(); // while (accountIds.hasNext()) { // Long accountId = accountIds.next(); // Cursor account = this.getContentResolver().query(Accounts.getContentUri(this), new String[]{Accounts._ID, ACCOUNTS_QUERY}, Accounts._ID + "=?", new String[]{Long.toString(accountId)}, null); // if (account.moveToFirst() && sTaggingSupported.contains(mAccountsService.get(accountId))) // accountEntries.put(account.getLong(0), account.getString(1)); // } // int size = accountEntries.size(); // if (size != 0) { // final long[] accountIndexes = new long[size]; // final String[] accounts = new String[size]; // int i = 0; // Iterator<Map.Entry<Long, String>> entries = accountEntries.entrySet().iterator(); // while (entries.hasNext()) { // Map.Entry<Long, String> entry = entries.next(); // accountIndexes[i] = entry.getKey(); // accounts[i++] = entry.getValue(); // } // mDialog = (new AlertDialog.Builder(this)) // .setTitle(R.string.accounts) // .setSingleChoiceItems(accounts, -1, new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // selectFriends(accountIndexes[which]); // dialog.dismiss(); // } // }) // .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }) // .create(); // mDialog.show(); // } else // unsupportedToast(sTaggingSupported); // } } else if (itemId == R.id.menu_post_location) { LocationManager locationManager = (LocationManager) SonetCreatePost.this .getSystemService(Context.LOCATION_SERVICE); Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { mLat = Double.toString(location.getLatitude()); mLong = Double.toString(location.getLongitude()); if (mAccountsService.size() == 1) { if (sLocationSupported.contains(mAccountsService.values().iterator().next())) setLocation(mAccountsService.keySet().iterator().next()); else unsupportedToast(sLocationSupported); } else { // dialog to select an account Iterator<Long> accountIds = mAccountsService.keySet().iterator(); HashMap<Long, String> accountEntries = new HashMap<Long, String>(); while (accountIds.hasNext()) { Long accountId = accountIds.next(); Cursor account = this.getContentResolver().query(Accounts.getContentUri(this), new String[] { Accounts._ID, ACCOUNTS_QUERY }, Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null); if (account.moveToFirst() && sLocationSupported.contains(mAccountsService.get(accountId))) accountEntries.put(account.getLong(account.getColumnIndex(Accounts._ID)), account.getString(account.getColumnIndex(Accounts.USERNAME))); } int size = accountEntries.size(); if (size != 0) { final long[] accountIndexes = new long[size]; final String[] accounts = new String[size]; int i = 0; Iterator<Map.Entry<Long, String>> entries = accountEntries.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<Long, String> entry = entries.next(); accountIndexes[i] = entry.getKey(); accounts[i++] = entry.getValue(); } mDialog = (new AlertDialog.Builder(this)).setTitle(R.string.accounts) .setSingleChoiceItems(accounts, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setLocation(accountIndexes[which]); dialog.dismiss(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create(); mDialog.show(); } else unsupportedToast(sLocationSupported); } } else (Toast.makeText(this, getString(R.string.location_unavailable), Toast.LENGTH_LONG)).show(); } return super.onOptionsItemSelected(item); }