有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

通过Android应用程序中的ContentProvider对临时字段进行java查询

对于Android应用程序,我实现了一个ContentProvider来访问SQLite数据库。现在,我想为一组固定的不存在字段向查询中添加附加值。对于消费者来说,表字段和瞬时字段之间没有区别。因为这些字段必须是合同的一部分。 如何增强ContentProvider内部的查询,使光标包含这些字段。 例如:数据库表“event”有一个字段“timestamp”,应该使用一个临时字段“duration”来增强查询,该字段在运行时由两个选定条目的时间戳计算


共 (1) 个答案

  1. # 1 楼答案

    解决了。在查询方法中,我使用本地光标从数据库中选择数据。然后,用瞬态属性丰富的结果集将被复制到MatrixCursor中。此MatrixCursor将由ContentProvider的查询方法返回

    public class BikeHistProvider extends ContentProvider {
    
    // Contract 
    public final class Contract {
        public static final String KEY_ID = "_id";
        public static final String KEY_NAME = "name";
        /** Calculated at run time */
        public static final String KEY_MY_TRANSIENT_FIELD = "myTransientField";
    }
    
    @Override
    public Cursor query(Uri uri, String[] projection, 
                        String selection, String[] selectionArgs, 
                        String sortOrder) {
    
        // Create a Cursor with the field structure defined in
        // Contract
        MatrixCursor mc = new MatrixCursor(new String[]{
            Contract.KEY_ID,
            Contract.KEY_NAME
            Contract.KEY_MY_TRANSIENT_FIELD
            });                 
    
        // Apply the query to the underlying database.
        Cursor c = qb.query(db, projection, selection, selectionArgs,
                    null, null, orderBy);
    
        //Move result to MatrixCursor and add transient fields
        c.moveToFirst();
        do {
            //Create new entries
            Object[] values = {
            c.getInt(0), //The key for the database entry
            c.getString(Contract.KEY_NAME),
            calculateTransientField()};
    
            mc.addRow(values);
        } while (c.moveToNext());
        c.close();
    
        return mc;
        }
    }