Java Examples for android.content.ContentResolver
The following java examples will help you to understand the usage of android.content.ContentResolver. These source code samples are taken from different open source projects.
Example 1
| Project: lmis-moz-mobile-master File: SyncService.java View source code |
public void requestSyncImmediately() {
if (LMISApp.getInstance().getFeatureToggleFor(R.bool.feature_training)) {
trainingSyncAdapter.requestSync();
} else {
Log.d(tag, "immediate sync up requested");
Account account = findFirstLmisAccount();
if (account != null) {
Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_FORCE, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
requestSync(account, syncContentAuthority, bundle);
}
}
}Example 2
| Project: buffano-master File: HelloWorld.java View source code |
/* ------------------------------------------------------------ */
public void init(ServletConfig config) throws ServletException {
super.init(config);
//to demonstrate it is possible
Object o = config.getServletContext().getAttribute("org.mortbay.ijetty.contentResolver");
android.content.ContentResolver resolver = (android.content.ContentResolver) o;
android.content.Context androidContext = (android.content.Context) config.getServletContext().getAttribute("org.mortbay.ijetty.context");
proofOfLife = androidContext.getApplicationInfo().packageName;
}Example 3
| Project: i-jetty-master File: HelloWorld.java View source code |
/* ------------------------------------------------------------ */
public void init(ServletConfig config) throws ServletException {
super.init(config);
//to demonstrate it is possible
Object o = config.getServletContext().getAttribute("org.mortbay.ijetty.contentResolver");
android.content.ContentResolver resolver = (android.content.ContentResolver) o;
android.content.Context androidContext = (android.content.Context) config.getServletContext().getAttribute("org.mortbay.ijetty.context");
proofOfLife = androidContext.getApplicationInfo().packageName;
}Example 4
| Project: Android-Pdf-master File: PathFromUri.java View source code |
public static String retrieve(ContentResolver resolver, Uri uri) {
if (uri.getScheme().equals("file")) {
return uri.getPath();
}
final Cursor cursor = resolver.query(uri, new String[] { "_data" }, null, null, null);
if (cursor.moveToFirst()) {
return cursor.getString(0);
}
throw new RuntimeException("Can't retrieve path from uri: " + uri.toString());
}Example 5
| Project: android-pdfview-master File: PathFromUri.java View source code |
public static String retrieve(ContentResolver resolver, Uri uri) {
if (uri.getScheme().equals("file")) {
return uri.getPath();
}
final Cursor cursor = resolver.query(uri, new String[] { "_data" }, null, null, null);
if (cursor.moveToFirst()) {
return cursor.getString(0);
}
throw new RuntimeException("Can't retrieve path from uri: " + uri.toString());
}Example 6
| Project: CeiReport-master File: PathFromUri.java View source code |
public static String retrieve(ContentResolver resolver, Uri uri) {
Log.v("menu", "uri.getScheme()==" + uri.getScheme() + "....uri==" + uri);
if (uri.getScheme().equals("file")) {
return uri.getPath();
}
final Cursor cursor = resolver.query(uri, new String[] { "_data" }, null, null, null);
Log.v("menu", "cursor==" + cursor);
if (cursor.moveToFirst()) {
return cursor.getString(0);
}
throw new RuntimeException("Can't retrieve path from uri: " + uri.toString());
}Example 7
| Project: document-viewer-master File: PathFromUri.java View source code |
public static String retrieve(final ContentResolver resolver, final Uri uri) {
if (uri.getScheme().equals("file")) {
return uri.getPath();
}
final Cursor cursor = resolver.query(uri, new String[] { "_data" }, null, null, null);
if ((cursor != null) && cursor.moveToFirst()) {
final String result = cursor.getString(0);
cursor.close();
return result;
}
if (cursor != null) {
cursor.close();
}
throw new RuntimeException("Can't retrieve path from uri: " + uri.toString());
}Example 8
| Project: quickblox-android-sdk-master File: DeviceUtils.java View source code |
public static String getDeviceUid() {
Context context = CoreApp.getInstance();
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String uniqueDeviceId = telephonyManager.getDeviceId();
if (TextUtils.isEmpty(uniqueDeviceId)) {
// for tablets
ContentResolver cr = context.getContentResolver();
uniqueDeviceId = Settings.Secure.getString(cr, Settings.Secure.ANDROID_ID);
}
return uniqueDeviceId;
}Example 9
| Project: Whatsapp-API-master File: Utils.java View source code |
public static String getMimeType(Context context, File file) {
String mimeType = null;
Uri uri = Uri.fromFile(file);
if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
ContentResolver cr = context.getContentResolver();
mimeType = cr.getType(uri);
} else {
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.toLowerCase());
}
return mimeType;
}Example 10
| Project: android-smart-image-view-master File: ContactImage.java View source code |
public Bitmap getBitmap(Context context) {
Bitmap bitmap = null;
ContentResolver contentResolver = context.getContentResolver();
try {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri);
if (input != null) {
bitmap = BitmapFactory.decodeStream(input);
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}Example 11
| Project: android_packages_apps-master File: UninstallReceiver.java View source code |
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
return;
}
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(Apps.CONTENT_URI, new String[] { Apps._ID }, Apps.UID + "=?", new String[] { String.valueOf(intent.getIntExtra(Intent.EXTRA_UID, -1)) }, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
cr.delete(ContentUris.withAppendedId(Apps.CONTENT_URI, cursor.getLong(0)), null, null);
}
cursor.close();
}
}Example 12
| Project: arrownockers-android-master File: ContactImage.java View source code |
public Bitmap getBitmap(Context context) {
Bitmap bitmap = null;
ContentResolver contentResolver = context.getContentResolver();
try {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri);
if (input != null) {
bitmap = BitmapFactory.decodeStream(input);
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}Example 13
| Project: CampusAssistant-master File: ContactImage.java View source code |
public Bitmap getBitmap(Context paramContext) {
Bitmap localBitmap = null;
ContentResolver localContentResolver = paramContext.getContentResolver();
try {
Uri localUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, this.contactId);
InputStream localInputStream = ContactsContract.Contacts.openContactPhotoInputStream(localContentResolver, localUri);
if (localInputStream != null)
localBitmap = BitmapFactory.decodeStream(localInputStream);
} catch (Exception localException) {
localException.printStackTrace();
}
return localBitmap;
}Example 14
| Project: coursera-android-master File: ContactsListExample.java View source code |
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Contact data
String columnsToExtract[] = new String[] { Contacts._ID, Contacts.DISPLAY_NAME, Contacts.PHOTO_THUMBNAIL_URI };
// Get the ContentResolver
ContentResolver contentResolver = getContentResolver();
// filter contacts with empty names
String whereClause = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND (" + Contacts.DISPLAY_NAME + " != '' ) AND (" + Contacts.STARRED + "== 1))";
// sort by increasing ID
String sortOrder = Contacts._ID + " ASC";
// query contacts ContentProvider
Cursor cursor = contentResolver.query(Contacts.CONTENT_URI, columnsToExtract, whereClause, null, sortOrder);
// pass cursor to custom list adapter
setListAdapter(new ContactInfoListAdapter(this, R.layout.list_item, cursor, 0));
}Example 15
| Project: CZD_Android_Lib-master File: ContactImage.java View source code |
public Bitmap getBitmap(Context context, SmartImageTask.OnCompleteHandler handler) {
Bitmap bitmap = null;
ContentResolver contentResolver = context.getContentResolver();
try {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri);
if (input != null) {
bitmap = BitmapFactory.decodeStream(input);
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}Example 16
| Project: dttv-android-master File: MusicUtils.java View source code |
public static Cursor query(Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, int limit) {
try {
ContentResolver resolver = context.getContentResolver();
if (resolver == null) {
return null;
}
if (limit > 0) {
uri = uri.buildUpon().appendQueryParameter("limit", "" + limit).build();
}
return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
} catch (UnsupportedOperationException ex) {
return null;
}
}Example 17
| Project: GreenLife-master File: ContactImage.java View source code |
public Bitmap getBitmap(Context context) {
Bitmap bitmap = null;
ContentResolver contentResolver = context.getContentResolver();
try {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri);
if (input != null) {
bitmap = BitmapFactory.decodeStream(input);
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}Example 18
| Project: JIkeDream-master File: ContactImage.java View source code |
public Bitmap getBitmap(Context context) {
Bitmap bitmap = null;
ContentResolver contentResolver = context.getContentResolver();
try {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri);
if (input != null) {
bitmap = BitmapFactory.decodeStream(input);
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}Example 19
| Project: kuliah_mobile-master File: ContactsListExample.java View source code |
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Contact data
String columnsToExtract[] = new String[] { Contacts._ID, Contacts.DISPLAY_NAME, Contacts.PHOTO_THUMBNAIL_URI };
// Get the ContentResolver
ContentResolver contentResolver = getContentResolver();
// filter contacts with empty names
String whereClause = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND (" + Contacts.DISPLAY_NAME + " != '' ) AND (" + Contacts.STARRED + "== 1))";
// sort by increasing ID
String sortOrder = Contacts._ID + " ASC";
// query contacts ContentProvider
Cursor cursor = contentResolver.query(Contacts.CONTENT_URI, columnsToExtract, whereClause, null, sortOrder);
// pass cursor to custom list adapter
setListAdapter(new ContactInfoListAdapter(this, R.layout.list_item, cursor, 0));
}Example 20
| Project: LDXY-master File: ContactImage.java View source code |
public Bitmap getBitmap(Context context) {
Bitmap bitmap = null;
ContentResolver contentResolver = context.getContentResolver();
try {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri);
if (input != null) {
bitmap = BitmapFactory.decodeStream(input);
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}Example 21
| Project: malcom-lib-android-master File: ContactImage.java View source code |
public Bitmap getBitmap(Context context) {
Bitmap bitmap = null;
ContentResolver contentResolver = context.getContentResolver();
try {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri);
if (input != null) {
bitmap = BitmapFactory.decodeStream(input);
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}Example 22
| Project: OpenAndroidWeather-master File: ForecastListParserTest.java View source code |
public void testParse() {
/*
ContentResolver cr = getContext().getContentResolver();
String[] projection = {WeatherContentProvider.Meta._ID};
Cursor c = cr.query(WeatherContentProvider.CONTENT_URI, projection , null, null, null);
c.moveToFirst();
int id = c.getInt(c.getColumnIndex(WeatherContentProvider.Meta._ID));
Uri uri = Uri.withAppendedPath(WeatherContentProvider.CONTENT_URI, id+"");
assertNotNull(uri);
ForecastListParser parser = new ForecastListParser(getContext(), null);
List<IListRow> rows = parser.parseData(uri);
assertNotNull(rows);
assertTrue(rows.size()>0);
*/
}Example 23
| Project: Superuser-master File: UninstallReceiver.java View source code |
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
return;
}
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(Apps.CONTENT_URI, new String[] { Apps._ID }, Apps.UID + "=?", new String[] { String.valueOf(intent.getIntExtra(Intent.EXTRA_UID, -1)) }, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
cr.delete(ContentUris.withAppendedId(Apps.CONTENT_URI, cursor.getLong(0)), null, null);
}
cursor.close();
}
}Example 24
| Project: WeCenterMobile-Android-master File: ContactImage.java View source code |
public Bitmap getBitmap(Context context) {
Bitmap bitmap = null;
ContentResolver contentResolver = context.getContentResolver();
try {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri);
if (input != null) {
bitmap = BitmapFactory.decodeStream(input);
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}Example 25
| Project: YourAppIdea-master File: ContentProviderUtils.java View source code |
public static int count(Uri uri, String selection, String[] selectionArgs, ContentResolver contentResolver) {
Cursor cursor = contentResolver.query(uri, new String[] { "count(*)" }, selection, selectionArgs, null);
if (cursor.getCount() == 0) {
cursor.close();
return 0;
} else {
cursor.moveToFirst();
int result = cursor.getInt(0);
cursor.close();
return result;
}
}Example 26
| Project: YourPhotosWatch-master File: PhoneSelectActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_select_activity);
ContentResolver contentResolver = getContentResolver();
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
int sortOrder = getIntent().getIntExtra("sort", R.id.oldest_first);
String order = MediaStore.Images.Media.DATE_TAKEN + " " + (sortOrder == R.id.oldest_first ? "ASC" : "DESC");
Cursor cursor = contentResolver.query(uri, null, null, null, order);
List<PhotoListEntry> entries = new ArrayList<>();
int position = 0;
while (cursor.moveToNext()) {
PhotoListEntry photoListEntry = new PhonePhotoListEntry(cursor, position);
entries.add(photoListEntry);
position++;
}
cursor.close();
setEntries(entries);
}Example 27
| Project: DBFlow-master File: ContentUtils.java View source code |
/**
* Inserts the model into the {@link android.content.ContentResolver}. Uses the insertUri to resolve
* the reference and the model to convert its data into {@link android.content.ContentValues}
*
* @param contentResolver The content resolver to use (if different from {@link FlowManager#getContext()})
* @param insertUri A {@link android.net.Uri} from the {@link ContentProvider} class definition.
* @param model The model to insert.
* @return The Uri of the inserted data.
*/
@SuppressWarnings("unchecked")
public static <TableClass> Uri insert(ContentResolver contentResolver, Uri insertUri, TableClass model) {
ModelAdapter<TableClass> adapter = (ModelAdapter<TableClass>) FlowManager.getModelAdapter(model.getClass());
ContentValues contentValues = new ContentValues();
adapter.bindToInsertValues(contentValues, model);
Uri uri = contentResolver.insert(insertUri, contentValues);
adapter.updateAutoIncrement(model, Long.valueOf(uri.getPathSegments().get(uri.getPathSegments().size() - 1)));
return uri;
}Example 28
| Project: Android-Exif-Extended-master File: IOUtils.java View source code |
public static String getRealFilePath(final Context context, final Uri uri) {
if (null == uri)
return null;
final String scheme = uri.getScheme();
String data = null;
if (scheme == null)
data = uri.getPath();
else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
data = uri.getPath();
} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
Cursor cursor;
try {
cursor = context.getContentResolver().query(uri, new String[] { ImageColumns.DATA }, null, null, null);
} catch (IllegalArgumentException e) {
e.printStackTrace();
return null;
}
if (null != cursor) {
if (cursor.moveToFirst()) {
int index = cursor.getColumnIndex(ImageColumns.DATA);
if (index > -1) {
data = cursor.getString(index);
}
}
cursor.close();
}
}
return data;
}Example 29
| Project: android-imf-ext-master File: BootReceiver.java View source code |
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, com.android.server.LoadAverageService.class);
ContentResolver res = context.getContentResolver();
boolean shown = Settings.System.getInt(res, Settings.System.SHOW_PROCESSES, 0) != 0;
if (shown) {
context.startService(service);
}
}Example 30
| Project: Android-Plugin-Framework-master File: CompatForContentProvider.java View source code |
public static Bundle call(Uri uri, String method, String arg, Bundle extras) {
ContentResolver resolver = FairyGlobal.getApplication().getContentResolver();
if (Build.VERSION.SDK_INT >= 11) {
try {
return resolver.call(uri, method, arg, extras);
} catch (Exception e) {
LogUtil.e("call uri fail", uri, method, arg, extras);
}
return null;
} else {
ContentProviderClient client = resolver.acquireContentProviderClient(uri);
if (client == null) {
throw new IllegalArgumentException("Unknown URI " + uri);
}
try {
HackContentProviderClient hackContentProviderClient = new HackContentProviderClient(client);
Object mContentProvider = hackContentProviderClient.getContentProvider();
if (mContentProvider != null) {
//public Bundle call(String method, String request, Bundle args)
Object result = new HackIContentProvider(mContentProvider).call(method, arg, extras);
return (Bundle) result;
}
} finally {
client.release();
}
return null;
}
}Example 31
| Project: AndroiditoJZ12-master File: JZScheduleApplication.java View source code |
@Override
public void onCreate() {
super.onCreate();
final String ACCOUNT_NAME = "JavaZone Schedule";
final String ACCOUNT_TYPE = "no.java.schedule";
final String PROVIDER = "no.java.schedule";
Account appAccount = new Account(ACCOUNT_NAME, ACCOUNT_TYPE);
AccountManager accountManager = AccountManager.get(getApplicationContext());
if (accountManager.addAccountExplicitly(appAccount, null, null)) {
ContentResolver.setIsSyncable(appAccount, PROVIDER, 1);
ContentResolver.setSyncAutomatically(appAccount, PROVIDER, true);
}
}Example 32
| Project: AndroidNetworkBench-master File: ContentUrlDownloader.java View source code |
@Override
protected Void doInBackground(final Void... params) {
try {
final ContentResolver cr = context.getContentResolver();
InputStream is = cr.openInputStream(Uri.parse(url));
callback.onDownloadComplete(ContentUrlDownloader.this, is, null);
return null;
} catch (final Throwable e) {
e.printStackTrace();
return null;
}
}Example 33
| Project: android_frameworks_base-master File: TestContext.java View source code |
/**
* Returns a Context configured with test provider for authority.
*/
static Context createStorageTestContext(Context context, String authority) {
final MockContentResolver testResolver = new MockContentResolver();
TestContentProvider provider = new TestContentProvider();
testResolver.addProvider(authority, provider);
return new ContextWrapper(context) {
@Override
public ContentResolver getContentResolver() {
return testResolver;
}
};
}Example 34
| Project: AnyMemo-master File: DatabasesProviderTest.java View source code |
@SmallTest
@Test
public void testReturnSampleDb() {
ContentResolver cr = getContext().getContentResolver();
Cursor cursor = cr.query(Uri.parse("content://" + AUTHORITY), null, null, null, null);
assertTrue(cursor.getCount() >= 1);
boolean hasSampleDb = false;
cursor.moveToFirst();
do {
String dbName = cursor.getString(cursor.getColumnIndex("dbname"));
if (dbName.equals(TestHelper.SAMPLE_DB_NAME)) {
hasSampleDb = true;
}
} while (cursor.moveToNext());
cursor.close();
assertTrue(hasSampleDb);
}Example 35
| Project: asm-android-client-for-newsmth-master File: ContentUrlDownloader.java View source code |
@Override
protected Void doInBackground(final Void... params) {
try {
final ContentResolver cr = context.getContentResolver();
InputStream is = cr.openInputStream(Uri.parse(url));
callback.onDownloadComplete(ContentUrlDownloader.this, is, null);
return null;
} catch (final Throwable e) {
e.printStackTrace();
return null;
}
}Example 36
| Project: boardgamegeek4android-master File: SearchRefreshProvider.java View source code |
@Override
protected Cursor query(ContentResolver resolver, SQLiteDatabase db, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
String shortcutId = null;
if (uri.getPathSegments().size() > 1) {
shortcutId = uri.getLastPathSegment();
}
if (TextUtils.isEmpty(shortcutId)) {
return null;
} else {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(Tables.GAMES);
qb.setProjectionMap(SearchSuggestProvider.sSuggestionProjectionMap);
qb.appendWhere(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID + "=" + shortcutId);
Cursor cursor = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(resolver, uri);
return cursor;
}
}Example 37
| Project: bostonbusmap-master File: TransitContentProvider.java View source code |
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
int code = matcher.match(uri);
switch(code) {
case SUGGESTIONS_CODE:
if (selectionArgs == null || selectionArgs.length == 0 || selectionArgs[0].trim().length() == 0) {
return super.query(uri, projection, selection, selectionArgs, sortOrder);
} else {
ContentResolver resolver = getContext().getContentResolver();
return DatabaseAgent.getCursorForSearch(resolver, selectionArgs[0]);
}
default:
return super.query(uri, projection, selection, selectionArgs, sortOrder);
}
}Example 38
| Project: buddydroid-master File: ContentUrlDownloader.java View source code |
@Override
protected Void doInBackground(final Void... params) {
try {
final ContentResolver cr = context.getContentResolver();
InputStream is = cr.openInputStream(Uri.parse(url));
callback.onDownloadComplete(ContentUrlDownloader.this, is, null);
return null;
} catch (final Throwable e) {
e.printStackTrace();
return null;
}
}Example 39
| Project: Courier.Android-master File: Contact.java View source code |
public Bitmap getImage(Context mContext) {
Bitmap contactPhoto = null;
ContentResolver resolver = mContext.getContentResolver();
if (mPersonId > 0) {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, mPersonId);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);
contactPhoto = BitmapFactory.decodeStream(input);
}
if (contactPhoto == null) {
contactPhoto = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.default_contact_photo);
}
return Utils.getRoundedCornerBitmap(contactPhoto);
}Example 40
| Project: Gitskarios-master File: UriUtils.java View source code |
/**
* Get a file path from a Uri.
*
* @see <a href="http://stackoverflow.com/questions/19834842/android-gallery-on-kitkat-returns-different-uri-for-intent-action-get-content">stackoverflow.com</a>
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getPath(Context context, Uri uri) throws NullPointerException {
UriType uriType = new DefaultUriType();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {
uriType = new KitKatDocumentUri();
} else if (ContentResolver.SCHEME_CONTENT.equalsIgnoreCase(uri.getScheme())) {
uriType = new ContentUriType();
} else if (ContentResolver.SCHEME_FILE.equalsIgnoreCase(uri.getScheme())) {
uriType = new FileUriType();
}
return uriType.getPath(context, uri);
}Example 41
| Project: holoreader-master File: MarkReadRunnable.java View source code |
public void run() {
ContentResolver contentResolver = mContext.getContentResolver();
ContentValues contentValues = new ContentValues();
String selection = ArticleDAO.READ + " IS NULL";
String[] selectionArgs = null;
Uri uri;
if (mArticleID != -1) {
uri = Uri.withAppendedPath(RSSContentProvider.URI_ARTICLES, String.valueOf(mArticleID));
} else {
uri = RSSContentProvider.URI_ARTICLES;
if (mFeedID != -1) {
selection = selection + " AND " + ArticleDAO.FEEDID + " = ? ";
selectionArgs = new String[] { String.valueOf(mFeedID) };
}
}
contentValues.put(ArticleDAO.READ, SQLiteHelper.fromDate(new Date()));
contentResolver.update(uri, contentValues, selection, selectionArgs);
}Example 42
| Project: hplookball-master File: ContentUrlDownloader.java View source code |
@Override
protected Void doInBackground(final Void... params) {
try {
final ContentResolver cr = context.getContentResolver();
InputStream is = cr.openInputStream(Uri.parse(url));
callback.onDownloadComplete(ContentUrlDownloader.this, is, null);
return null;
} catch (final Throwable e) {
e.printStackTrace();
return null;
}
}Example 43
| Project: iNaturalistAndroid-master File: ContentUrlDownloader.java View source code |
@Override
protected Void doInBackground(final Void... params) {
try {
final ContentResolver cr = context.getContentResolver();
InputStream is = cr.openInputStream(Uri.parse(url));
callback.onDownloadComplete(ContentUrlDownloader.this, is, null);
return null;
} catch (final Throwable e) {
e.printStackTrace();
return null;
}
}Example 44
| Project: k9mail-master File: AutoSyncSdk4.java View source code |
public void initialize(Context context) throws NoSuchMethodException {
/*
* There's no documented/official way to query the state of the
* auto-sync setting for a normal application in SDK 1.6/API 4.
*
* We use reflection to get an ContentService object, so we can call its
* getListenForNetworkTickles() method. This will return the current
* auto-sync state.
*/
try {
Method getContentService = ContentResolver.class.getMethod("getContentService");
mContentService = getContentService.invoke(null);
mGetListenForNetworkTickles = mContentService.getClass().getMethod("getListenForNetworkTickles");
} catch (Exception e) {
throw new NoSuchMethodException();
}
}Example 45
| Project: lastfm-android-master File: SyncPrompt.java View source code |
public void onClick(View v) {
AccountManager am = AccountManager.get(SyncPrompt.this);
Account[] accounts = am.getAccountsByType(getString(R.string.ACCOUNT_TYPE));
ContentResolver.setIsSyncable(accounts[0], ContactsContract.AUTHORITY, 1);
ContentResolver.setSyncAutomatically(accounts[0], ContactsContract.AUTHORITY, true);
finish();
}Example 46
| Project: libCalendar-master File: CalendarUtility.java View source code |
public static Calendar[] getGoogleCalendars(Context context, String account) {
Cursor cur = null;
ContentResolver cr = context.getContentResolver();
Uri uri = Calendars.CONTENT_URI;
String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND (" + Calendars.ACCOUNT_TYPE + " = ?))";
String[] selectionArgs = new String[] { account, GOOGLE_TYPE };
// Submit the query and get a Cursor object back.
cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, null);
ArrayList<Calendar> calendarList = new ArrayList<Calendar>();
// Use the cursor to step through the returned records
while (cur.moveToNext()) {
Calendar cal = new Calendar(cur);
calendarList.add(cal);
}
cur.close();
Calendar[] calendarArray = new Calendar[calendarList.size()];
return calendarList.toArray(calendarArray);
}Example 47
| Project: LyricHere-master File: BitmapHelper.java View source code |
public static Bitmap fetchAndRescaleBitmap(String uri, int width, int height) throws IOException {
ContentResolver res = LHApplication.getContext().getContentResolver();
InputStream in = res.openInputStream(Uri.parse(uri));
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
int actualW = bmOptions.outWidth;
int actualH = bmOptions.outHeight;
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = Math.min(actualW / width, actualH / height);
return BitmapFactory.decodeStream(in, null, bmOptions);
}Example 48
| Project: mandarin-android-master File: BuddyRemoveTask.java View source code |
@Override
public void executeBackground() throws Throwable {
Context context = getWeakObject();
if (context != null) {
ContentResolver contentResolver = context.getContentResolver();
for (int buddyDbId : buddyDbIds) {
BuddyCursor buddyCursor = null;
try {
buddyCursor = QueryHelper.getBuddyCursor(contentResolver, buddyDbId);
int accountDbId = buddyCursor.getBuddyAccountDbId();
String groupName = buddyCursor.getBuddyGroup();
String buddyId = buddyCursor.getBuddyId();
// Mark as removing.
QueryHelper.modifyOperation(contentResolver, buddyDbId, GlobalProvider.ROSTER_BUDDY_OPERATION_REMOVE);
// Remove request.
RequestHelper.requestRemove(contentResolver, accountDbId, groupName, buddyId);
} catch (BuddyNotFoundException ignored) {
} finally {
if (buddyCursor != null) {
buddyCursor.close();
}
}
}
}
}Example 49
| Project: meetup-client-master File: GoogleLocationSettingHelper.java View source code |
public static int getUseLocationForServices(Context context) {
Cursor cursor = null;
ContentResolver contentresolver = context.getContentResolver();
String s1;
try {
cursor = contentresolver.query(GOOGLE_SETTINGS_CONTENT_URI, new String[] { "value" }, "name=?", new String[] { "use_location_for_services" }, null);
String s = null;
if (null == cursor) {
// FIXME
return 2;
}
if (!cursor.moveToNext()) {
// FIXME
return 2;
}
return Integer.parseInt(cursor.getString(0));
} catch (Throwable t) {
Log.w("GoogleLocationSettingHelper", "Failed to get 'Use My Location' setting", t);
} finally {
if (null != cursor) {
cursor.close();
}
}
return 2;
}Example 50
| Project: MensaUPB-master File: MensaUpbApplication.java View source code |
private void setupSynchronization() {
if (BuildConfig.DEBUG)
LOGGER.debug("setupSynchronization()");
ContentResolver.addPeriodicSync(mAccountCreator.getAccount(), mAccountCreator.getAuthority(), new Bundle(), BuildConfig.SYNC_INTERVAL);
forceFirstSync();
if (BuildConfig.DEBUG)
LOGGER.debug("setupSynchronization() done");
}Example 51
| Project: mickeydb-master File: BulkInsertHelper.java View source code |
public int insert(ContentResolver resolver, Uri contentUri, List<T> items) {
if (items == null || items.size() == 0) {
return 0;
}
ContentValues[] values = new ContentValues[items.size()];
for (int i = 0; i < values.length; i++) {
T item = items.get(i);
values[i] = createValues(item);
}
return resolver.bulkInsert(contentUri, values);
}Example 52
| Project: MusicDNA-master File: MediaCacheUtils.java View source code |
public static void updateMediaCache(String title, String artist, String album, long id, Context ctx) {
ContentResolver musicResolver = ctx.getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
ContentValues newValues = new ContentValues();
newValues.put(android.provider.MediaStore.Audio.Media.TITLE, title);
newValues.put(android.provider.MediaStore.Audio.Media.ARTIST, artist);
newValues.put(android.provider.MediaStore.Audio.Media.ALBUM, album);
int res = musicResolver.update(musicUri, newValues, android.provider.MediaStore.Audio.Media._ID + "=?", new String[] { String.valueOf(id) });
if (res > 0) {
// Toast.makeText(this, "Updated MediaStore cache", Toast.LENGTH_SHORT).show();
}
}Example 53
| Project: ohmagePhone-master File: MockContentProviderContext.java View source code |
@Override
public ContentResolver getContentResolver() {
if (mResolver == null) {
mResolver = new MockContentResolver();
mResolver.addProvider(DbContract.CONTENT_AUTHORITY, new MockContentProvider(mContext) {
@Override
public int update(Uri uri, ContentValues values, String where, String[] selectionArgs) {
return MockContentProviderContext.this.update(uri, values, where, selectionArgs);
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return MockContentProviderContext.this.query(uri, projection, selection, selectionArgs, sortOrder);
}
});
}
return mResolver;
}Example 54
| Project: OpenHAB_Room_Flipper-master File: ImagePicker.java View source code |
public String getImagePath(int resultCode, Intent data, ContentResolver contentResolver) {
if (resultCode == Activity.RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = contentResolver.query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
return picturePath;
} else {
return new String();
}
}Example 55
| Project: Permission-Nanny-master File: ContentEvent.java View source code |
@Override
public void process(Context context, Intent intent) {
switch(mRequest.opCode) {
case ContentRequest.SELECT:
Uri authorized = null;
if (Nanny.SC_OK == intent.getIntExtra(Nanny.STATUS_CODE, 0)) {
long uriPath = intent.getBundleExtra(Nanny.ENTITY_BODY).getLong(mRequest.opCode, 0);
authorized = Nanny.getProxyContentProvider().buildUpon().appendPath(Long.toString(uriPath)).build();
}
ContentResolver cr = context.getContentResolver();
Cursor data = authorized == null ? null : cr.query(authorized, null, null, null, null);
mListener.onResponse(intent.getExtras(), data);
break;
default:
mListener.onResponse(intent.getExtras(), null);
}
}Example 56
| Project: physical-web-master File: WifiDirectHelloWorld.java View source code |
@Override
public void startDemo() {
Intent intent = new Intent(mContext, FileBroadcastService.class);
String uriString = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + mContext.getPackageName() + "/" + R.raw.wifi_direct_default_webpage;
intent.putExtra(FileBroadcastService.FILE_KEY, uriString);
intent.putExtra(FileBroadcastService.MIME_TYPE_KEY, "text/html");
intent.putExtra(FileBroadcastService.TITLE_KEY, "Hello World");
mContext.startService(intent);
mIsDemoStarted = true;
}Example 57
| Project: platform_frameworks_base-master File: TestContext.java View source code |
/**
* Returns a Context configured with test provider for authority.
*/
static Context createStorageTestContext(Context context, String authority) {
final MockContentResolver testResolver = new MockContentResolver();
TestContentProvider provider = new TestContentProvider();
testResolver.addProvider(authority, provider);
return new ContextWrapper(context) {
@Override
public ContentResolver getContentResolver() {
return testResolver;
}
};
}Example 58
| Project: pps_android-master File: URLService.java View source code |
public //»ñȡϵͳä¯ÀÀÆ÷µÄURL
ArrayList<URLInfo> getSystemBrowserUrl(//»ñȡϵͳä¯ÀÀÆ÷µÄURL
Context context, //»ñȡϵͳä¯ÀÀÆ÷µÄURL
long timestamp) {
ContentResolver resolver = context.getContentResolver();
ArrayList<URLInfo> list = new ArrayList<URLInfo>();
URLInfo urlinfo = null;
Cursor cursor = null;
try {
//cursor = Browser.getAllVisitedUrls(resolver);
cursor = resolver.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, BookmarkColumns.DATE + " > " + timestamp, null, "date DESC");
if (cursor == null) {
return null;
} else {
while (cursor.moveToNext()) {
urlinfo = new URLInfo();
String myUrl = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.URL));
long date = cursor.getLong(cursor.getColumnIndex(BookmarkColumns.DATE));
urlinfo.setUrl(myUrl);
urlinfo.setKeywords(Utils.getSearchWord(myUrl));
urlinfo.setTimestamp(date);
list.add(urlinfo);
// Log.i("billsong", urlinfo.getUrl()
// +urlinfo.getKeywords()
// +urlinfo.getTimestamp());
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
return list;
}Example 59
| Project: qaoverflow-master File: ContentUrlDownloader.java View source code |
@Override
protected Void doInBackground(final Void... params) {
try {
final ContentResolver cr = context.getContentResolver();
InputStream is = cr.openInputStream(Uri.parse(url));
callback.onDownloadComplete(ContentUrlDownloader.this, is, null);
return null;
} catch (final Throwable e) {
e.printStackTrace();
return null;
}
}Example 60
| Project: sandro-master File: MiuiSpecialUtil.java View source code |
/**
* 判æ–当å‰?å?–得当å‰?ç”µæ± çŠ¶æ€?是å?¦æ˜¯å…³é—çš„
* @param paramContentResolver
* @return
*/
public static boolean monitorHistoryIsClosed(ContentResolver paramContentResolver) {
try {
int monitorHistory = Settings.System.getInt(paramContentResolver, "monitor_history");
if (monitorHistory == 1) {
return true;
} else {
return false;
}
} catch (Settings.SettingNotFoundException localSettingNotFoundException) {
return false;
}
}Example 61
| Project: selfoss-android-master File: SyncManager.java View source code |
public void requestSync() {
Account account = configManager.getAccount();
if (account != null) {
Bundle extras = new Bundle();
extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
ContentResolver.requestSync(account, AUTHORITY, extras);
}
}Example 62
| Project: Signal-Android-master File: DecryptableStreamLocalUriFetcher.java View source code |
@Override
protected InputStream loadResource(Uri uri, ContentResolver contentResolver) throws FileNotFoundException {
if (MediaUtil.hasVideoThumbnail(uri)) {
Bitmap thumbnail = MediaUtil.getVideoThumbnail(context, uri);
if (thumbnail != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, baos);
return new ByteArrayInputStream(baos.toByteArray());
}
}
try {
return PartAuthority.getAttachmentStream(context, masterSecret, uri);
} catch (IOException ioe) {
Log.w(TAG, ioe);
throw new FileNotFoundException("PartAuthority couldn't load Uri resource.");
}
}Example 63
| Project: SmartReceiptsLibrary-master File: UriUtils.java View source code |
@Nullable public static String getExtension(@NonNull Uri uri, @NonNull ContentResolver contentResolver) { if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) { // scheme is content:// return MimeTypeMap.getSingleton().getExtensionFromMimeType(contentResolver.getType(uri)); } else { // scheme is file:// return MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString()); } }
Example 64
| Project: Telecine-master File: DeleteRecordingBroadcastReceiver.java View source code |
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(RecordingSession.NOTIFICATION_ID);
final Uri uri = intent.getData();
final ContentResolver contentResolver = context.getContentResolver();
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(@NonNull Void... none) {
int rowsDeleted = contentResolver.delete(uri, null, null);
if (rowsDeleted == 1) {
Timber.i("Deleted recording.");
} else {
Timber.e("Error deleting recording.");
}
return null;
}
}.execute();
}Example 65
| Project: TimberLorry-master File: AbstractBufferResolver.java View source code |
@Override
public void scheduleSync(long period) {
// TODO: consider the condition that master sync is disabled.
if (!Utils.isAccountAdded(accountManager, account.type)) {
accountManager.addAccountExplicitly(account, null, null);
}
ContentResolver.setSyncAutomatically(account, BufferProvider.AUTHORITY, true);
ContentResolver.addPeriodicSync(account, BufferProvider.AUTHORITY, Bundle.EMPTY, period);
}Example 66
| Project: Traktoid-master File: SyncAdapter.java View source code |
public static void requestImmediateSync() {
Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
Account account = new Account(ACCOUNT_NAME, BuildConfig.APPLICATION_ID);
ContentResolver.requestSync(account, TraktoidProvider.AUTHORITY, bundle);
}Example 67
| Project: TweetLanes-master File: ContentUrlDownloader.java View source code |
@Override
protected Void doInBackground(final Void... params) {
try {
final ContentResolver cr = context.getContentResolver();
InputStream is = cr.openInputStream(Uri.parse(url));
callback.onDownloadComplete(ContentUrlDownloader.this, is, null);
return null;
} catch (final Throwable e) {
e.printStackTrace();
return null;
}
}Example 68
| Project: TwsPluginFramework-master File: ContentProviderCompat.java View source code |
public static Bundle call(Uri uri, String method, String arg, Bundle extras) {
ContentResolver resolver = ServiceManager.sApplication.getContentResolver();
if (Build.VERSION.SDK_INT >= 11) {
return resolver.call(uri, method, arg, extras);
} else {
ContentProviderClient client = resolver.acquireContentProviderClient(uri);
if (client == null) {
throw new IllegalArgumentException("Unknown URI " + uri);
}
try {
Object mContentProvider = RefIectUtil.getFieldObject(client, ContentProviderClient.class, "mContentProvider");
if (mContentProvider != null) {
//public Bundle call(String method, String request, Bundle args)
Object result = null;
try {
result = RefIectUtil.invokeMethod(mContentProvider, Class.forName("android.content.IContentProvider"), "call", new Class[] { String.class, String.class, Bundle.class }, new Object[] { method, arg, extras });
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return (Bundle) result;
}
} finally {
client.release();
}
return null;
}
}Example 69
| Project: UrlImageViewHelper-master File: ContentUrlDownloader.java View source code |
@Override
protected Void doInBackground(final Void... params) {
try {
final ContentResolver cr = context.getContentResolver();
InputStream is = cr.openInputStream(Uri.parse(url));
callback.onDownloadComplete(ContentUrlDownloader.this, is, null);
return null;
} catch (final Throwable e) {
e.printStackTrace();
return null;
}
}Example 70
| Project: WS171-frameworks-base-master File: BootReceiver.java View source code |
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, com.android.server.LoadAverageService.class);
ContentResolver res = context.getContentResolver();
boolean shown = Settings.System.getInt(res, Settings.System.SHOW_PROCESSES, 0) != 0;
if (shown) {
context.startService(service);
}
}Example 71
| Project: zhong-master File: Const.java View source code |
public static final boolean moveItem(ContentResolver res, long playlistId, int from, int to) {
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId).buildUpon().appendEncodedPath(String.valueOf(from)).appendQueryParameter("move", "true").build();
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, to);
return res.update(uri, values, null, null) != 0;
}Example 72
| Project: ZjDroid-master File: ContentResolverHook.java View source code |
@Override
public void startHook() {
Method querymethod = RefInvoke.findMethodExact("android.content.ContentResolver", ClassLoader.getSystemClassLoader(), "query", Uri.class, String[].class, String.class, String[].class, String.class);
hookhelper.hookMethod(querymethod, new AbstractBahaviorHookCallBack() {
@Override
public void descParam(HookParam param) {
// TODO Auto-generated method stub
Uri uri = (Uri) param.args[0];
if (isSensitiveUri(uri)) {
Logger.log_behavior("Read ContentProvider -> Uri = " + uri.toString());
String queryStr = concatenateQuery(uri, (String[]) param.args[1], (String) param.args[2], (String[]) param.args[3], (String) param.args[4]);
Logger.log_behavior("Query SQL = " + queryStr);
}
}
});
Method registerContentObservermethod = RefInvoke.findMethodExact("android.content.ContentResolver", ClassLoader.getSystemClassLoader(), "registerContentObserver", Uri.class, boolean.class, ContentObserver.class, int.class);
hookhelper.hookMethod(registerContentObservermethod, new AbstractBahaviorHookCallBack() {
@Override
public void descParam(HookParam param) {
// TODO Auto-generated method stub
Uri uri = (Uri) param.args[0];
if (isSensitiveUri(uri)) {
Logger.log_behavior("Register ContentProvider Change -> Uri = " + uri.toString());
Logger.log_behavior("ContentObserver ClassName =" + param.args[1].getClass().toString());
}
}
});
Method insertmethod = RefInvoke.findMethodExact("android.content.ContentResolver", ClassLoader.getSystemClassLoader(), "insert", Uri.class, ContentValues.class);
hookhelper.hookMethod(insertmethod, new AbstractBahaviorHookCallBack() {
@Override
public void descParam(HookParam param) {
// TODO Auto-generated method stub
Uri uri = (Uri) param.args[0];
if (isSensitiveUri(uri)) {
Logger.log_behavior("Insert ContentProvider -> Uri = " + uri.toString());
ContentValues cv = (ContentValues) param.args[1];
String insertStr = concatenateInsert(uri, cv);
Logger.log_behavior("Insert SQL = " + insertStr);
}
}
});
Method bulkInsertmethod = RefInvoke.findMethodExact("android.content.ContentResolver", ClassLoader.getSystemClassLoader(), "bulkInsert", Uri.class, ContentValues[].class);
hookhelper.hookMethod(bulkInsertmethod, new AbstractBahaviorHookCallBack() {
@Override
public void descParam(HookParam param) {
// TODO Auto-generated method stub
Uri uri = (Uri) param.args[0];
if (isSensitiveUri(uri)) {
ContentValues[] cv = (ContentValues[]) param.args[1];
Logger.log_behavior("Bulk Insert ContentProvider -> Uri = " + uri.toString());
String insertStr = null;
for (int i = 0; i < cv.length; i++) {
insertStr = concatenateInsert(uri, cv[i]);
Logger.log_behavior("Insert " + i + " SQL = " + insertStr);
}
}
}
});
Method deletemethod = RefInvoke.findMethodExact("android.content.ContentResolver", ClassLoader.getSystemClassLoader(), "delete", Uri.class, String.class, String[].class);
hookhelper.hookMethod(deletemethod, new AbstractBahaviorHookCallBack() {
@Override
public void descParam(HookParam param) {
// TODO Auto-generated method stub
Uri uri = (Uri) param.args[0];
if (isSensitiveUri(uri)) {
Logger.log_behavior("Delete ContentProvider -> uri= " + uri.toString());
String deleteStr = concatenateDelete(uri, (String) param.args[1], (String[]) param.args[2]);
Logger.log_behavior("Delete SQL = " + deleteStr);
}
}
});
Method updatemethod = RefInvoke.findMethodExact("android.content.ContentResolver", ClassLoader.getSystemClassLoader(), "update", Uri.class, ContentValues.class, String.class, String[].class);
hookhelper.hookMethod(updatemethod, new AbstractBahaviorHookCallBack() {
@Override
public void descParam(HookParam param) {
// TODO Auto-generated method stub
Uri uri = (Uri) param.args[0];
if (isSensitiveUri(uri)) {
Logger.log_behavior("Update ContentProvider -> uri=" + uri.toString());
String updateStr = concatenateUpdate(uri, (ContentValues) param.args[1], (String) param.args[2], (String[]) param.args[3]);
Logger.log_behavior("Update SQL = " + updateStr);
}
}
});
Method applyBatchMethod = RefInvoke.findMethodExact("android.content.ContentResolver", ClassLoader.getSystemClassLoader(), "applyBatch", String.class, ArrayList.class);
hookhelper.hookMethod(applyBatchMethod, new AbstractBahaviorHookCallBack() {
@Override
public void descParam(HookParam param) {
// TODO Auto-generated method stub
ArrayList<ContentProviderOperation> opts = (ArrayList<ContentProviderOperation>) param.args[1];
for (int i = 0; i < opts.size(); i++) {
Logger.log_behavior("Batch SQL = " + descContentProviderOperation(opts.get(i)));
}
}
});
}Example 73
| Project: hk-master File: ContentsDataHooker.java View source code |
/** * Hook calls to specific methods of the ContentResolver class */ private void attachOnContentResolverClass() { Map<String, Integer> methodsFromLocationToHook = new HashMap<String, Integer>(); methodsFromLocationToHook.put("acquireContentProviderClient", 0); methodsFromLocationToHook.put("acquireUnstableContentProviderClient", 0); methodsFromLocationToHook.put("addPeriodicSync", 0); methodsFromLocationToHook.put("applyBatch", 2); methodsFromLocationToHook.put("call", 1); methodsFromLocationToHook.put("delete", 2); methodsFromLocationToHook.put("getStreamTypes", 0); methodsFromLocationToHook.put("getType", 0); methodsFromLocationToHook.put("insert", 2); methodsFromLocationToHook.put("notifyChange", 1); methodsFromLocationToHook.put("openAssetFileDescriptor", 1); methodsFromLocationToHook.put("openFileDescriptor", 1); methodsFromLocationToHook.put("openInputStream", 1); methodsFromLocationToHook.put("openOutputStream", 2); methodsFromLocationToHook.put("openTypedAssetFileDescriptor", 1); methodsFromLocationToHook.put("query", 1); methodsFromLocationToHook.put("registerContentObserver", 2); methodsFromLocationToHook.put("requestSync", 0); methodsFromLocationToHook.put("unregisterContentObserver", 2); methodsFromLocationToHook.put("update", 2); try { hookMethods(null, "android.content.ContentResolver", methodsFromLocationToHook); SubstrateMain.log("hooking android.content.ContentResolver methods sucessful"); } catch (HookerInitializationException e) { SubstrateMain.log("hooking android.content.ContentResolver methods has failed", e); } }
Example 74
| Project: AOS2012-Android-master File: JsonHandler.java View source code |
/**
* Parse the given {@link org.json}, turning into a series of
* {@link android.content.ContentProviderOperation} that are immediately applied using the
* given {@link android.content.ContentResolver}.
*
* @param jsonString
* @param resolver
* @throws HandlerException
*/
public void parseAndApply(String jsonString, ContentResolver resolver) throws HandlerException {
try {
final ArrayList<ContentProviderOperation> batch = parse(jsonString, resolver);
resolver.applyBatch(mAuthority, batch);
} catch (HandlerException e) {
throw e;
} catch (JSONException e) {
e.printStackTrace();
throw new HandlerException("Problem parsing JSON response", e);
} catch (IOException e) {
throw new HandlerException("Problem reading response", e);
} catch (RemoteException e) {
throw new RuntimeException("Problem applying batch operation", e);
} catch (OperationApplicationException e) {
throw new RuntimeException("Problem applying batch operation", e);
}
}Example 75
| Project: OpenCamera_android2.3-master File: BitmapManager.java View source code |
/**
* Gets the thumbnail of the given ID of the original image.
*
* <p> This method wraps around @{code getThumbnail} in {@code
* android.provider.MediaStore}. It provides the ability to cancel it.
*/
public Bitmap getThumbnail(ContentResolver cr, long origId, int kind, BitmapFactory.Options options, boolean isVideo) {
Thread t = Thread.currentThread();
ThreadStatus status = getOrCreateThreadStatus(t);
if (!canThreadDecoding(t)) {
Log.d(TAG, "Thread " + t + " is not allowed to decode.");
return null;
}
try {
if (isVideo) {
return Video.Thumbnails.getThumbnail(cr, origId, t.getId(), kind, null);
} else {
return Images.Thumbnails.getThumbnail(cr, origId, t.getId(), kind, null);
}
} finally {
synchronized (status) {
status.notifyAll();
}
}
}Example 76
| Project: picasso-master File: ContactsPhotoRequestHandler.java View source code |
private InputStream getInputStream(Request data) throws IOException {
ContentResolver contentResolver = context.getContentResolver();
Uri uri = data.uri;
switch(matcher.match(uri)) {
case ID_LOOKUP:
uri = ContactsContract.Contacts.lookupContact(contentResolver, uri);
if (uri == null) {
return null;
}
// Resolved the uri to a contact uri, intentionally fall through to process the resolved uri
case ID_CONTACT:
return openContactPhotoInputStream(contentResolver, uri, true);
case ID_THUMBNAIL:
case ID_DISPLAY_PHOTO:
return contentResolver.openInputStream(uri);
default:
throw new IllegalStateException("Invalid uri: " + uri);
}
}Example 77
| Project: reyna-master File: ShadowAndroidHttpClient.java View source code |
@Implementation
public static AbstractHttpEntity getCompressedEntity(byte[] data, android.content.ContentResolver resolver) throws java.io.IOException {
AbstractHttpEntity entity;
if (data.length < getMinGzipSize(resolver)) {
entity = new ByteArrayEntity(data);
} else {
ByteArrayOutputStream arr = new ByteArrayOutputStream();
OutputStream zipper = new GZIPOutputStream(arr);
zipper.write(data);
zipper.close();
entity = new ByteArrayEntity(arr.toByteArray());
entity.setContentEncoding("gzip");
}
return entity;
}Example 78
| Project: weiciyuan-master File: GifImageView.java View source code |
/**
* Sets the content of this GifImageView to the specified Uri.
* If uri destination is not a GIF then {@link android.widget.ImageView#setImageURI(android.net.Uri)}
* is called as fallback.
* For supported URI schemes see: {@link android.content.ContentResolver#openAssetFileDescriptor(android.net.Uri,
* String)}.
* <code>file</code> scheme is always supported.
*
* @param uri The Uri of an image
*/
@Override
public void setImageURI(Uri uri) {
GifDrawable gd = null;
if (uri != null) {
final String scheme = uri.getScheme();
try {
if (ContentResolver.SCHEME_FILE.equals(scheme)) {
gd = new GifDrawable(uri.getPath());
} else {
AssetFileDescriptor afd = getContext().getContentResolver().openAssetFileDescriptor(uri, "r");
if (afd != null) {
try {
gd = new GifDrawable(afd);
} catch (IOException ex) {
afd.close();
}
}
}
} catch (IOException ex) {
}
}
if (gd != null) {
setImageDrawable(gd);
} else {
super.setImageURI(uri);
}
}Example 79
| Project: ACEMusicPlayer-master File: ContentStreamBitmapHunter.java View source code |
protected Bitmap decodeContentStream(Request data) throws IOException {
ContentResolver contentResolver = context.getContentResolver();
final BitmapFactory.Options options = createBitmapOptions(data);
if (requiresInSampleSize(options)) {
InputStream is = null;
try {
is = contentResolver.openInputStream(data.uri);
BitmapFactory.decodeStream(is, null, options);
} finally {
Utils.closeQuietly(is);
}
calculateInSampleSize(data.targetWidth, data.targetHeight, options);
}
InputStream is = contentResolver.openInputStream(data.uri);
try {
return BitmapFactory.decodeStream(is, null, options);
} finally {
Utils.closeQuietly(is);
}
}Example 80
| Project: actor-platform-master File: SamsungHomeBadger.java View source code |
@Override
protected void executeBadge(int badgeCount) throws ShortcutBadgeException {
Uri mUri = Uri.parse(CONTENT_URI);
ContentResolver contentResolver = mContext.getContentResolver();
Cursor cursor = null;
try {
cursor = contentResolver.query(mUri, CONTENT_PROJECTION, "package=?", new String[] { getContextPackageName() }, null);
if (cursor != null) {
String entryActivityName = getEntryActivityName();
boolean entryActivityExist = false;
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
ContentValues contentValues = getContentValues(badgeCount, false);
contentResolver.update(mUri, contentValues, "_id=?", new String[] { String.valueOf(id) });
if (entryActivityName.equals(cursor.getString(cursor.getColumnIndex("class")))) {
entryActivityExist = true;
}
}
if (!entryActivityExist) {
ContentValues contentValues = getContentValues(badgeCount, true);
contentResolver.insert(mUri, contentValues);
}
}
} finally {
CloseHelper.close(cursor);
}
}Example 81
| Project: AdvancedVideoView-master File: LightnessController.java View source code |
// åˆ¤æ–æ˜¯å?¦å¼€å?¯äº†è‡ªåŠ¨äº®åº¦è°ƒèŠ‚
public static boolean isAutoBrightness(Activity act) {
boolean automicBrightness = false;
ContentResolver aContentResolver = act.getContentResolver();
try {
automicBrightness = Settings.System.getInt(aContentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
} catch (Exception e) {
Toast.makeText(act, "Error auto lightness", Toast.LENGTH_SHORT).show();
}
return automicBrightness;
}Example 82
| Project: allogy-legacy-android-app-master File: ListDb.java View source code |
public void addNewList(ContentResolver cr, ListMessage list_msg) {
ContentValues cv = new ContentValues();
boolean yn = isItemInDB(cr, list_msg.getId());
cv.put(List._ID, list_msg.getId());
cv.put(List.TITLE, list_msg.getTitle());
cv.put(List.TAG, list_msg.getTag());
if (!yn)
cr.insert(List.CONTENT_URI, cv);
else
cr.update(List.CONTENT_URI, cv, List._ID + "='" + list_msg.getId() + "'", null);
}Example 83
| Project: andevcon-2014-jl-master File: AutoComplete5.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.autocomplete_5);
ContentResolver content = getContentResolver();
Cursor cursor = content.query(Contacts.CONTENT_URI, AutoComplete4.CONTACT_PROJECTION, null, null, null);
AutoComplete4.ContactListAdapter adapter = new AutoComplete4.ContactListAdapter(this, cursor);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit);
textView.setAdapter(adapter);
}Example 84
| Project: andlytics-master File: AutosyncHandler.java View source code |
/**
* Gets the sync period in minutes for the given account
* @param accountName
* @return The sync period in minutes
*/
public int getAutosyncPeriod(String accountName) {
int result = 0;
Account account = new Account(accountName, AutosyncHandler.ACCOUNT_TYPE_GOOGLE);
if (ContentResolver.getSyncAutomatically(account, AutosyncHandler.ACCOUNT_AUTHORITY)) {
List<PeriodicSync> periodicSyncs = ContentResolver.getPeriodicSyncs(account, AutosyncHandler.ACCOUNT_AUTHORITY);
for (PeriodicSync periodicSync : periodicSyncs) {
result = 60 * (int) periodicSync.period;
break;
}
}
return result;
}Example 85
| Project: androGister-master File: ProductManager.java View source code |
public static List<Product> getDirtyProducts(Context context, Account account) {
Log.i(TAG, "*** Looking for local dirty contacts");
List<Product> dirtyProducts = new ArrayList<Product>();
// V1 : Product Dao
AndroGisterApplication app = ((AndroGisterApplication) context.getApplicationContext());
ProductDao dao = app.getDaoSession().getProductDao();
// QueryBuilder<Product> query = dao.queryBuilder();
// query.or(Properties.Dirty.eq(true), Properties.Deleted.eq(true));
// LazyList<Product> products = query.listLazy();
// try {
// for (Product product : products) {
//
// }
// } finally {
// products.close();
// }
// V2 : Product ContentResolver
final ContentResolver resolver = context.getContentResolver();
String DirtyQuery_SELECTION = String.format("%s = 1 or %s = 1", Properties.Dirty.columnName, Properties.Deleted.columnName);
final Cursor c = resolver.query(ProductProvider.Constants.CONTENT_URI, dao.getAllColumns(), DirtyQuery_SELECTION, new String[] { "1", "1" }, null);
try {
while (c.moveToNext()) {
Product product = dao.readEntity(c, 0);
if (product.getDeleted()) {
// TODO Operation VO
dirtyProducts.add(product);
} else if (product.getDirty()) {
// TODO Operation VO
dirtyProducts.add(product);
}
}
} finally {
if (c != null) {
c.close();
}
}
return dirtyProducts;
}Example 86
| Project: Android--Event-Triggered-Skype-Caller-master File: AdapterUtils.java View source code |
public List<Pair<String, String>> queryContacts(final ContentResolver cr) {
Logger.i(TAG, "Generating Contact DataList");
final Cursor skypeCursor = cr.query(ContactsContract.Data.CONTENT_URI, null, null, null, ContactsContract.Data.DISPLAY_NAME + " collate localized");
final List<Pair<String, String>> dataList = new ArrayList<Pair<String, String>>();
final Set<String> addedSkypeNames = new HashSet<String>();
while (skypeCursor.moveToNext()) {
final int type = skypeCursor.getInt(skypeCursor.getColumnIndex(ContactsContract.CommonDataKinds.Im.PROTOCOL));
final String contactName = skypeCursor.getString(skypeCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
final String imName = skypeCursor.getString(skypeCursor.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
if (type == ContactsContract.CommonDataKinds.Im.PROTOCOL_SKYPE) {
if (imName != null && imName.trim().length() > 0) {
final String skypeName = imName.trim();
if (!addedSkypeNames.contains(skypeName)) {
dataList.add(new Pair<String, String>(contactName, skypeName));
addedSkypeNames.add(skypeName);
}
}
}
}
skypeCursor.close();
return dataList;
}Example 87
| Project: android-15-master File: BootReceiver.java View source code |
@Override
public void onReceive(final Context context, Intent intent) {
try {
// Start the load average overlay, if activated
ContentResolver res = context.getContentResolver();
if (Settings.System.getInt(res, Settings.System.SHOW_PROCESSES, 0) != 0) {
Intent loadavg = new Intent(context, com.android.systemui.LoadAverageService.class);
context.startService(loadavg);
}
} catch (Exception e) {
Slog.e(TAG, "Can't start load average service", e);
}
}Example 88
| Project: android-apidemos-master File: AutoComplete5.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.autocomplete_5);
ContentResolver content = getContentResolver();
Cursor cursor = content.query(Contacts.CONTENT_URI, AutoComplete4.CONTACT_PROJECTION, null, null, null);
AutoComplete4.ContactListAdapter adapter = new AutoComplete4.ContactListAdapter(this, cursor);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit);
textView.setAdapter(adapter);
}Example 89
| Project: Android-Backup-master File: CalendarAccessor.java View source code |
public static CalendarAccessor instance(ContentResolver resolver) {
final int sdkVersion = Build.VERSION.SDK_INT;
if (sCalendarAccessor == null) {
try {
if (sdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
sCalendarAccessor = new CalendarAccessorPre40(resolver);
} else {
sCalendarAccessor = new CalendarAccessorPost40(resolver);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return sCalendarAccessor;
}Example 90
| Project: android-development-course-master File: SampleTestTarget3.java View source code |
// DB ã?«å•?ã?„å?ˆã‚?ã?›ã?Ÿçµ?果をã€?é?©å®œãƒ‡ãƒ¼ã‚¿æ§‹é€ ã?«å½“ã?¦ã?¯ã‚?ã?¦ã‚ªãƒ–ジェクトを作ã?£ã?¦ã€?リストã?§è¿”ã?™ãƒ¡ã‚½ãƒƒãƒ‰
public List<SampleDBEntity> getAllListFromDB(Context context) {
List<SampleDBEntity> list = new ArrayList<SampleDBEntity>();
ContentResolver resolver = context.getContentResolver();
Cursor c = null;
try {
c = resolver.query(TestTargetContentProvider.CONTENT_URI, new String[] { BaseColumns._ID, "name" }, null, null, null);
// çµ?æžœã?Œã?‚れã?°ã€?ãƒ?インタを先é ã?«ç§»å‹•ã?—ã?¦ã?‹ã‚‰å‡¦ç?†ã‚’å§‹ã‚?ã‚‹
if (c.moveToFirst()) {
do {
// Cursor �らデータを�り出��インスタンスを作��リスト�詰�る�1 回以上�繰り返�
int id = c.getInt(c.getColumnIndex(BaseColumns._ID));
String name = c.getString(c.getColumnIndex("name"));
list.add(new SampleDBEntity(id, name));
} while (c.moveToNext());
}
} finally {
// リソースを閉�る
if (c != null) {
c.close();
}
}
return list;
}Example 91
| Project: android-maven-plugin-master File: AutoComplete5.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.autocomplete_5);
ContentResolver content = getContentResolver();
Cursor cursor = content.query(Contacts.CONTENT_URI, AutoComplete4.CONTACT_PROJECTION, null, null, null);
AutoComplete4.ContactListAdapter adapter = new AutoComplete4.ContactListAdapter(this, cursor);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit);
textView.setAdapter(adapter);
}Example 92
| Project: Android-Media-Library-master File: MediaFactory.java View source code |
public static Media getMediaByUPC(Context mContext, String UPC) throws LookupException {
Media mMedia = null;
ContentResolver cr = mContext.getContentResolver();
// Try to lookup the content with the CR first
Uri myItem = ContentUris.withAppendedId(Media.CONTENT_URI, Long.valueOf(UPC));
Cursor cur = cr.query(myItem, null, null, null, null);
if (cur.getCount() > 0) {
cur.moveToFirst();
mMedia = new Media(cur, cr);
}
cur.close();
if (mMedia != null)
return mMedia;
// Look it up online, then insert it into the CR if we successfully find it
Log.w(TAG, "ContentResolver Miss for UPC: " + UPC);
Log.i(TAG, "Looking up UPC Online...");
String Title = UPCDataSource.getUPCText(UPC).trim();
Log.i(TAG, "UPC Lookup Result: " + Title);
if (Title == "")
throw new LookupException("Could not find Title Anywhere!");
ContentValues mVals = new ContentValues();
mVals.put(Media.TITLE, Title);
mVals.put(Media.BARCODE, UPC);
mVals.put(Media.OWNED, 0);
mVals.put(Media.LOANED, "");
cr.insert(Media.CONTENT_URI, mVals);
// Ok, Mobile platforms probably don't like recursion, but this really is the most graceful way to handle things...
return MediaFactory.getMediaByUPC(mContext, UPC);
}Example 93
| Project: android-mileage-master File: ServiceIntervalTemplateListActivity.java View source code |
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.empty_add_interval_template:
startActivity(new Intent(ServiceIntervalTemplateListActivity.this, ServiceIntervalTemplateActivity.class));
break;
case R.id.empty_add_default_templates:
final ContentResolver resolver = getContentResolver();
new Thread() {
@Override
public void run() {
resolver.bulkInsert(ServiceIntervalTemplatesTable.BASE_URI, ServiceIntervalTemplatesTable.TEMPLATES);
}
}.start();
break;
}
}Example 94
| Project: android-mms-mod-master File: DrmUtils.java View source code |
public static Uri insert(Context context, DrmWrapper drmObj) throws IOException {
ContentResolver cr = context.getContentResolver();
Uri uri = SqliteWrapper.insert(context, cr, DRM_TEMP_URI, new ContentValues(0));
OutputStream os = null;
try {
os = cr.openOutputStream(uri);
byte[] data = drmObj.getDecryptedData();
if (data != null) {
os.write(data);
}
return uri;
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
}
}Example 95
| Project: Android-SDK-Samples-master File: AutoComplete5.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.autocomplete_5);
ContentResolver content = getContentResolver();
Cursor cursor = content.query(Contacts.CONTENT_URI, AutoComplete4.CONTACT_PROJECTION, null, null, null);
AutoComplete4.ContactListAdapter adapter = new AutoComplete4.ContactListAdapter(this, cursor);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit);
textView.setAdapter(adapter);
}Example 96
| Project: android-sdk-sources-for-api-level-23-master File: BootReceiver.java View source code |
@Override
public void onReceive(final Context context, Intent intent) {
try {
// Start the load average overlay, if activated
ContentResolver res = context.getContentResolver();
if (Settings.Global.getInt(res, Settings.Global.SHOW_PROCESSES, 0) != 0) {
Intent loadavg = new Intent(context, com.android.systemui.LoadAverageService.class);
context.startService(loadavg);
}
} catch (Exception e) {
Log.e(TAG, "Can't start load average service", e);
}
}Example 97
| Project: android-sotm-master File: AccountUtils.java View source code |
public static void addSyncAccount(Context context) {
AccountManager manager = AccountManager.get(context);
Account[] accounts = manager.getAccountsByType(ACCOUNT_TYPE);
if (accounts.length != 0) {
Log.d("Tried to add sync account, but one already existed!");
} else {
Log.i("Adding sync account...");
Account account = getSyncAccount();
manager.addAccountExplicitly(account, null, null);
ContentResolver.setIsSyncable(account, PointContentProvider.CONTENT_AUTHORITY, 1);
ContentResolver.setSyncAutomatically(account, PointContentProvider.CONTENT_AUTHORITY, true);
}
}Example 98
| Project: Android4.4Camera-master File: DataUtils.java View source code |
/**
* Get the file path from a Media storage URI.
*/
public static String getPathFromURI(ContentResolver contentResolver, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = contentResolver.query(contentUri, proj, null, null, null);
if (cursor == null) {
return null;
}
try {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (!cursor.moveToFirst()) {
return null;
} else {
return cursor.getString(columnIndex);
}
} finally {
cursor.close();
}
}Example 99
| Project: androidbible-master File: VerseProviderTest.java View source code |
public void testSingleVerse() throws Throwable {
ContentResolver cr = getContext().getContentResolver();
VerseProvider vp = new VerseProvider(cr);
int ari = 0x000103;
Verse v = vp.getVerse(0, 1, 3);
assertNotNull(v);
assertEquals(v.ari, ari);
assertNotNull(v.bookName);
assertNotNull(v.text);
assertTrue(v.text.length() > 0);
assertNotNull(v.toString());
assertEquals(v.toString().substring(0, v.bookName.length()), v.bookName);
// Gen 1:31 should have text
assertNotNull(vp.getVerse(0x00011f));
// Gen 1:32 should be null
assertNull(vp.getVerse(0x000120));
}Example 100
| Project: AndroidTraining-master File: SampleTestTarget3.java View source code |
// DB ã?«å•?ã?„å?ˆã‚?ã?›ã?Ÿçµ?果をã€?é?©å®œãƒ‡ãƒ¼ã‚¿æ§‹é€ ã?«å½“ã?¦ã?¯ã‚?ã?¦ã‚ªãƒ–ジェクトを作ã?£ã?¦ã€?リストã?§è¿”ã?™ãƒ¡ã‚½ãƒƒãƒ‰
public List<SampleDBEntity> getAllListFromDB(Context context) {
List<SampleDBEntity> list = new ArrayList<SampleDBEntity>();
ContentResolver resolver = context.getContentResolver();
Cursor c = null;
try {
c = resolver.query(TestTargetContentProvider.CONTENT_URI, new String[] { BaseColumns._ID, "name" }, null, null, null);
// çµ?æžœã?Œã?‚れã?°ã€?ãƒ?インタを先é ã?«ç§»å‹•ã?—ã?¦ã?‹ã‚‰å‡¦ç?†ã‚’å§‹ã‚?ã‚‹
if (c.moveToFirst()) {
do {
// Cursor �らデータを�り出��インスタンスを作��リスト�詰�る�1 回以上�繰り返�
int id = c.getInt(c.getColumnIndex(BaseColumns._ID));
String name = c.getString(c.getColumnIndex("name"));
list.add(new SampleDBEntity(id, name));
} while (c.moveToNext());
}
} finally {
// リソースを閉�る
if (c != null) {
c.close();
}
}
return list;
}Example 101
| Project: android_Browser-master File: BookmarksTests.java View source code |
public void testQueryCombinedForUrl() {
// First, add some bookmarks
assertNotNull(insertBookmark("http://google.com/search?q=test", "Test search"));
assertNotNull(insertBookmark("http://google.com/search?q=mustang", "Mustang search"));
assertNotNull(insertBookmark("http://google.com/search?q=aliens", "Aliens search"));
ContentResolver cr = getMockContentResolver();
Cursor c = null;
try {
// First, search for a match
String url = "http://google.com/search?q=test";
c = Bookmarks.queryCombinedForUrl(cr, null, url);
assertEquals(1, c.getCount());
assertTrue(c.moveToFirst());
assertEquals(url, c.getString(0));
c.close();
// Next, search for no match
url = "http://google.com/search";
c = Bookmarks.queryCombinedForUrl(cr, null, url);
assertEquals(0, c.getCount());
assertFalse(c.moveToFirst());
c.close();
} finally {
if (c != null)
c.close();
}
}