Java Examples for android.database.Cursor
The following java examples will help you to understand the usage of android.database.Cursor. These source code samples are taken from different open source projects.
Example 1
| Project: SayItFromTheSky-master File: CursorHelper.java View source code |
/**
* Convert a {@link android.database.Cursor} to a {@link fr.tvbarthel.apps.sayitfromthesky.models.Drawing}
*
* @param cursor the {@link android.database.Cursor} to be converted.
* @return a new {@link fr.tvbarthel.apps.sayitfromthesky.models.Drawing}
*/
public static Drawing cursorToDrawing(Cursor cursor) {
final int id = CursorHelper.getInt(cursor, DrawingContract.Columns.COLUMN_ID, Drawing.NON_VALID_ID);
final String title = CursorHelper.getString(cursor, DrawingContract.Columns.COLUMN_TITLE, "");
final long creationTime = CursorHelper.getLong(cursor, DrawingContract.Columns.COLUMN_CREATION_TIME, 0l);
final String encodedPolylines = CursorHelper.getString(cursor, DrawingContract.Columns.COLUMN_ENCODED_POLYLINES, "");
final String[] polylines = GSON.fromJson(encodedPolylines, String[].class);
final Drawing drawing = new Drawing(title, creationTime, Arrays.asList(polylines));
drawing.setId(id);
return drawing;
}Example 2
| Project: actor-platform-master File: SQLiteHelpers.java View source code |
public static boolean isTableExists(SQLiteDatabase db, String tableName) {
Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '" + tableName + "'", null);
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.close();
return true;
}
cursor.close();
}
return false;
}Example 3
| Project: undergraduate-master File: V12Migration.java View source code |
@Override
public void migrate(SQLiteDatabase db) {
Cursor cursor = db.rawQuery("SELECT * FROM semesters WHERE semestername='2012-2013|2'", null);
if (cursor.moveToNext()) {
db.execSQL("UPDATE semester SET begindate=1362326400000,enddate=1373817600000" + "WHERE semestername=2012-2013|2");
}
cursor.close();
/***
2013-01-24 basilwang don't close db(db.close()) VERY IMPORTANT!!!!!!!
* **/
}Example 4
| Project: HugeSQLiteCursor-master File: HugeSQLiteCursor.java View source code |
/**
* Make sure the cursor is loaded at least up to position pos, but it could be a lot more.
*
* This allows you to manually "buffer" the cursor after it has
* finished initializing. For instance, calling
* cursor.loadUpTo(cursor.getCount()) loads the entire cursor.
* This could be called once the app is not doing any work so that
* items don't have to be loaded real-time when the user starts
* scrolling (useful for slower systems). It can also be used if
* you'd like to finalize the cursor because you're about to
* change something in the database.
*
* @param pos The minimum position you want to be loaded.
* @return void
*/
public void loadUpTo(int last) {
int pCount = getPartialCount();
if ((pCount < getCount()) && (last >= pCount)) {
if (Log.isLoggable(TAG, Log.DEBUG))
Log.d(TAG, "Loading HugeSQLiteCursor up to [" + last + "] (currently it's " + (pCount - 1) + ").");
// Save the position for latter
final int oldPos = mCursor.getPosition();
// Get the last _id we have
mCursor.moveToLast();
final int lastId = mCursor.getInt(mIdColumn);
// How Many steps to we need to add?
final int times = (last + 1 - pCount) / mStep + // 1 more then necessary, for safety.
(((last + 1 - pCount) % mStep) == 0 ? 1 : 2);
Cursor newCursor = db.query(mTable, mColumns, ((mWhere == null) ? "" : mWhere + " AND ") + "_id > " + lastId, mSearchText, null, null, "_id", Integer.toString(times * mStep));
// isFinished = (newCursor.getCount() < times*mStep);
mCursors.add(newCursor);
mCursor = new MergeCursor(mCursors.toArray(new Cursor[mCursors.size()]));
partialCount = mCursor.getCount();
mCursor.moveToPosition(oldPos);
if (Log.isLoggable(TAG, Log.DEBUG))
Log.d(TAG, "Loaded HugeSQLiteCursor up to [" + (partialCount - 1) + "].");
}
}Example 5
| Project: android-mileage-master File: WorstFuelEconomyChart.java View source code |
@Override
protected void processCursor(LineChartGenerator generator, Cursor cursor, Vehicle vehicle) {
int num = 0;
double worst_fuel_economy = 100000;
while (cursor.isAfterLast() == false) {
if (generator.isCancelled()) {
break;
}
if (num > 0) {
double economy = cursor.getDouble(1);
if (Calculator.isBetterEconomy(vehicle, economy, worst_fuel_economy) == false) {
worst_fuel_economy = economy;
}
addPoint(cursor.getLong(0), worst_fuel_economy);
}
generator.update(num++);
cursor.moveToNext();
}
}Example 6
| 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 7
| 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 8
| Project: BaiduImageViewer-master File: DatabaseUtils.java View source code |
public static int queryCount(SQLiteDatabase db, String tableName, String where, String[] whereArgs) {
StringBuffer stringBuffer = new StringBuffer("select count(*) from ");
stringBuffer.append(tableName);
if (where != null) {
stringBuffer.append(" where ");
stringBuffer.append(where);
}
Cursor cursor = db.rawQuery(stringBuffer.toString(), whereArgs);
cursor.moveToFirst();
int count = cursor.getInt(0);
cursor.close();
return count;
}Example 9
| 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 10
| Project: commcare-master File: UrlUtils.java View source code |
public static String getPathFromUri(Uri uri, Context context) {
if (uri.toString().startsWith("file")) {
return uri.toString().substring(6);
} else {
// find entry in content provider
String colString = null;
Cursor c = null;
try {
c = context.getContentResolver().query(uri, null, null, null, null);
if (c != null) {
c.moveToFirst();
// get data path
colString = c.getString(c.getColumnIndex("_data"));
}
} finally {
if (c != null) {
c.close();
}
}
return colString;
}
}Example 11
| Project: cw-andtutorials-master File: OldMobileContacts.java View source code |
public Cursor getMobileNumbers(Activity host) {
String[] PROJECTION = new String[] { Contacts.Phones._ID, Contacts.Phones.NAME, Contacts.Phones.NUMBER };
String[] ARGS = { String.valueOf(Contacts.Phones.TYPE_MOBILE) };
return (host.managedQuery(Contacts.Phones.CONTENT_URI, PROJECTION, Contacts.Phones.TYPE + "=?", ARGS, Contacts.Phones.NAME));
}Example 12
| 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 13
| Project: Dribbo-master File: DatabaseUtils.java View source code |
public static int queryCount(SQLiteDatabase db, String tableName, String where, String[] whereArgs) {
StringBuffer stringBuffer = new StringBuffer("select count(*) from ");
stringBuffer.append(tableName);
if (where != null) {
stringBuffer.append(" where ");
stringBuffer.append(where);
}
Cursor cursor = db.rawQuery(stringBuffer.toString(), whereArgs);
cursor.moveToFirst();
int count = cursor.getInt(0);
cursor.close();
return count;
}Example 14
| Project: SharedBillHelper2015-master File: CursorUtils.java View source code |
public static List<Long> getIdListFromCursor(Cursor cursor) {
long id = -1;
List<Long> idList = new ArrayList<>();
if (cursor != null && cursor.moveToPosition(-1)) {
while (cursor.moveToNext()) {
id = cursor.getLong(cursor.getColumnIndexOrThrow(BaseColumns._ID));
if (id >= 0) {
idList.add(id);
}
}
return idList;
}
return null;
}Example 15
| Project: Synodroid-master File: SearchViewBinder.java View source code |
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
try {
if (columnIndex == cursor.getColumnIndex("ADDED")) {
Long milliseconds = cursor.getLong(5);
Date d = new Date(milliseconds);
((TextView) view).setText(d.toLocaleString());
return true;
}
} catch (Exception e) {
}
return false;
}Example 16
| Project: wing4twitter-master File: DatabaseUtils.java View source code |
public static int queryCount(SQLiteDatabase db, String tableName, String where, String[] whereArgs) {
StringBuffer stringBuffer = new StringBuffer("select count(*) from ");
stringBuffer.append(tableName);
if (where != null) {
stringBuffer.append(" where ");
stringBuffer.append(where);
}
Cursor cursor = db.rawQuery(stringBuffer.toString(), whereArgs);
cursor.moveToFirst();
int count = cursor.getInt(0);
cursor.close();
return count;
}Example 17
| Project: bunurong-fieldguide-Android-master File: SpeciesListCursorAdapter.java View source code |
/* (non-Javadoc) * @see android.support.v4.widget.CursorAdapter#bindView(android.view.View, android.content.Context, android.database.Cursor) */ @Override public void bindView(View view, Context context, Cursor cursor) { String iconLabel = cursor.getString(cursor.getColumnIndex(FieldGuideDatabase.SPECIES_THUMBNAIL)); String iconPath = Utilities.SPECIES_IMAGES_THUMBNAILS_PATH + iconLabel; Log.d(TAG, iconLabel + " -> iconPath: " + iconPath); TextView txtView1 = (TextView) view.findViewById(R.id.speciesLabel); txtView1.setText(cursor.getString(cursor.getColumnIndex(FieldGuideDatabase.SPECIES_LABEL))); ImageView imgView = (ImageView) view.findViewById(R.id.speciesIcon); imgView.setImageBitmap(ImageResizer.decodeSampledBitmapFromFile(Utilities.getFullExternalDataPath(context, iconPath), 75, 75)); TextView txtView2 = (TextView) view.findViewById(R.id.speciesSublabel); txtView2.setText(cursor.getString(cursor.getColumnIndex(FieldGuideDatabase.SPECIES_SUBLABEL))); }
Example 18
| Project: mv-fieldguide-android-master File: SpeciesListCursorAdapter.java View source code |
/* (non-Javadoc) * @see android.support.v4.widget.CursorAdapter#bindView(android.view.View, android.content.Context, android.database.Cursor) */ @Override public void bindView(View view, Context context, Cursor cursor) { String iconLabel = cursor.getString(cursor.getColumnIndex(FieldGuideDatabase.SPECIES_THUMBNAIL)); String iconPath = Utilities.SPECIES_IMAGES_THUMBNAILS_PATH + iconLabel; Log.d(TAG, iconLabel + " -> iconPath: " + iconPath); TextView txtView1 = (TextView) view.findViewById(R.id.speciesLabel); txtView1.setText(cursor.getString(cursor.getColumnIndex(FieldGuideDatabase.SPECIES_LABEL))); ImageView imgView = (ImageView) view.findViewById(R.id.speciesIcon); // imgView.setImageBitmap(ImageResizer.decodeSampledBitmapFromAsset(context.getAssets(), iconPath, 150, 150)); // InputStream istr = null; // try { // istr = Utilities.getAssetInputStream(context, iconPath); // } catch (Exception e) { // e.printStackTrace(); // } // imgView.setImageBitmap(ImageResizer.decodeSampledBitmapFromStream(istr, 75, 75)); imgView.setImageBitmap(ImageResizer.decodeSampledBitmapFromFile(Utilities.getFullExternalDataPath(context, iconPath), 75, 75)); TextView txtView2 = (TextView) view.findViewById(R.id.speciesSublabel); txtView2.setText(cursor.getString(cursor.getColumnIndex(FieldGuideDatabase.SPECIES_SUBLABEL))); }
Example 19
| Project: sagesmobile-mReceive-master File: SummaryCursorAdapter.java View source code |
/* * (non-Javadoc) * * @see android.widget.CursorAdapter#bindView(android.view.View, * android.content.Context, android.database.Cursor) */ @Override public void bindView(View view, Context context, Cursor cursor) { SummaryCursorView pmcv = (SummaryCursorView) view; pmcv.setData(cursor); Integer intpos = Integer.valueOf(cursor.getPosition()); if (!mExpanded.containsKey(intpos)) { mExpanded.put(intpos, bFalse); } pmcv.setExpanded(mExpanded.get(intpos).booleanValue()); // bindCount++; mLoadViewCount++; }
Example 20
| Project: Android-Backup-master File: BulkFetcher.java View source code |
@NotNull
public BackupCursors fetch(@NotNull final EnumSet<DataType> types, @Nullable final ContactGroupIds groups, final int maxItems) {
int max = maxItems;
BackupCursors cursors = new BackupCursors();
for (DataType type : types) {
Cursor cursor = itemsFetcher.getItemsForDataType(type, groups, max);
cursors.add(type, cursor);
if (max > 0) {
max = Math.max(max - cursor.getCount(), 0);
}
if (max == 0)
break;
}
return cursors;
}Example 21
| Project: android-master File: MainActivity.java View source code |
public void getBrowserHist() {
Cursor cursor = getContentResolver().query(Browser.BOOKMARKS_URI, null, null, null, null);
// Cursor cursor = getContentResolver().query(Browser.SEARCHES_URI, null, null, null, null);
MyCursorAdapter myCursorAdapter = new MyCursorAdapter(this, cursor, 0);
listView.setAdapter(myCursorAdapter);
}Example 22
| Project: android-testmatos-master File: CheckedCriteriaViewBinder.java View source code |
@Override
public boolean bindView(View v, Cursor c) {
int id = v.getId();
String columnName = map.get(id);
if (columnName == null)
return false;
String value = c.getString(c.getColumnIndexOrThrow(columnName));
if (v instanceof CheckBox) {
CheckBox cb = (CheckBox) v;
cb.setTag(value);
return true;
} else
return super.bindView(v, c);
}Example 23
| 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 24
| Project: apps-android-wikipedia-master File: ReadingListPageDiskRow.java View source code |
public static ReadingListPageDiskRow fromCursor(@NonNull Cursor cursor) {
ReadingListPageDiskRow diskRow = ReadingListPage.DISK_DATABASE_TABLE.fromCursor(cursor);
boolean hasRow = ReadingListPageContract.DiskWithPage.KEY.val(cursor) != null;
ReadingListPageRow row = hasRow ? ReadingListPage.DATABASE_TABLE.fromCursor(cursor) : null;
return new ReadingListPageDiskRow(diskRow, row);
}Example 25
| Project: Area-master File: GlobalListAdapter.java View source code |
@Override public Cursor loadInBackground() { area = (AreaApplication) mContext.getApplicationContext(); try { if (area.areaData.globalSearch(searchType, searchField) >= SEARCH_SUCCESS) { Cursor results = area.areaData.getGlobalData(searchType, searchField); Log.d(TAG, "Returning data. Num of records: " + results.getCount()); /**/ return results; } } catch (IllegalStateException ilEc) { Log.e(TAG, "Database list loading returned Database Lock exception on " + searchType + " query"); } Log.d(TAG, "Returning zero"); return null; }
Example 26
| Project: audit-master File: MainActivity.java View source code |
private void displayRecords() {
String columns[] = new String[] { "_id", TestProvider.USER_NAME };
Uri myUri = TestProvider.CONTENT_URI;
Cursor cur = managedQuery(myUri, columns, null, null, null);
if (cur.moveToFirst()) {
String id = null;
String userName = null;
do {
id = cur.getString(cur.getColumnIndex("_id"));
userName = cur.getString(cur.getColumnIndex(TestProvider.USER_NAME));
Log.e("TestCase", id + ":" + userName);
} while (cur.moveToNext());
}
}Example 27
| Project: cg_starter-master File: LastCallActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null, null, null, null);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
while (managedCursor.moveToNext()) {
String phNumber = managedCursor.getString(number);
if (!phNumber.equals("")) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + phNumber));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
break;
}
}
managedCursor.close();
finish();
}Example 28
| Project: copyit-app-master File: HistoryListFactory.java View source code |
public static List<HistoryItem> buildList(Cursor cursor) {
List<HistoryItem> items = new ArrayList<HistoryItem>();
while (cursor.moveToNext()) {
String content = cursor.getString(cursor.getColumnIndex(HistoryContract.ItemEntry.COLUMN_NAME_CONTENT));
Date date = new Date(cursor.getLong(cursor.getColumnIndex(HistoryContract.ItemEntry.COLUMN_NAME_DATE)));
Change change = Change.valueOf(cursor.getString(cursor.getColumnIndex(HistoryContract.ItemEntry.COLUMN_NAME_CHANGE)));
items.add(new HistoryItem(content, date, change));
}
return items;
}Example 29
| Project: core-android-master File: RecordHashtableIdVisitor.java View source code |
@Override
public long cursor(Cursor cursor) {
Hashtable<String, String> map = new Hashtable<String, String>();
int columnIndex = 0;
for (String columnName : cursor.getColumnNames()) {
String value = cursor.getString(columnIndex);
if (columnIndex == 0) {
key = columnName;
}
map.put(columnName, value);
columnIndex += 1;
}
tree.put(key, map);
return 0;
}Example 30
| Project: coursera-android-master File: ContactsListExample.java View source code |
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContentResolver cr = getContentResolver();
Cursor c = cr.query(ContactsContract.Contacts.CONTENT_URI, new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null, null);
List<String> contacts = new ArrayList<String>();
if (c.moveToFirst()) {
do {
contacts.add(c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
} while (c.moveToNext());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, contacts);
setListAdapter(adapter);
}Example 31
| Project: deepnighttwo-master File: DBUtil.java View source code |
public static void initDB(Activity activity) {
SQLiteDatabase db = activity.openOrCreateDatabase(C.DB_NAME, Context.MODE_PRIVATE, null);
Cursor tableCur = db.query("sqlite_master", new String[] { "name" }, "type='table'", null, null, null, "name");
Set<String> tableNames = new HashSet<String>();
while (tableCur.moveToNext()) {
tableNames.add(tableCur.getString(0));
}
if (tableNames.contains(C.TB_USER) == false) {
db.execSQL("create table " + C.TB_USER + " (username varchar(255) not null, password varchar(32) not null);");
}
db.close();
}Example 32
| Project: DroidconApp-master File: UserProfileInfo.java View source code |
public static String findUserName(Context context) {
String displayName = null;
try {
Cursor c = context.getContentResolver().query(ContactsContract.Profile.CONTENT_URI, null, null, null, null);
int count = c.getCount();
c.moveToFirst();
int position = c.getPosition();
if (count == 1 && position == 0) {
displayName = c.getString(c.getColumnIndex(ContactsContract.Profile.DISPLAY_NAME));
}
c.close();
} catch (Exception e) {
Log.w("Hi", "Didn't work", e);
}
return displayName;
}Example 33
| 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 34
| Project: edx-app-android-master File: DbOperationGetVideos.java View source code |
@Override
public List<VideoModel> execute(SQLiteDatabase db) {
List<VideoModel> list = new ArrayList<VideoModel>();
Cursor c = getCursor(db);
if (c.moveToFirst()) {
do {
VideoModel video = DatabaseModelFactory.getModel(c);
list.add(video);
} while (c.moveToNext());
}
c.close();
return list;
}Example 35
| Project: enroscar-async-master File: CursorCloseAndroidTest.java View source code |
public void testCursorReset() throws Throwable {
final CursorAsyncUserActivity activity = getActivity();
assertThat(activity.cursorSync.await(10, TimeUnit.SECONDS)).isTrue();
assertThat(activity.cursor).isNotNull();
final Cursor c = activity.cursor;
runTestOnUiThread(new Runnable() {
@Override
public void run() {
getInstrumentation().callActivityOnDestroy(activity);
setActivity(null);
assertThat(activity.cursor).isNull();
assertThat(c).isClosed();
}
});
}Example 36
| Project: fighter-master File: MainActivity.java View source code |
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (c.moveToFirst()) {
System.out.println("ddddddddddddddddd: " + c.getCount());
do {
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.d("fff", name);
} while (c.moveToNext());
}
c.close();
}Example 37
| Project: GlassTunes-master File: HeaderActivity.java View source code |
@Override
protected CardFragment getCardFromCursor(Cursor cursor) {
Intent intent = new Intent("com.google.android.xdi.action.BROWSE");
intent.setData(ContentUris.withAppendedId(Uri.parse("content://com.google.android.music.xdi/browse"), cursor.getLong(cursor.getColumnIndex("_id"))));
return BrowseCard.newInstance(cursor.getString(cursor.getColumnIndex("display_name")), intent.toUri(Intent.URI_INTENT_SCHEME));
}Example 38
| Project: HeartBeat-master File: GetAllCrashesApi.java View source code |
public ArrayList<Crash> exec() {
Cursor cursor = mDatabaseHelper.getReadableDatabase().query(CrashTable.NAME, new String[] { CrashTable.LOG, CrashTable.TIMESTAMP }, null, null, null, null, null);
ArrayList<Crash> crashes = new ArrayList<>();
if (cursor.getCount() < 1)
return crashes;
cursor.moveToFirst();
do {
String log = cursor.getString(cursor.getColumnIndex(CrashTable.LOG));
long timestamp = cursor.getLong(cursor.getColumnIndex(CrashTable.TIMESTAMP));
crashes.add(0, new Crash(log, timestamp));
} while (cursor.moveToNext());
cursor.close();
return crashes;
}Example 39
| Project: java_android_demo-master File: PhoneHelper.java View source code |
public static List<PhoneInfo> getNumber(Context context) {
Cursor cursor = context.getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
String phoneNumber;
String contractName;
while (cursor.moveToNext()) {
phoneNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
contractName = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME));
System.out.println(contractName + "__" + phoneNumber);
PhoneInfo phoneInfo = new PhoneInfo(contractName, phoneNumber);
phoneList.add(phoneInfo);
}
return phoneList;
}Example 40
| Project: kolabnotes-android-master File: NotebookContentResolver.java View source code |
public static List<Notebook> getAll(Context context, String rootFolder) {
Uri uri = Uri.parse(BASE_URI + rootFolder);
Cursor cursor = context.getContentResolver().query(uri, new String[0], null, null, null);
if (cursor == null) {
if (cursor != null) {
cursor.close();
}
return Collections.emptyList();
}
while (cursor.moveToNext()) {
//TODO was machen
}
if (cursor != null) {
cursor.close();
}
return null;
}Example 41
| Project: kuliah_mobile-master File: ContactsListExample.java View source code |
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContentResolver cr = getContentResolver();
Cursor c = cr.query(ContactsContract.Contacts.CONTENT_URI, new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null, null);
List<String> contacts = new ArrayList<String>();
if (c.moveToFirst()) {
do {
contacts.add(c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
} while (c.moveToNext());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, contacts);
setListAdapter(adapter);
}Example 42
| Project: meetup-client-master File: EsAlphabetIndexer.java View source code |
private static CharSequence computeAlphabet(Cursor cursor, int i) {
StringBuilder stringbuilder = new StringBuilder();
boolean flag = cursor.moveToFirst();
int j = 0;
if (flag)
do {
char c = StringUtils.firstLetter(cursor.getString(i));
if (c != j) {
stringbuilder.append(c);
j = c;
}
} while (cursor.moveToNext());
return stringbuilder.toString();
}Example 43
| Project: MessageRelayer-master File: ContactManager.java View source code |
/**
* 从ContentProviderä¸èŽ·å?–所有è?”系人
* @param context
* @return
*/
public static ArrayList<Contact> getContactList(Context context) {
ArrayList<Contact> mContactList = new ArrayList<>();
Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY);
while (cursor.moveToNext()) {
Contact contact = new Contact();
contact.setContactName(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
contact.setContactNum(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
mContactList.add(contact);
}
return mContactList;
}Example 44
| Project: messaging-master File: CursorUtil.java View source code |
public static Object cursorValue(String column, Cursor cr) { Object value = false; int index = cr.getColumnIndex(column); switch(cr.getType(index)) { case Cursor.FIELD_TYPE_NULL: value = false; break; case Cursor.FIELD_TYPE_STRING: value = cr.getString(index); break; case Cursor.FIELD_TYPE_INTEGER: value = cr.getInt(index); break; case Cursor.FIELD_TYPE_FLOAT: value = cr.getFloat(index); break; case Cursor.FIELD_TYPE_BLOB: value = cr.getBlob(index); break; } return value; }
Example 45
| Project: minerstatus-master File: ThemeServiceImpl.java View source code |
public Theme getTheme() {
Cursor cursor = null;
try {
cursor = getDBr().rawQuery(SELECT_CONFIG_VALUE, new String[] { "theme" });
if (cursor.moveToNext()) {
return ThemeFactory.getTheme(cursor.getString(0));
} else {
return ThemeFactory.getTheme();
}
} catch (Exception e) {
return ThemeFactory.getTheme();
} finally {
if (cursor != null) {
cursor.close();
}
}
}Example 46
| Project: mobile-ecommerce-android-education-master File: ListViewActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor c = managedQuery(Contacts.CONTENT_URI, null, null, null, Contacts.DISPLAY_NAME + " ASC");
String[] cols = new String[] { Contacts.DISPLAY_NAME };
int[] views = new int[] { android.R.id.text1 };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, c, cols, views);
this.setListAdapter(adapter);
}Example 47
| Project: MonsterHunter3UDatabase-master File: MonsterToQuestListCursorLoader.java View source code |
@Override
protected Cursor loadCursor() {
if (from.equals(FROM_MONSTER)) {
// Query the list of quests based on monster
return DataManager.get(getContext()).queryMonsterToQuestMonster(id);
} else if (from.equals(FROM_QUEST)) {
// Query the list of monsters based on quest
return DataManager.get(getContext()).queryMonsterToQuestQuest(id);
} else {
return null;
}
}Example 48
| Project: MonsterHunter4UDatabase-master File: UniversalSearchCursorLoader.java View source code |
@Override
protected Cursor loadCursor() {
DataManager manager = DataManager.get(getContext());
try {
MultiObjectCursor.Builder builder = new MultiObjectCursor.Builder();
builder.add(manager.queryMonstersSearch(searchTerm), "getMonster");
builder.add(manager.queryQuestsSearch(searchTerm), "getQuest");
builder.add(manager.queryItemSearch(searchTerm), "getItem");
return builder.create();
} catch (NoSuchMethodException ex) {
throw new RuntimeException(ex);
}
}Example 49
| 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 50
| Project: OrderNowAndroid-master File: CurrentOrdersHelpers.java View source code |
public void getCurrentOrders() {
Cursor cursor = dbManager.rawQuery(GET_ALL_EVENTS, null);
Map<String, String> map = new HashMap<String, String>();
while (cursor.moveToNext()) {
for (String col : columns) map.put(col, cursor.getString(cursor.getColumnIndex(col)));
}
Utilities.info(map.toString());
}Example 51
| Project: PADListener-master File: ViewCapturedDataFriendsFragment.java View source code |
@Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { MyLog.entry(); final Loader<Cursor> loader = new CursorLoader(getActivity(), CapturedPlayerFriendDescriptor.UriHelper.uriForAllWithInfo(), null, null, null, CapturedPlayerFriendDescriptor.TABLE_NAME + "." + CapturedPlayerFriendDescriptor.Fields.NAME.getColName()); MyLog.exit(); return loader; }
Example 52
| Project: Phonograph-master File: LastAddedLoader.java View source code |
public static Cursor makeLastAddedCursor(@NonNull final Context context) {
long fourWeeksAgo = (System.currentTimeMillis() / 1000) - (4 * 3600 * 24 * 7);
// possible saved timestamp caused by user "clearing" the last added playlist
long cutoff = PreferenceUtil.getInstance(context).getLastAddedCutOffTimestamp() / 1000;
if (cutoff < fourWeeksAgo) {
cutoff = fourWeeksAgo;
}
return SongLoader.makeSongCursor(context, MediaStore.Audio.Media.DATE_ADDED + ">?", new String[] { String.valueOf(cutoff) }, MediaStore.Audio.Media.DATE_ADDED + " DESC");
}Example 53
| Project: Securecom-Text-master File: ConversationListLoader.java View source code |
@Override
public Cursor loadInBackground() {
if (filter != null && filter.trim().length() != 0) {
List<String> numbers = ContactAccessor.getInstance().getNumbersForThreadSearchFilter(filter, context.getContentResolver());
return DatabaseFactory.getThreadDatabase(context).getFilteredConversationList(numbers);
} else {
return DatabaseFactory.getThreadDatabase(context).getConversationList();
}
}Example 54
| Project: shoppinglist-master File: ProviderUtils.java View source code |
/**
* Returns the row IDs of all affected rows.
*
* @param db
* @param table
* @param whereClause
* @param whereArgs
* @return
*/
public static long[] getAffectedRows(SQLiteDatabase db, String table, String whereClause, String[] whereArgs) {
if (TextUtils.isEmpty(whereClause)) {
return null;
}
Cursor c = db.query(table, new String[] { BaseColumns._ID }, whereClause, whereArgs, null, null, null);
long[] affectedRows = null;
if (c != null) {
affectedRows = new long[c.getCount()];
for (int i = 0; c.moveToNext(); i++) {
affectedRows[i] = c.getLong(0);
}
}
c.close();
return affectedRows;
}Example 55
| Project: sms-backup-plus-master File: BulkFetcher.java View source code |
@NotNull
public BackupCursors fetch(@NotNull final EnumSet<DataType> types, @Nullable final ContactGroupIds groups, final int maxItems) {
int max = maxItems;
BackupCursors cursors = new BackupCursors();
for (DataType type : types) {
Cursor cursor = itemsFetcher.getItemsForDataType(type, groups, max);
cursors.add(type, cursor);
if (max > 0) {
max = Math.max(max - cursor.getCount(), 0);
}
if (max == 0)
break;
}
return cursors;
}Example 56
| Project: sonet-master File: PhotoPathLoader.java View source code |
@Override
public String loadInBackground() {
String path;
Cursor cursor = mContext.getContentResolver().query(mUri, new String[] { MediaStore.Images.Media.DATA }, null, null, null);
if (cursor.moveToFirst()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
} else {
// some file managers send the path in the uri
path = mUri.getPath();
}
cursor.close();
return path;
}Example 57
| Project: storio-master File: PrimitivePrivateFieldsStorIOSQLiteGetResolver.java View source code |
/**
* {@inheritDoc}
*/
@Override
@NonNull
public PrimitivePrivateFields mapFromCursor(@NonNull Cursor cursor) {
PrimitivePrivateFields object = new PrimitivePrivateFields();
object.setField1(cursor.getInt(cursor.getColumnIndex("field1")) == 1);
object.setField2(cursor.getShort(cursor.getColumnIndex("field2")));
object.setField3(cursor.getInt(cursor.getColumnIndex("field3")));
object.setField4(cursor.getLong(cursor.getColumnIndex("field4")));
object.setField5(cursor.getFloat(cursor.getColumnIndex("field5")));
object.setField6(cursor.getDouble(cursor.getColumnIndex("field6")));
object.setField7(cursor.getString(cursor.getColumnIndex("field7")));
object.setField8(cursor.getBlob(cursor.getColumnIndex("field8")));
return object;
}Example 58
| 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 59
| Project: TextSecureSMP-master File: ConversationListLoader.java View source code |
@Override
public Cursor getCursor() {
if (filter != null && filter.trim().length() != 0) {
List<String> numbers = ContactAccessor.getInstance().getNumbersForThreadSearchFilter(context, filter);
return DatabaseFactory.getThreadDatabase(context).getFilteredConversationList(numbers);
} else {
return DatabaseFactory.getThreadDatabase(context).getConversationList();
}
}Example 60
| Project: thedroid-master File: DefaultContacts.java View source code |
public BasicContact process(Activity activity, Intent data) throws NoPhoneNumberException {
BasicContact contact = null;
Uri contactData = data.getData();
Cursor cursor = activity.managedQuery(contactData, null, null, null, null);
if (cursor.moveToFirst()) {
contact = finder.find(cursor, activity.getContentResolver());
}
cursor.close();
if (contact == null)
throw new IllegalStateException("No phone number to process.");
return contact;
}Example 61
| Project: training-content-master File: ReadMessagesActivity.java View source code |
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtMessages = (TextView) findViewById(R.id.messages);
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = getContentResolver().query(uriSMSURI, null, null, null, BaseColumns._ID + " DESC LIMIT 40");
String sms = "";
while (cur.moveToNext()) {
sms += "From :" + cur.getString(2) + " : " + cur.getString(12) + "\n";
}
txtMessages.setText(sms);
}Example 62
| Project: translator-master File: DBUtil.java View source code |
public static Boolean queryIfItemExist(NotebookDatabaseHelper dbhelper, String queryString) {
SQLiteDatabase db = dbhelper.getReadableDatabase();
Cursor cursor = db.query("notebook", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
String s = cursor.getString(cursor.getColumnIndex("input"));
if (queryString.equals(s)) {
return true;
}
} while (cursor.moveToNext());
}
cursor.close();
return false;
}Example 63
| Project: tuberun_android-master File: StationsProviderDepartures.java View source code |
@Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (!isOpen) tryOpen(); if (!isOpen) return null; Cursor result = null; try { switch(sUriMatcher.match(uri)) { case 1: result = myDbHelper.getDeparturesSuggestions(selectionArgs[0]); break; default: } result = myDbHelper.getDeparturesSuggestions(selectionArgs[0]); } catch (Exception e) { Log.w("StationsProvider", e); } finally { // myDbHelper.close(); } return result; }
Example 64
| Project: UnivrApp-master File: LightweightItemLoader.java View source code |
@Override
public Item load(Cursor cursor) {
Item item = new Item();
// cursor.getColumnIndex(Items.ID));
item.id = cursor.getInt(0);
// cursor.getColumnIndex(Items.TITLE));
item.title = cursor.getString(1);
// cursor.getColumnIndex(Items.PUB_DATE));
item.pubDate = new Timestamp(cursor.getLong(3));
item.updateTime = cursor.getLong(3);
item.channel = new Channel(cursor.getInt(4));
return item;
}Example 65
| 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 66
| Project: folio100_frameworks_base-master File: SimpleCursorAdapter.java View source code |
/**
* 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 67
| Project: mayloon-runtime-master File: SimpleCursorAdapter.java View source code |
/**
* 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 /*else if (v instanceof ImageView) {
setViewImage((ImageView) v, text);
}*/
{
throw new IllegalStateException(v.getClass().getName() + " is not a " + " view that can be bounds by this SimpleCursorAdapter");
}
}
}
}
}Example 68
| Project: allogy-legacy-android-app-master File: StudentCursorAdapter.java View source code |
private void InitializeAdapter(Activity activity) {
String TAG = "Student Initialize Cursor Adpter";
mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Cursor cursor = this.getCursor();
Log.d(TAG, "Start");
colID = cursor.getColumnIndexOrThrow(Academic.Users._ID);
colFN = cursor.getColumnIndexOrThrow(Academic.Users.FIRST_NAME);
colLN = cursor.getColumnIndexOrThrow(Academic.Users.LAST_NAME);
colUN = cursor.getColumnIndexOrThrow(Academic.Users.USERNAME);
Log.d(TAG, colID + ":" + colFN + ":" + colLN + ":" + colUN);
}Example 69
| Project: AndroidViewUtils-master File: SampleExpandAndShrinkCard.java View source code |
/*
* Bind the sample title and text into our card view
*/
public void bind(final Cursor cursor) {
final Object tag = this.getTag();
if (tag != null && tag instanceof ViewHolder) {
final ViewHolder viewHolder = (ViewHolder) tag;
// Get Title and Text
if (cursor != null) {
final String title = cursor.getString(cursor.getColumnIndexOrThrow(ExpandShrinkListViewActivity.COLUMN_NAME_TITLE));
final String text = cursor.getString(cursor.getColumnIndexOrThrow(ExpandShrinkListViewActivity.COLUMN_NAME_TEXT));
viewHolder.title.setText(title);
viewHolder.text.setText(text);
}
}
}Example 70
| Project: rapidandroid-master File: SummaryCursorAdapter.java View source code |
/* * (non-Javadoc) * * @see android.widget.CursorAdapter#bindView(android.view.View, * android.content.Context, android.database.Cursor) */ @Override public void bindView(View view, Context context, Cursor cursor) { SummaryCursorView pmcv = (SummaryCursorView) view; pmcv.setData(cursor); Integer intpos = Integer.valueOf(cursor.getPosition()); if (!mExpanded.containsKey(intpos)) { mExpanded.put(intpos, bFalse); } pmcv.setExpanded(mExpanded.get(intpos).booleanValue()); // bindCount++; mLoadViewCount++; }
Example 71
| Project: TagNotepad-master File: TagListAdapter.java View source code |
/* (é?ž Javadoc)
* @see android.support.v4.widget.ResourceCursorAdapter#newView(android.content.Context, android.database.Cursor, android.view.ViewGroup)
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_item_tag, null, true);
ViewHolder holder = new ViewHolder();
holder.textView = (TextView) rowView.findViewById(R.id.tag_item);
holder.imageView = (ImageView) rowView.findViewById(R.id.icon_tag_list);
rowView.setTag(holder);
return rowView;
}Example 72
| Project: 2Degrees-Toolbox-master File: DBLog.java View source code |
public static void insertMessage(Context c, String severity, String tag, String message) {
DBOpenHelper dbHelper = new DBOpenHelper(c);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
Date now = new Date();
values.put("date_time", DateFormatters.ISO8601FORMAT.format(now));
values.put("severity", severity);
values.put("tag", tag);
values.put("message", message);
db.insert("log", null, values);
if ((int) (Math.random() * 200) == 5) {
Cursor results = db.rawQuery("SELECT COUNT(1) FROM log", null);
results.moveToFirst();
int noLines = results.getInt(0);
results.close();
if (noLines > 50) {
String sql = "DELETE FROM log WHERE `id` IN (SELECT `id` FROM log ORDER BY `id` ASC LIMIT " + (noLines - 50) + ")";
Log.d("2DegreesDBLog", "Deleting " + (noLines - 50) + "rows. Sql: " + sql);
db.execSQL(sql);
}
}
db.close();
}Example 73
| Project: Amigo-master File: MainActivity.java View source code |
public void testProvider(View view) {
Cursor cursor = getContentResolver().query(Uri.parse("content://me.ele.app.amigo.provider/student?id=0"), null, null, null, null);
Log.d(TAG, "testPatchedProvider: patched provider loaded ? " + (cursor != null));
if (cursor != null) {
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String gender = cursor.getInt(2) == 0 ? "male" : "female";
Log.d(TAG, "testPatchedProvider: student[id=" + id + ", name=" + name + ", gender=" + gender + "]");
}
cursor.close();
}
}Example 74
| Project: Android---CSV-Contacts-Import-master File: MainScreen.java View source code |
public void listContacts() {
String[] projection = new String[] { People.NAME, People.Phones._COUNT, People.PRIMARY_EMAIL_ID, People.NUMBER };
Uri contacts = People.CONTENT_URI;
Cursor managedCursor = managedQuery(contacts, projection, null, null, People.NAME + "ASC");
String[] displayFields = new String[] { People.NAME, People.NUMBER };
int[] displayViews = new int[] { android.R.id.text1, android.R.id.text2 };
setListAdapter(new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, managedCursor, displayFields, displayViews));
}Example 75
| Project: android-app-common-tasks-master File: CameraActivity.java View source code |
public String getRealPathFromURI(Uri contentUri) {
// can post image
String[] proj = { MediaStore.Images.Media.DATA };
@SuppressWarnings("deprecation") Cursor cursor = managedQuery(// Which columns to
contentUri, // Which columns to
proj, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null, // Order-by clause (ascending by name)
null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}Example 76
| Project: android-atleap-master File: CursorFiler.java View source code |
@Override
protected FilterResults performFiltering(CharSequence constraint) {
Cursor cursor = mClient.runQueryOnBackgroundThread(constraint);
FilterResults results = new FilterResults();
if (cursor != null) {
results.count = cursor.getCount();
results.values = cursor;
} else {
results.count = 0;
results.values = null;
}
return results;
}Example 77
| Project: Android-Cookbook-Examples-master File: MainActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Cursor c = new DataToCursor();
String[] fromColumns = { c.getColumnName(1), c.getColumnName(2) };
int[] toViews = { android.R.id.text1, android.R.id.text2 };
@SuppressWarnings("deprecation") ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, c, fromColumns, toViews);
getListView().setAdapter(adapter);
}Example 78
| Project: android-development-course-master File: MainActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Uri uri = Uri.parse("content://" + "jp.mixi.sample.contentprovider.Book" + "/book");
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
while (cursor.moveToNext()) {
Log.d(TAG, "call:" + cursor.getString(cursor.getColumnIndexOrThrow("title")));
}
// 処��完了��らCursorを閉���
cursor.close();
}Example 79
| Project: android-discourse-master File: DrawerCategoryAdapter.java View source code |
@Override
public void bindView(View view, Context context, Cursor cursor) {
Categories c = new Categories(cursor);
view.setTag(c);
View color = view.findViewById(R.id.category_color);
String colorString = c.getColor();
int colorValue = Utils.parseColor(colorString);
color.setBackgroundColor(colorValue);
TextView name = (TextView) view.findViewById(R.id.category_name);
name.setText(c.getName());
}Example 80
| 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 81
| Project: android-money-manager-ex-master File: InfoRepositorySql.java View source code |
// @Override
// public String[] getAllColumns() {
// return new String[] {"INFOID AS _id", Info.INFOID, Info.INFONAME, Info.INFOVALUE};
// }
public List<Info> loadAll(String infoName) {
Select sql = new Select().from(TABLE_NAME).where(Info.INFONAME + "=?", infoName);
Cursor c = this.query(sql);
if (c == null)
return null;
List<Info> results = new ArrayList<>();
while (c.moveToNext()) {
Info entity = new Info();
entity.loadFromCursor(c);
results.add(entity);
}
return results;
}Example 82
| Project: android-smsmms-master File: SubscriptionIdChecker.java View source code |
// I met a device which does not have Telephony.Mms.SUBSCRIPTION_ID event if it's API Level is 22.
private void check(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
Cursor c = null;
try {
c = SqliteWrapper.query(context, context.getContentResolver(), Telephony.Mms.CONTENT_URI, new String[] { Telephony.Mms.SUBSCRIPTION_ID }, null, null, null);
if (c != null) {
mCanUseSubscriptionId = true;
}
} catch (SQLiteException e) {
Log.e(TAG, "SubscriptionIdChecker.check() fail");
} finally {
if (c != null) {
c.close();
}
}
}
}Example 83
| Project: Android-sql-lite-helper-master File: SqlLiteTests.java View source code |
public void testEdit() {
mHelper.addEvent("BBBB", new Date(), "ShortEvent");
Cursor c = mHelper.getAllEvent();
c.moveToFirst();
int index = c.getInt(0);
mHelper.updateEvent(index, "CCCC", new Date(), "ShortName1");
c = mHelper.getAllEvent();
c.moveToFirst();
assertEquals(c.getString(DbHelperDbHelper.EVENT_DESCRIPTION_COLUMN_POSITION), "CCCC");
}Example 84
| Project: android-sqlite-asset-helper-master File: MyDatabase.java View source code |
public Cursor getEmployees() { SQLiteDatabase db = getReadableDatabase(); SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String[] sqlSelect = { "0 _id", "FirstName", "LastName" }; String sqlTables = "Employees"; qb.setTables(sqlTables); Cursor c = qb.query(db, sqlSelect, null, null, null, null, null); c.moveToFirst(); return c; }
Example 85
| Project: Android-Studio-Project-master File: ProviderActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Uri bookUri = Uri.parse("content://com.example.mr_wrong.androidstudioproject.provider/book");
//getContentResolver().query(bookUri, new String[]{"_id", "name"}, null, null, null);
ContentValues values = new ContentValues();
values.put("_id", 6);
values.put("name", "开�的艺术");
getContentResolver().insert(bookUri, values);
Cursor bookCursor = getContentResolver().query(bookUri, new String[] { "_id", "name" }, null, null, null);
while (bookCursor.moveToNext()) {
LogUtils.e("id:" + bookCursor.getInt(0) + " name:" + bookCursor.getString(1));
}
bookCursor.close();
Uri userUri = Uri.parse("content://com.example.mr_wrong.androidstudioproject.provider/user");
Cursor userCursor = getContentResolver().query(userUri, new String[] { "_id", "name", "sex" }, null, null, null);
while (userCursor.moveToNext()) {
LogUtils.e("id:" + userCursor.getInt(0) + " name:" + userCursor.getString(1) + " sex:" + userCursor.getInt(2));
//LogUtils.e("æ£åœ¨æŸ¥è¯¢");
}
userCursor.close();
}Example 86
| Project: Android-Templates-And-Utilities-master File: SearchSuggestionAdapter.java View source code |
@Override
public void bindView(View view, Context context, Cursor cursor) {
// reference
LinearLayout root = (LinearLayout) view;
TextView titleTextView = (TextView) root.findViewById(R.id.search_suggestion_item_title);
TextView subtitleTextView = (TextView) root.findViewById(R.id.search_suggestion_item_subtitle);
// content
final int index1 = cursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1);
final int index2 = cursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_2);
titleTextView.setText(cursor.getString(index1));
subtitleTextView.setText(cursor.getString(index2));
}Example 87
| Project: AndroidBinding-master File: CursorField.java View source code |
public void fillValue(Cursor cursor) {
if (mColumnIndex >= 0) {
this.set(returnValue(cursor));
return;
}
if (mColumnIndex == COLUMN_NOT_FOUND)
return;
if (mColumnIndex == COLUMN_UNSET) {
mColumnIndex = cursor.getColumnIndex(mColumnName);
fillValue(cursor);
return;
}
}Example 88
| Project: AndroidCommons-master File: IntentsHandler.java View source code |
/**
* Call this method from {@link android.app.Activity#onActivityResult(int, int, android.content.Intent)} method to
* get picked contact info.
*/
public static ContactInfo onPickPhoneResult(Context context, Intent data) {
if (data == null || data.getData() == null)
return null;
Cursor c = null;
try {
c = context.getContentResolver().query(data.getData(), new String[] { ContactsContract.CommonDataKinds.Phone.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER }, null, null, null);
if (c != null && c.moveToFirst()) {
return new ContactInfo(c.getInt(0), c.getString(1), c.getString(2));
}
} finally {
if (c != null)
c.close();
}
return null;
}Example 89
| Project: AndroidRecyclerViewDemo-master File: CursorFilter.java View source code |
@Override
protected FilterResults performFiltering(CharSequence constraint) {
Cursor cursor = mClient.runQueryOnBackgroundThread(constraint);
FilterResults results = new FilterResults();
if (cursor != null) {
results.count = cursor.getCount();
results.values = cursor;
} else {
results.count = 0;
results.values = null;
}
return results;
}Example 90
| Project: AndroidTraining-master File: MainActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Uri uri = Uri.parse("content://" + "jp.mixi.sample.contentprovider.Book" + "/book");
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
while (cursor.moveToNext()) {
Log.d(TAG, "call:" + cursor.getString(cursor.getColumnIndexOrThrow("title")));
}
// 処��完了��らCursorを閉���
cursor.close();
}Example 91
| Project: AndroidZipcodeLib-master File: ZipcodeDataSource.java View source code |
public static ZipResult getValue(String zip, SQLiteDatabase database) {
Cursor cursor = database.rawQuery("select * from zipcodes where zipcode = \'" + zip + "\' LIMIT 1", null);
boolean result = cursor.moveToFirst();
if (!result) {
cursor.close();
return null;
}
String zipDB = cursor.getString(0);
String state = cursor.getString(1);
String primaryCity = cursor.getString(2);
Cursor cities = database.rawQuery("select * from cities where parent_id = \'" + zipDB + "\'", null);
ArrayList<String> holder = new ArrayList<String>();
boolean resultCities = cities.moveToFirst();
if (resultCities) {
String cit = cities.getString(1);
holder.add(cit);
while (cities.moveToNext()) {
cit = cities.getString(1);
holder.add(cit);
}
}
ZipResult ret = new ZipResult();
ret.state = state;
ret.zip = zip;
ret.cities.add(primaryCity);
for (int r = 0; r < holder.size(); r++) {
ret.cities.add(holder.get(r));
}
cursor.close();
cities.close();
return ret;
}Example 92
| Project: Android_App_OpenSource-master File: SQLiteUtil.java View source code |
public <T> ArrayList<T> queryByPage(String sql, int pageIndex, int pageSize, CursorDataExtractor<T> cursorDataExactor) {
int offset = pageIndex * pageSize;
sql = "select * from (" + sql + ")" + " limit " + pageSize + " offset" + offset;
ArrayList<T> resultList = null;
Cursor cursor = sqLiteDatabase.rawQuery(sql, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
resultList = new ArrayList<T>();
do {
resultList.add(cursorDataExactor.extractData(sqLiteDatabase, cursor));
} while (cursor.isLast());
}
cursor.deactivate();
cursor.close();
}
return resultList;
}Example 93
| Project: android_chat-master File: SearchContacts.java View source code |
@Override
protected String[] doInBackground(Void... params) {
String results = "";
Cursor c = act.getContentResolver().query(Phone.CONTENT_URI, new String[] { Phone.NUMBER, Phone.DISPLAY_NAME }, null, null, null);
if (c != null) {
while (c.moveToNext()) {
String number = c.getString(c.getColumnIndex(Phone.NUMBER));
//String name = c.getString(c.getColumnIndex(Phone.DISPLAY_NAME));
results += number + ",";
}
}
return results.split(",");
}Example 94
| Project: android_packages_apps_apolloMod-master File: SonglistAdapter.java View source code |
public void setupViewData(Cursor mCursor) {
mLineOneText = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaColumns.TITLE));
mLineTwoText = mCursor.getString(mCursor.getColumnIndexOrThrow(AudioColumns.ARTIST));
mImageData = new String[] { mLineTwoText };
mPlayingId = MusicUtils.getCurrentAudioId();
mCurrentId = mCursor.getLong(mCursor.getColumnIndexOrThrow(BaseColumns._ID));
mListType = TYPE_ARTIST;
}Example 95
| Project: android_xcore-master File: CacheRequestHelper.java View source code |
public static boolean cacheIfNotCached(Context context, DataSourceRequest dataSourceRequest, long requestId) {
Cursor cursor = context.getContentResolver().query(ModelContract.getUri(DataSourceRequestEntity.class, requestId), new String[] { DataSourceRequestEntity.LAST_UPDATE }, null, null, null);
try {
if (cursor == null || !cursor.moveToFirst()) {
context.getContentResolver().insert(ModelContract.getUri(DataSourceRequestEntity.class), DataSourceRequestEntity.prepare(dataSourceRequest));
} else {
Long lastUpdate = CursorUtils.getLong(DataSourceRequestEntity.LAST_UPDATE, cursor);
if (System.currentTimeMillis() - dataSourceRequest.getCacheExpiration() < lastUpdate) {
return true;
} else {
context.getContentResolver().insert(ModelContract.getUri(DataSourceRequestEntity.class), DataSourceRequestEntity.prepare(dataSourceRequest));
}
}
} finally {
CursorUtils.close(cursor);
}
return false;
}Example 96
| 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 97
| Project: AOS2012-Android-master File: TalksByHourTreeAdapter.java View source code |
@Override protected Cursor getChildrenCursor(Cursor groupCursor) { String[] projection = new String[] { KitaosContract.Talks._ID, KitaosContract.Talks.TITLE, KitaosContract.Talks.ROOM, KitaosContract.Talks.SPEAKER }; if (groupCursor == null || mContentResover == null) { return new MatrixCursor(projection); } Long startDate = groupCursor.getLong(0); return mContentResover.query(KitaosContract.Talks.uri(), projection, KitaosContract.Talks.START_DATE + "=?", new String[] { "" + startDate }, KitaosContract.Talks.ROOM + " ASC"); }
Example 98
| Project: AppCodeArchitecture-master File: CursorFilter.java View source code |
@Override
protected FilterResults performFiltering(CharSequence constraint) {
Cursor cursor = mClient.runQueryOnBackgroundThread(constraint);
FilterResults results = new FilterResults();
if (cursor != null) {
results.count = cursor.getCount();
results.values = cursor;
} else {
results.count = 0;
results.values = null;
}
return results;
}Example 99
| Project: arca-android-master File: CursorAdapterHelper.java View source code |
private void bindView(final View container, final Cursor cursor, final Binding binding) {
final View view = ViewHelper.getView(container, binding.getViewId());
boolean bound = false;
if (mViewBinder != null) {
bound = mViewBinder.setViewValue(view, cursor, binding);
}
if (!bound) {
bound = mDefaultBinder.setViewValue(view, cursor, binding);
}
if (!bound) {
throw new IllegalStateException("Cannot bind to view: " + view);
}
}Example 100
| Project: BangumiTimeMachine-master File: DB.java View source code |
public BaseAuth getAuth() {
SQLiteDatabase db = helper.getReadableDatabase();
Cursor query = db.rawQuery("select * from " + DBHelper.TABLE_AUTH, null);
BaseAuth auth = null;
if (query.moveToFirst()) {
auth = new BaseAuth();
auth.setUsername(query.getString(query.getColumnIndex("username")));
auth.setPassword(query.getString(query.getColumnIndex("password")));
}
query.close();
db.close();
return auth;
}Example 101
| Project: boardgamegeek4android-master File: Game.java View source code |
public void addColors(@NonNull Context context) {
colors = new ArrayList<>();
final Cursor cursor = context.getContentResolver().query(Games.buildColorsUri(id), Color.PROJECTION, null, null, null);
if (cursor == null) {
return;
}
try {
while (cursor.moveToNext()) {
Color color = Color.fromCursor(cursor);
colors.add(color);
}
} finally {
cursor.close();
}
}