Java Code Examples for android.database.Cursor#getString()
The following examples show how to use
android.database.Cursor#getString() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AtUsersDBTask.java From iBeebo with GNU General Public License v3.0 | 6 votes |
public static List<AtUserBean> get(SQLiteDatabase db, String accountId) { List<AtUserBean> msgList = new ArrayList<AtUserBean>(); String sql = "select * from " + AtUsersTable.TABLE_NAME + " where " + AtUsersTable.ACCOUNTID + " = " + accountId + " order by " + AtUsersTable.ID + " desc"; Cursor c = db.rawQuery(sql, null); Gson gson = new Gson(); while (c.moveToNext()) { String json = c.getString(c.getColumnIndex(AtUsersTable.JSONDATA)); try { AtUserBean value = gson.fromJson(json, AtUserBean.class); msgList.add(value); } catch (JsonSyntaxException e) { AppLoggerUtils.e(e.getMessage()); } } c.close(); return msgList; }
Example 2
Source File: GalleryUtils.java From photo-editor-android with MIT License | 6 votes |
/** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context * The context. * @param uri * The Uri to query. * @param selection * (Optional) Filter used in the query. * @param selectionArgs * (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. */ public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int column_index = cursor.getColumnIndexOrThrow(column); return cursor.getString(column_index); } } finally { if (cursor != null) cursor.close(); } return null; }
Example 3
Source File: LogsManager.java From calllogs with BSD 2-Clause "Simplified" License | 6 votes |
public int getOutgoingDuration() { int sum = 0; Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, CallLog.Calls.TYPE + " = " + CallLog.Calls.OUTGOING_TYPE, null, null); int duration = cursor.getColumnIndex(CallLog.Calls.DURATION); while (cursor.moveToNext()) { String callDuration = cursor.getString(duration); sum += Integer.parseInt(callDuration); } cursor.close(); return sum; }
Example 4
Source File: ContactPhoneNumberLoader.java From RememBirthday with GNU General Public License v3.0 | 6 votes |
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { List<PhoneNumber> phoneNumbers = new ArrayList<>(); if(cursor != null && !cursor.isClosed()) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { String number = cursor.getString(cursor.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER)); int type = cursor.getInt(cursor.getColumnIndex( ContactsContract.CommonDataKinds.Phone.TYPE)); phoneNumbers.add(new PhoneNumber(number, type)); cursor.moveToNext(); } // TODO try catch with id cursor.close(); } if(callbackActionPhoneNumber != null) callbackActionPhoneNumber.afterActionPhoneNumberInDatabase(phoneNumbers); }
Example 5
Source File: DatabaseAccess.java From QuranAndroid with GNU General Public License v3.0 | 6 votes |
/** * Function to get aya from position * * @param position Position of aya * @return Aya object */ public Aya getAyaFromPosition(int position) { Aya aya = null; try { SQLiteDatabase db = openDB(MAIN_DATABASE); String sql = "select a.name , a.name_english , b.soraid , b.ayaid , b.page , b.text from sora a , aya b where a.soraid = b.soraid limit " + position + ",1 ;"; Cursor cursor = db.rawQuery(sql, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { aya = new Aya(cursor.getInt(4), cursor.getInt(3), cursor.getInt(2), cursor.getString(5), cursor.getString(0), cursor.getString(1)); cursor.moveToNext(); } cursor.close(); closeDB(db); } catch (Exception e) { e.printStackTrace(); } return aya; }
Example 6
Source File: YiIMUtils.java From yiim_v2 with GNU General Public License v2.0 | 6 votes |
public static String getMultUserChatDesc(Context context, String roomJid) { String owner = UserInfo.getUserInfo(context).getUser(); Cursor cursor = null; try { cursor = context.getContentResolver().query( MultiChatRoomColumns.CONTENT_URI, new String[] { MultiChatRoomColumns.ROOM_DESC }, MultiChatRoomColumns.ROOM_JID + "='" + roomJid + "' and " + MultiChatRoomColumns.OWNER + "='" + owner + "'", null, null); if (cursor != null && cursor.getCount() == 1) { cursor.moveToFirst(); return cursor.getString(0); } return ""; } catch (Exception e) { return ""; } finally { if (cursor != null) { cursor.close(); cursor = null; } } }
Example 7
Source File: FilePickUtils.java From ml with Apache License 2.0 | 6 votes |
/** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context The context. * @param uri The Uri to query. * @param selection (Optional) Filter used in the query. * @param selectionArgs (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. */ public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int column_index = cursor.getColumnIndexOrThrow(column); return cursor.getString(column_index); } } finally { if (cursor != null) cursor.close(); } return null; }
Example 8
Source File: DownloadedVideosDb.java From SkyTube with GNU General Public License v3.0 | 6 votes |
public Uri getVideoFileUri(String videoId) { Cursor cursor = null; try { cursor = getReadableDatabase().query( DownloadedVideosTable.TABLE_NAME, new String[]{DownloadedVideosTable.COL_FILE_URI}, DownloadedVideosTable.COL_YOUTUBE_VIDEO_ID + " = ?", new String[]{videoId}, null, null, null); if (cursor.moveToNext()) { String uri = cursor.getString(cursor.getColumnIndex(DownloadedVideosTable.COL_FILE_URI)); return Uri.parse(uri); } return null; } finally { if (cursor != null) { cursor.close(); } } }
Example 9
Source File: DatabaseHelper.java From emerald with GNU General Public License v3.0 | 6 votes |
public static void removeAppFromCategory(Context context, String id, String categoryName) { SQLiteDatabase db = getDatabase(context); Cursor cursor = db.rawQuery("SELECT component, categories FROM apps WHERE component = '" + id + "'", null); if (!cursor.moveToFirst()) { cursor.close(); close(); return; } String categoryNameSQL = "@" + categoryName + "@"; String oldCategoriesList = cursor.getString(1); int startIndex = oldCategoriesList.indexOf(categoryNameSQL); String newValue = new StringBuilder(oldCategoriesList).delete(startIndex, startIndex+categoryNameSQL.length()).toString(); ContentValues values = new ContentValues(); values.put("categories", newValue); db.update("apps", values, "component = ?", new String[]{cursor.getString(0)}); cursor.close(); close(); }
Example 10
Source File: TestUtilities.java From android-dev-challenge with Apache License 2.0 | 6 votes |
/** * This method iterates through a set of expected values and makes various assertions that * will pass if our app is functioning properly. * * @param error Message when an error occurs * @param valueCursor The Cursor containing the actual values received from an arbitrary query * @param expectedValues The values we expect to receive in valueCursor */ static void validateCurrentRecord(String error, Cursor valueCursor, ContentValues expectedValues) { Set<Map.Entry<String, Object>> valueSet = expectedValues.valueSet(); for (Map.Entry<String, Object> entry : valueSet) { String columnName = entry.getKey(); int index = valueCursor.getColumnIndex(columnName); /* Test to see if the column is contained within the cursor */ String columnNotFoundError = "Column '" + columnName + "' not found. " + error; assertFalse(columnNotFoundError, index == -1); /* Test to see if the expected value equals the actual value (from the Cursor) */ String expectedValue = entry.getValue().toString(); String actualValue = valueCursor.getString(index); String valuesDontMatchError = "Actual value '" + actualValue + "' did not match the expected value '" + expectedValue + "'. " + error; assertEquals(valuesDontMatchError, expectedValue, actualValue); } }
Example 11
Source File: SimpleDragSortCursorAdapter.java From android-kernel-tweaker with GNU General Public License v3.0 | 5 votes |
/** * Binds all of the field names passed into the "to" parameter of the * constructor with their corresponding cursor columns as specified in the * "from" parameter. * * Binding occurs in two phases. First, if a * {@link android.widget.SimpleCursorAdapter.ViewBinder} is available, * {@link ViewBinder#setViewValue(android.view.View, android.database.Cursor, int)} * is invoked. If the returned value is true, binding has occured. If the * returned value is false and the view to bind is a TextView, * {@link #setViewText(TextView, String)} is invoked. If the returned value is * false and the view to bind is an ImageView, * {@link #setViewImage(ImageView, String)} is invoked. If no appropriate * binding can be found, an {@link IllegalStateException} is thrown. * * @throws IllegalStateException if binding cannot occur * * @see android.widget.CursorAdapter#bindView(android.view.View, * android.content.Context, android.database.Cursor) * @see #getViewBinder() * @see #setViewBinder(android.widget.SimpleCursorAdapter.ViewBinder) * @see #setViewImage(ImageView, String) * @see #setViewText(TextView, String) */ @Override public void bindView(View view, Context context, Cursor cursor) { final ViewBinder binder = mViewBinder; final int count = mTo.length; final int[] from = mFrom; final int[] to = mTo; for (int i = 0; i < count; i++) { final View v = view.findViewById(to[i]); if (v != null) { boolean bound = false; if (binder != null) { bound = binder.setViewValue(v, cursor, from[i]); } if (!bound) { String text = cursor.getString(from[i]); if (text == null) { text = ""; } if (v instanceof TextView) { setViewText((TextView) v, text); } else if (v instanceof ImageView) { setViewImage((ImageView) v, text); } else { throw new IllegalStateException(v.getClass().getName() + " is not a " + " view that can be bounds by this SimpleCursorAdapter"); } } } } }
Example 12
Source File: PathUtils.java From Luban with Apache License 2.0 | 5 votes |
/** * <b>BuildTime:</b> 2014年10月23日<br> * <b>Description:</b> Use the uri to get the file path<br> * * @param c * @param uri * * @return */ public static String getAbsoluteUriPath(Context c, Uri uri) { String imgPath = ""; String[] proj = {MediaStore.Images.Media.DATA}; Cursor cursor = new CursorLoader(c, uri, proj, null, null, null).loadInBackground(); if (cursor != null) { int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); if (cursor.getCount() > 0 && cursor.moveToFirst()) { imgPath = cursor.getString(column_index); } } return imgPath; }
Example 13
Source File: GcmDatabase.java From android_packages_apps_GmsCore with Apache License 2.0 | 5 votes |
private App(Cursor cursor) { packageName = cursor.getString(cursor.getColumnIndex(FIELD_PACKAGE_NAME)); lastError = cursor.getString(cursor.getColumnIndex(FIELD_LAST_ERROR)); lastMessageTimestamp = cursor.getLong(cursor.getColumnIndex(FIELD_LAST_MESSAGE_TIMESTAMP)); totalMessageCount = cursor.getLong(cursor.getColumnIndex(FIELD_TOTAL_MESSAGE_COUNT)); totalMessageBytes = cursor.getLong(cursor.getColumnIndex(FIELD_TOTAL_MESSAGE_BYTES)); allowRegister = cursor.getLong(cursor.getColumnIndex(FIELD_ALLOW_REGISTER)) == 1; wakeForDelivery = cursor.getLong(cursor.getColumnIndex(FIELD_WAKE_FOR_DELIVERY)) == 1; }
Example 14
Source File: FileHelper.java From showCaseCordova with Apache License 2.0 | 5 votes |
@SuppressLint("NewApi") public static String getRealPathFromURI_API19(Context context, Uri uri) { String filePath = ""; try { String wholeID = DocumentsContract.getDocumentId(uri); // Split at colon, use second item in the array String id = wholeID.indexOf(":") > -1 ? wholeID.split(":")[1] : wholeID.indexOf(";") > -1 ? wholeID .split(";")[1] : wholeID; String[] column = { MediaStore.Images.Media.DATA }; // where id is equal to String sel = MediaStore.Images.Media._ID + "=?"; Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[] { id }, null); int columnIndex = cursor.getColumnIndex(column[0]); if (cursor.moveToFirst()) { filePath = cursor.getString(columnIndex); } cursor.close(); } catch (Exception e) { filePath = ""; } return filePath; }
Example 15
Source File: BookDao.java From MissZzzReader with Apache License 2.0 | 4 votes |
@Override public String readKey(Cursor cursor, int offset) { return cursor.isNull(offset + 0) ? null : cursor.getString(offset + 0); }
Example 16
Source File: Db.java From sqlbrite with Apache License 2.0 | 4 votes |
public static String getString(Cursor cursor, String columnName) { return cursor.getString(cursor.getColumnIndexOrThrow(columnName)); }
Example 17
Source File: WebCommandsExecutor.java From PhoneMonitor with GNU General Public License v3.0 | 4 votes |
String getSMSMessages() { //Returns a JSON array string of JSON objects of SMS messages; "" if failed //the SMS content provider is undocumented as of yet(27th Dec, 2017 | 10:59PM | GMT+05:45). //the following links and some testing on my part went into making of this method //http://grepcode.com/file/repo1.maven.org/maven2/org.robolectric/android-all/4.1.2_r1-robolectric-0/android/provider/Telephony.java#Telephony.TextBasedSmsColumns //https://stackoverflow.com/questions/1976252/how-to-use-sms-content-provider-where-are-the-docs //the messages are by default retrieved in descending order of date String retval = ""; JSONArray smsJsonArr = new JSONArray(); Uri smsUri = Uri.parse("content://sms"); String[] columns = {"type", "thread_id", "address", "date", "read", "body"}; Cursor cursor = context.getContentResolver().query(smsUri, columns, null, null, null); if (cursor != null) { while (cursor.moveToNext()) { int type_ = cursor.getInt(cursor.getColumnIndex("type")); String type; switch (type_) { case 1: type = "Inbox"; break; case 2: type = "Sent"; break; case 3: type = "Draft"; break; case 4: type = "Outbox"; break; case 5: type = "Failed"; break; case 6: type = "Queued"; break; default: type = "Type " + type_; } int threadid = cursor.getInt(cursor.getColumnIndex("thread_id")); String address = cursor.getString(cursor.getColumnIndex("address")); //get the contact name corresponding to the number(address) String personName = ""; Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(address)); Cursor phoneLookupCursor = context.getContentResolver().query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null); if (phoneLookupCursor != null) { if (phoneLookupCursor.moveToNext()) { personName = phoneLookupCursor.getString(phoneLookupCursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)); } phoneLookupCursor.close(); } String date = cursor.getString(cursor.getColumnIndex("date")); int read = cursor.getInt(cursor.getColumnIndex("read")); String body = cursor.getString(cursor.getColumnIndex("body")); try { JSONObject indivSMS = new JSONObject(); indivSMS.put("ThreadId", threadid); indivSMS.put("Type", type); indivSMS.put("Address", address); indivSMS.put("Date", date); indivSMS.put("ReadStatus", read); indivSMS.put("Body", body); indivSMS.put("PersonName", personName);//personName is "" if the address(number) couldn't be resolved into a contact name smsJsonArr.put(indivSMS); } catch (JSONException jsex) { //error while creating json object/array. skip this entry } } cursor.close(); retval = smsJsonArr.toString(); } return retval; }
Example 18
Source File: CaptureActivity.java From o2oa with GNU Affero General Public License v3.0 | 4 votes |
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { switch (requestCode) { case 1: Uri selectedImage = data.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); Result resultString = scanningImage1(picturePath); if (resultString == null) { Toast.makeText(getApplicationContext(), "解析错误,请选择正确的二维码图片", Toast.LENGTH_LONG).show(); } else { String resultImage = resultString.getText(); if (resultImage.equals("")) { Toast.makeText(CaptureActivity.this, "扫描失败", Toast.LENGTH_SHORT).show(); } else { Intent resultIntent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("result", resultImage); resultIntent.putExtras(bundle); CaptureActivity.this.setResult(RESULT_OK, resultIntent); } CaptureActivity.this.finish(); } break; default: break; } } super.onActivityResult(requestCode, resultCode, data); }
Example 19
Source File: PluginDatabaseManager.java From PluginLoader with Apache License 2.0 | 4 votes |
/** * convert to info list * * @param cursor cursor * @return infos */ private PluginDescriptor convertToPlugin(Cursor cursor) { if (cursor == null || cursor.getCount() == 0) { return null; } else { PluginDescriptor pluginDescriptor = new PluginDescriptor(); String pluginId = cursor.getString(cursor.getColumnIndex(Columns.PLUGIN_ID)); String url = cursor.getString(cursor.getColumnIndex(Columns.URL)); String pluginName = cursor.getString(cursor.getColumnIndex(Columns.PLUGIN_NAME)); String packageName = cursor.getString(cursor.getColumnIndex(Columns.PACKAGE_NAME)); String path = cursor.getString(cursor.getColumnIndex(Columns.INSTALL_PATH)); String version = cursor.getString(cursor.getColumnIndex(Columns.VERSION)); String mianAt = cursor.getString(cursor.getColumnIndex(Columns.APK_MAINACTIVITY)); int status = cursor.getInt(cursor.getColumnIndex(Columns.STATUS)); int type = cursor.getInt(cursor.getColumnIndex(Columns.TYPE)); String descripion = cursor.getString(cursor.getColumnIndex(Columns.DESCRIPTION)); int isEnableValue = cursor.getInt(cursor.getColumnIndex(Columns.IS_ENABLED)); int isStandaloneValue = cursor.getInt(cursor.getColumnIndex(Columns.IS_STANDALONE)); byte[] appIconByte = cursor.getBlob(cursor.getColumnIndex(Columns.APP_ICON)); String applicationName = cursor.getString(cursor.getColumnIndex(Columns.APPLICATION_NAME)); int applicationLogo = cursor.getInt(cursor.getColumnIndex(Columns.APPLICATION_LOGO)); int apiacationIcon = cursor.getInt(cursor.getColumnIndex(Columns.APPLICATION_ICON)); int applicationTheme = cursor.getInt(cursor.getColumnIndex(Columns.APPLICATION_THEME)); String activityInfos = cursor.getString(cursor.getColumnIndex(Columns.ACTIVITY_INFOS)); String providerInfos = cursor.getString(cursor.getColumnIndex(Columns.PROVIDER_INFOS)); String activitys = cursor.getString(cursor.getColumnIndex(Columns.ACTIVITYS)); String fragments = cursor.getString(cursor.getColumnIndex(Columns.FRAGMENTS)); String services = cursor.getString(cursor.getColumnIndex(Columns.SERVICES)); String receivers = cursor.getString(cursor.getColumnIndex(Columns.RECEIVERS)); String mata = cursor.getString(cursor.getColumnIndex(Columns.METADATA)); String progressMap = cursor.getString(cursor.getColumnIndex(Columns.PROGRESS_MAP)); // constucts pluginModel pluginDescriptor.setPluginID(pluginId); pluginDescriptor.setPackageName(packageName); pluginDescriptor.setPluginName(pluginName); pluginDescriptor.setApkMainActivity(mianAt); pluginDescriptor.setVersion(version); pluginDescriptor.setPluginType(type); pluginDescriptor.setUrl(url); pluginDescriptor.setInstalledPath(path); pluginDescriptor.setStatus(status); pluginDescriptor.setApkMainActivity(mianAt); pluginDescriptor.setDescription(descripion); pluginDescriptor.setApplicationIcon(apiacationIcon); pluginDescriptor.setApplicationName(applicationName); pluginDescriptor.setApplicationTheme(applicationTheme); pluginDescriptor.setApplicationLogo(applicationLogo); pluginDescriptor.setEnabled(isEnableValue == 0); pluginDescriptor.setStandalone(isStandaloneValue == 0); pluginDescriptor.setAppIcon(appIconByte); pluginDescriptor.setActivityInfos( JsonUtil.parseObject(activityInfos, new TypeReference<HashMap<String, PluginActivityInfo>>() { })); pluginDescriptor.setActivitys( JsonUtil.parseObject(activitys, new TypeReference<HashMap<String, ArrayList<PluginIntentFilter>>>() { })); pluginDescriptor.setProviderInfos( JsonUtil.parseObject(providerInfos, new TypeReference<HashMap<String, PluginProviderInfo>>() { })); pluginDescriptor.setfragments( JsonUtil.parseObject(fragments, new TypeReference<HashMap<String, String>>() { })); pluginDescriptor.setReceivers( JsonUtil.parseObject(receivers, new TypeReference<HashMap<String, ArrayList<PluginIntentFilter>>>() { })); pluginDescriptor.setServices( JsonUtil.parseObject(services, new TypeReference<HashMap <String, ArrayList< PluginIntentFilter >>>(){ })); pluginDescriptor.setMetaData( JsonUtil.parseObject(mata, new TypeReference<HashMap<String, String>>(){ })); return pluginDescriptor; } }
Example 20
Source File: VideoDataFactory.java From Camera2 with Apache License 2.0 | 4 votes |
public VideoItemData fromCursor(Cursor c) { long id = c.getLong(VideoDataQuery.COL_ID); String title = c.getString(VideoDataQuery.COL_TITLE); String mimeType = c.getString(VideoDataQuery.COL_MIME_TYPE); long creationDateInMilliSeconds = c.getLong(VideoDataQuery.COL_DATE_TAKEN); long lastModifiedDateInSeconds = c.getLong(VideoDataQuery.COL_DATE_MODIFIED); Date creationDate = new Date(creationDateInMilliSeconds); Date lastModifiedDate = new Date(lastModifiedDateInSeconds * 1000); String filePath = c.getString(VideoDataQuery.COL_DATA); int width = c.getInt(VideoDataQuery.COL_WIDTH); int height = c.getInt(VideoDataQuery.COL_HEIGHT); Size dimensions; // If the media store doesn't contain a width and a height, use the width and height // of the default camera mode instead. When the metadata loader runs, it will set the // correct values. if (width == 0 || height == 0) { Log.w(TAG, "failed to retrieve width and height from the media store, defaulting " + " to camera profile"); CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH); if (profile != null) { dimensions = new Size(profile.videoFrameWidth, profile.videoFrameHeight); } else { Log.w(TAG, "Video profile was null, defaulting to unknown width and height."); dimensions = UNKNOWN_SIZE; } } else { dimensions = new Size(width, height); } long sizeInBytes = c.getLong(VideoDataQuery.COL_SIZE); double latitude = c.getDouble(VideoDataQuery.COL_LATITUDE); double longitude = c.getDouble(VideoDataQuery.COL_LONGITUDE); long videoDurationMillis = c.getLong(VideoDataQuery.COL_DURATION); Location location = Location.from(latitude, longitude); Uri uri = VideoDataQuery.CONTENT_URI.buildUpon().appendPath(String.valueOf(id)).build(); return new VideoItemData( id, title, mimeType, creationDate, lastModifiedDate, filePath, uri, dimensions, sizeInBytes, 0 /* orientation */, location, videoDurationMillis); }