Java Code Examples for android.database.Cursor#getColumnCount()

The following examples show how to use android.database.Cursor#getColumnCount() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Logger.java    From chess with Apache License 2.0 6 votes vote down vote up
public static void log(final Cursor c) {
    if (!BuildConfig.DEBUG) return;
    c.moveToFirst();
    String title = "";
    for (int i = 0; i < c.getColumnCount(); i++)
        title += c.getColumnName(i) + " | ";
    log(title);
    while (!c.isAfterLast()) {
        title = "";
        for (int i = 0; i < c.getColumnCount(); i++)
            title += c.getString(i) + " | ";
        log(title);
        c.moveToNext();
    }
    c.close();
}
 
Example 2
Source File: MediaManager.java    From Musicoco with Apache License 2.0 6 votes vote down vote up
private synchronized String getAlbumArtPicPath(Context context, String albumId) {

        // 小米应用商店检测crash ,错误信息:[31188,0,com.duan.musicoco,13155908,java.lang.IllegalStateException,Unknown URL: content://media/external/audio/albums/null,Parcel.java,1548]
        if (!StringUtils.isReal(albumId)) {
            return null;
        }

        String[] projection = {MediaStore.Audio.Albums.ALBUM_ART};
        String imagePath = null;
        Uri uri = Uri.parse("content://media" + MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI.getPath() + "/" + albumId);

        Cursor cur = context.getContentResolver().query(uri, projection, null, null, null);
        if (cur == null) {
            return null;
        }

        if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
            cur.moveToNext();
            imagePath = cur.getString(0);
        }
        cur.close();


        return imagePath;
    }
 
Example 3
Source File: StudentGradeActivity.java    From Android-ORM with Apache License 2.0 6 votes vote down vote up
@Override
protected ListAdapter onUpdateAdapter() {
    Cursor c = ExampleContentProvider.getSession().query(
            Criteria.create(Grade.class).add(Restrictions.eq("sid", sid)));
    int len = c.getColumnCount();
    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        for (int i = 0; i < len; i++) {
            System.out.println(c.getColumnName(i) + "=" + c.getString(i));
        }
    }
    Criteria criteria = Criteria
            .create(Student.class, "s")
            .addChild(Grade.class, "g", Criteria.LEFT_JOIN,
                    Restrictions.eqProperty("s.id", "g.sid"))
            .setProjection(true)
            .addChild(Course.class, "c", Criteria.LEFT_JOIN,
                    Restrictions.eqProperty("g.cid", "c.id"))
            .setProjection(true).add(Restrictions.eq("g.sid", sid));
    
    List<Object[]> list = ExampleContentProvider.getSession().listAll(
            criteria);
    adapter.setDataList(list);
    adapter.notifyDataSetChanged();
    return adapter;
}
 
Example 4
Source File: BaseDB.java    From Android_framework with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 查<br/>
 * 使用范例:query("city like ? or city=?", new String[]{"shangh", "beijing"}, "district", "sum(people)>10", "GDP", "1000"),
 * 作用为查找城市中像"shangh"和等于beijing的城市,并且按照district排序,统计所有区总人数大于10万,并且区之间按照GDP排序,显示前1000条信息,该函数的
 * 使用与正常的sql语句一样
 */
public ArrayList<HashMap<String, String>> query(String selection, String[] selectionArgs,
                                                String groupBy, String having, String orderBy, String limit){
    ArrayList<HashMap<String, String>> result = new ArrayList<>();
    synchronized (lock){
        try {
            Cursor cursor = mDb.query(mTable, null, selection, selectionArgs, groupBy, having, orderBy, limit);
            int length = cursor.getColumnCount();
            while (cursor.moveToNext()){
                HashMap<String, String> value = new HashMap<>();
                for (int i=0; i<length; i++){
                    value.put(cursor.getColumnName(i), cursor.getString(i));
                }
                result.add(value);
            }
            if (result.size() == 0)
                result = null;
        }catch (Exception e){
            e.printStackTrace();
            result = null;
        }
    }
    return result;
}
 
Example 5
Source File: DBUtils.java    From DoraemonKit with Apache License 2.0 6 votes vote down vote up
/** 是否需要升级表 */
public static boolean isNeedUpgradeTable(SQLiteDatabase db, TableEntity table) {
    if (!isTableExists(db, table.tableName)) return true;

    Cursor cursor = db.rawQuery("select * from " + table.tableName, null);
    if (cursor == null) return false;
    try {
        int columnCount = table.getColumnCount();
        if (columnCount == cursor.getColumnCount()) {
            for (int i = 0; i < columnCount; i++) {
                if (table.getColumnIndex(cursor.getColumnName(i)) == -1) {
                    return true;
                }
            }
        } else {
            return true;
        }
        return false;
    } finally {
        cursor.close();
    }
}
 
Example 6
Source File: SqliteStorageManager.java    From gsn with GNU General Public License v3.0 6 votes vote down vote up
public DataField[] tableToStructure(CharSequence tableName) throws SQLException {
	StringBuilder sb = new StringBuilder("select * from ").append(tableName).append(" limit 1");
	Cursor cursor = database.rawQuery(sb.toString(), new String[]{});
	boolean c = cursor.moveToFirst();
	ArrayList<DataField> toReturnArr = new ArrayList<DataField>();
	for (int i = 0; i < cursor.getColumnCount(); i++) {
		String colName = cursor.getColumnName(i);
		if (colName.equalsIgnoreCase("_id") || colName.equalsIgnoreCase("timed"))
			continue;
		int colType = Cursor.FIELD_TYPE_STRING;
		if (c) { //can only get type from data
			colType = cursor.getType(i);
		}
		byte colTypeInGSN = convertLocalTypeToGSN(colType);
		toReturnArr.add(new DataField(colName, colTypeInGSN));
	}
	return toReturnArr.toArray(new DataField[]{});

}
 
Example 7
Source File: ExportBackupService.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
private static void appendValues(final Cursor cursor, final StringBuilder builder, final int skipColumn) {
    builder.append("(");
    for (int i = 0; i < cursor.getColumnCount(); ++i) {
        if (i == skipColumn) {
            continue;
        }
        if (i != 0) {
            builder.append(',');
        }
        final String value = cursor.getString(i);
        if (value == null) {
            builder.append("NULL");
        } else if (value.matches("[0-9]+")) {
            builder.append(value);
        } else {
            DatabaseUtils.appendEscapedSQLString(builder, value);
        }
    }
    builder.append(")");

}
 
Example 8
Source File: ModelInflater.java    From QuantumFlux with Apache License 2.0 6 votes vote down vote up
public static <T> T inflate(Cursor cursor, TableDetails tableDetails) {
    T dataModelObject;

    try {
        dataModelObject = (T) tableDetails.createNewModelInstance();
    } catch (Exception ex) {
        throw new QuantumFluxException("Could not create a new instance of data model object: " + tableDetails.getTableName());
    }

    for (int i = 0; i < cursor.getColumnCount(); i++) {
        String columnName = cursor.getColumnName(i);
        TableDetails.ColumnDetails columnDetails = tableDetails.findColumn(columnName);
        inflateColumn(cursor, dataModelObject, columnDetails, i);

    }

    return dataModelObject;
}
 
Example 9
Source File: Matchers.java    From Kore with Apache License 2.0 6 votes vote down vote up
public static Matcher<Object> withItemContent(final Matcher<String> textMatcher) {
    return new BoundedMatcher<Object, Cursor>(Cursor.class) {
        @Override
        protected boolean matchesSafely(Cursor item) {
            for (int i = 0; i < item.getColumnCount();i++) {
                switch (item.getType(i)) {
                    case Cursor.FIELD_TYPE_STRING:
                        if (CursorMatchers.withRowString(i, textMatcher).matches(item))
                            return true;
                        break;
                }
            }
            return false;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("withItemContent: ");
            textMatcher.describeTo(description);
        }
    };
}
 
Example 10
Source File: Logger.java    From Pedometer with Apache License 2.0 5 votes vote down vote up
public static void log(final Cursor c) {
    if (!BuildConfig.DEBUG) return;
    c.moveToFirst();
    String title = "";
    for (int i = 0; i < c.getColumnCount(); i++)
        title += c.getColumnName(i) + "\t| ";
    log(title);
    while (!c.isAfterLast()) {
        title = "";
        for (int i = 0; i < c.getColumnCount(); i++)
            title += c.getString(i) + "\t| ";
        log(title);
        c.moveToNext();
    }
}
 
Example 11
Source File: Recipe.java    From search-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Static helper method for populating attributes from a database cursor.
 *
 * @param cursor The cursor returned from a database query.
 * @return A new {@link com.recipe_app.client.Recipe.Step} object with all attributes populated.
 */
public static Step fromCursor(Cursor cursor) {
    Step step = new Step();
    for (int c=0; c<cursor.getColumnCount(); c++) {
        String columnName = cursor.getColumnName(c);
        if (columnName.equals(RecipeInstructionsTable.PHOTO_COLUMN)) {
            step.setPhoto(cursor.getString(c));
        } else if (columnName.equals(RecipeInstructionsTable.DESCRIPTION_COLUMN)) {
            step.setDescription(cursor.getString(c));
        }
    }
    return step;
}
 
Example 12
Source File: Recipe.java    From search-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Static helper method for populating attributes from a database cursor.
 *
 * @param cursor The cursor returned from a database query.
 * @return A new {@link com.recipe_app.client.Recipe.Ingredient} object with all attributes populated.
 */
public static Ingredient fromCursor(Cursor cursor) {
    Ingredient ingredient = new Ingredient();
    for (int c=0; c<cursor.getColumnCount(); c++) {
        String columnName = cursor.getColumnName(c);
        if (columnName.equals(RecipeIngredientTable.AMOUNT_COLUMN)) {
            ingredient.setAmount(cursor.getString(c));
        } else if (columnName.equals(RecipeIngredientTable.DESCRIPTION_COLUMN)) {
            ingredient.setDescription(cursor.getString(c));
        }
    }
    return ingredient;
}
 
Example 13
Source File: TableInfo.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
private static Map<String, Column> readColumns(SupportSQLiteDatabase database,
        String tableName) {
    Cursor cursor = database
            .query("PRAGMA table_info(`" + tableName + "`)");
    //noinspection TryFinallyCanBeTryWithResources
    Map<String, Column> columns = new HashMap<>();
    try {
        if (cursor.getColumnCount() > 0) {
            int nameIndex = cursor.getColumnIndex("name");
            int typeIndex = cursor.getColumnIndex("type");
            int notNullIndex = cursor.getColumnIndex("notnull");
            int pkIndex = cursor.getColumnIndex("pk");
            int defaultValueIndex = cursor.getColumnIndex("dflt_value");

            while (cursor.moveToNext()) {
                final String name = cursor.getString(nameIndex);
                final String type = cursor.getString(typeIndex);
                final boolean notNull = 0 != cursor.getInt(notNullIndex);
                final int primaryKeyPosition = cursor.getInt(pkIndex);
                final String defaultValue = cursor.getString(defaultValueIndex);
                columns.put(name,
                        new Column(name, type, notNull, primaryKeyPosition, defaultValue,
                                CREATED_FROM_DATABASE));
            }
        }
    } finally {
        cursor.close();
    }
    return columns;
}
 
Example 14
Source File: Recipe.java    From io2015-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Static helper method for populating attributes from a database cursor.
 *
 * @param cursor The cursor returned from a database query.
 * @return A new {@link com.recipe_app.client.Recipe.Step} object with all attributes populated.
 */
public static Step fromCursor(Cursor cursor) {
    Step step = new Step();
    for (int c=0; c<cursor.getColumnCount(); c++) {
        String columnName = cursor.getColumnName(c);
        if (columnName.equals(RecipeInstructionsTable.PHOTO_COLUMN)) {
            step.setPhoto(cursor.getString(c));
        } else if (columnName.equals(RecipeInstructionsTable.DESCRIPTION_COLUMN)) {
            step.setDescription(cursor.getString(c));
        }
    }
    return step;
}
 
Example 15
Source File: Utils.java    From easyDAO with Apache License 2.0 4 votes vote down vote up
public static <T extends BaseEntity> List<T> cursor2Entity(Class<T> clazz, Cursor cursor) throws DBException {
    List<T> objList = new ArrayList<>();
    Field[] fields = getDeclaredField(clazz);
    try {
        if (cursor.moveToFirst()) {
            while (!cursor.isAfterLast()) {
                T obj = clazz.newInstance();

                for (int i = 0; i < cursor.getColumnCount(); i++) {
                    String strColName = cursor.getColumnName(i);
                    for (Field field : fields) {
                        if (field.getName().equals(strColName)) {
                            strColName = toUpperCaseFirstOne(strColName);
                            if (cursor.getType(i) == Cursor.FIELD_TYPE_NULL) {
                                continue;
                            } else if (cursor.getType(i) == Cursor.FIELD_TYPE_FLOAT) {
                                clazz.getMethod("set" + strColName, field.getType()).invoke(obj,
                                        cursor.getFloat(i));
                            } else if (cursor.getType(i) == Cursor.FIELD_TYPE_INTEGER) {
                                if (field.getGenericType().toString().equals("class java.lang.Boolean")
                                        || field.getGenericType().toString().equals("boolean")) {
                                    // e.g. boolean isOk; public boolean isOk(){ return isOk; }   public void setOk(){}
                                    clazz.getMethod("set" + strColName.replaceFirst("Is", ""), field.getType()).invoke(obj,
                                            cursor.getInt(i) == 1 ? true : false);
                                } else if (field.getGenericType().toString().equals("class java.lang.Integer")
                                        || field.getGenericType().toString().equals("int")) {
                                    clazz.getMethod("set" + strColName, field.getType()).invoke(obj,
                                            cursor.getInt(i));
                                } else if (field.getGenericType().toString().equals("class java.lang.Long")
                                        || field.getGenericType().toString().equals("long")) {
                                    clazz.getMethod("set" + strColName, field.getType()).invoke(obj,
                                            (long) cursor.getInt(i));
                                } else if (field.getGenericType().toString().equals("class java.lang.Short")
                                        || field.getGenericType().toString().equals("short")) {
                                    clazz.getMethod("set" + strColName, field.getType()).invoke(obj,
                                            (short) cursor.getInt(i));
                                } else if (field.getGenericType().toString().equals("class java.lang.Byte")
                                        || field.getGenericType().toString().equals("byte")) {
                                    clazz.getMethod("set" + strColName, field.getType()).invoke(obj,
                                            (byte) cursor.getInt(i));
                                }
                            } else if (cursor.getType(i) == Cursor.FIELD_TYPE_STRING) {
                                clazz.getMethod("set" + strColName, field.getType()).invoke(obj,
                                        cursor.getString(i));
                            } else if (cursor.getType(i) == Cursor.FIELD_TYPE_BLOB) {
                                clazz.getMethod("set" + strColName, field.getType()).invoke(obj,
                                        cursor.getBlob(i));
                            } else {
                                throw new DBException(null);
                            }
                            break;
                        }
                    }
                }
                objList.add(obj);
                cursor.moveToNext();
            }
            return objList;
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new DBException(null);
    }
    return objList;
}
 
Example 16
Source File: DbConnection.java    From Ecommerce-Morningmist-Android with Creative Commons Zero v1.0 Universal 4 votes vote down vote up
public ArrayList<HashMap<String, String>> retrieveDB() {

		Cursor cursor = database.query(MainActivity.DB_TABLE, MainActivity.DB_ALL_COL, null, null, null, null, null);

		ArrayList<HashMap<String, String>> arrRet = new ArrayList<HashMap<String,String>>();

		cursor.moveToFirst();
		while(!cursor.isAfterLast()) {

			HashMap<String, String> mapRet = new HashMap<String, String>();
			for(int j = 0; j < cursor.getColumnCount(); j++) {

				String key = cursor.getColumnName(j);
				String value = cursor.getString(j);
				mapRet.put(key, value);

			}
			arrRet.add(mapRet);

		}

		return arrRet;

	}
 
Example 17
Source File: TransactionsDAO.java    From fingen with Apache License 2.0 4 votes vote down vote up
private Transaction cursorToTransaction(Cursor cursor) {
    Transaction transaction = new Transaction(-1);

    transaction.setID(cursor.getLong(mColumnIndexes.get(C_ID)));
    transaction.setDateTime(new Date(cursor.getLong(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_DATETIME))));
    transaction.setAccountID(cursor.getLong(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_SRCACCOUNT)));
    transaction.setPayeeID(cursor.getLong(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_PAYEE)));
    transaction.setCategoryID(cursor.getLong(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_CATEGORY)));
    transaction.setAmount(new BigDecimal(cursor.getDouble(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_AMOUNT))), Transaction.TRANSACTION_TYPE_UNDEFINED);
    transaction.setProjectID(cursor.getLong(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_PROJECT)));
    transaction.setDepartmentID(cursor.getLong(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_DEPARTMENT)));
    transaction.setLocationID(cursor.getLong(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_LOCATION)));
    transaction.setComment(cursor.getString(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_COMMENT)));
    transaction.setFile(cursor.getString(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_FILE)));
    transaction.setDestAccountID(cursor.getLong(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_DESTACCOUNT)));
    transaction.setExchangeRate(new BigDecimal(cursor.getDouble(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_EXCHANGERATE))));
    transaction.setAutoCreated(cursor.getInt(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_AUTOCREATED)) == 1);
    transaction.setLat(cursor.getDouble(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_LAT)));
    transaction.setLon(cursor.getDouble(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_LON)));
    transaction.setAccuracy(cursor.getInt(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_ACCURACY)));
    transaction.setSimpleDebtID(cursor.getLong(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_SIMPLEDEBT)));
    transaction.setFN(cursor.getLong(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_FN)));
    transaction.setFD(cursor.getLong(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_FD)));
    transaction.setFP(cursor.getLong(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_FP)));

    if (cursor.getInt(mColumnIndexes.get(DBHelper.C_LOG_TRANSACTIONS_SPLIT)) == 1) {
        List<ProductEntry> entries = new ArrayList<>();
        for (IAbstractModel entry : mProductEntrysDAO.getAllEntriesOfTransaction(transaction.getID(), false)) {
            entries.add((ProductEntry) entry);
        }
        transaction.setProductEntries(entries);
    }

    if (cursor.getColumnCount() > mColumnIndexes.size()) {
        transaction.setFromAccountBalance(new BigDecimal(cursor.getDouble(mColumnIndexes.size())));
        transaction.setToAccountBalance(new BigDecimal(cursor.getDouble(mColumnIndexes.size() + 1)));
    }

    if (transaction.getDestAccountID() >= 0) {
        transaction.setTransactionType(Transaction.TRANSACTION_TYPE_TRANSFER);
    }

    transaction = (Transaction) DBHelper.getSyncDataFromCursor(transaction, cursor, mColumnIndexes);

    return transaction;
}
 
Example 18
Source File: Repo.java    From fdroidclient with GNU General Public License v3.0 4 votes vote down vote up
public Repo(Cursor cursor) {

        checkCursorPosition(cursor);

        for (int i = 0; i < cursor.getColumnCount(); i++) {
            switch (cursor.getColumnName(i)) {
                case Cols._ID:
                    id = cursor.getInt(i);
                    break;
                case Cols.LAST_ETAG:
                    lastetag = cursor.getString(i);
                    break;
                case Cols.ADDRESS:
                    address = cursor.getString(i);
                    break;
                case Cols.DESCRIPTION:
                    description = cursor.getString(i);
                    break;
                case Cols.FINGERPRINT:
                    fingerprint = cursor.getString(i);
                    break;
                case Cols.IN_USE:
                    inuse = cursor.getInt(i) == 1;
                    break;
                case Cols.LAST_UPDATED:
                    String dateString = cursor.getString(i);
                    lastUpdated = Utils.parseTime(dateString, Utils.parseDate(dateString, null));
                    break;
                case Cols.MAX_AGE:
                    maxage = cursor.getInt(i);
                    break;
                case Cols.VERSION:
                    version = cursor.getInt(i);
                    break;
                case Cols.NAME:
                    name = cursor.getString(i);
                    break;
                case Cols.SIGNING_CERT:
                    signingCertificate = cursor.getString(i);
                    break;
                case Cols.PRIORITY:
                    priority = cursor.getInt(i);
                    break;
                case Cols.IS_SWAP:
                    isSwap = cursor.getInt(i) == 1;
                    break;
                case Cols.USERNAME:
                    username = cursor.getString(i);
                    break;
                case Cols.PASSWORD:
                    password = cursor.getString(i);
                    break;
                case Cols.TIMESTAMP:
                    timestamp = cursor.getLong(i);
                    break;
                case Cols.ICON:
                    icon = cursor.getString(i);
                    break;
                case Cols.MIRRORS:
                    mirrors = Utils.parseCommaSeparatedString(cursor.getString(i));
                    break;
                case Cols.USER_MIRRORS:
                    userMirrors = Utils.parseCommaSeparatedString(cursor.getString(i));
                    break;
                case Cols.DISABLED_MIRRORS:
                    disabledMirrors = Utils.parseCommaSeparatedString(cursor.getString(i));
                    break;
                case Cols.PUSH_REQUESTS:
                    pushRequests = cursor.getInt(i);
                    break;
            }
        }
    }
 
Example 19
Source File: NGWVectorLayer.java    From android_maplib with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected String cursorToJson(Cursor cursor)
        throws JSONException, IOException
{
    JSONObject rootObject = new JSONObject();
    if (0 != (mSyncType & Constants.SYNC_ATTRIBUTES)) {
        JSONObject valueObject = new JSONObject();
        for (int i = 0; i < cursor.getColumnCount(); i++) {
            String name = cursor.getColumnName(i);
            if (name.equals(Constants.FIELD_ID) || name.equals(Constants.FIELD_GEOM)) {
                continue;
            }

            Field field = mFields.get(cursor.getColumnName(i));
            if (null == field) {
                continue;
            }

            switch (field.getType()) {
                case GeoConstants.FTReal:
                    valueObject.put(name, cursor.getFloat(i));
                    break;
                case GeoConstants.FTInteger:
                    valueObject.put(name, cursor.getInt(i));
                    break;
                case GeoConstants.FTString:
                    String stringVal = cursor.getString(i);
                    if (null != stringVal && !stringVal.equals("null")) {
                        valueObject.put(name, stringVal);
                    }
                    break;
                case GeoConstants.FTDateTime:
                    TimeZone timeZoneDT = TimeZone.getDefault();
                    timeZoneDT.setRawOffset(0); // set to UTC
                    Calendar calendarDT = Calendar.getInstance(timeZoneDT);
                    calendarDT.setTimeInMillis(cursor.getLong(i));
                    JSONObject jsonDateTime = new JSONObject();
                    jsonDateTime.put("year", calendarDT.get(Calendar.YEAR));
                    jsonDateTime.put("month", calendarDT.get(Calendar.MONTH) + 1);
                    jsonDateTime.put("day", calendarDT.get(Calendar.DAY_OF_MONTH));
                    jsonDateTime.put("hour", calendarDT.get(Calendar.HOUR_OF_DAY));
                    jsonDateTime.put("minute", calendarDT.get(Calendar.MINUTE));
                    jsonDateTime.put("second", calendarDT.get(Calendar.SECOND));
                    valueObject.put(name, jsonDateTime);
                    break;
                case GeoConstants.FTDate:
                    TimeZone timeZoneD = TimeZone.getDefault();
                    timeZoneD.setRawOffset(0); // set to UTC
                    Calendar calendarD = Calendar.getInstance(timeZoneD);
                    calendarD.setTimeInMillis(cursor.getLong(i));
                    JSONObject jsonDate = new JSONObject();
                    jsonDate.put("year", calendarD.get(Calendar.YEAR));
                    jsonDate.put("month", calendarD.get(Calendar.MONTH) + 1);
                    jsonDate.put("day", calendarD.get(Calendar.DAY_OF_MONTH));
                    valueObject.put(name, jsonDate);
                    break;
                case GeoConstants.FTTime:
                    TimeZone timeZoneT = TimeZone.getDefault();
                    timeZoneT.setRawOffset(0); // set to UTC
                    Calendar calendarT = Calendar.getInstance(timeZoneT);
                    calendarT.setTimeInMillis(cursor.getLong(i));
                    JSONObject jsonTime = new JSONObject();
                    jsonTime.put("hour", calendarT.get(Calendar.HOUR_OF_DAY));
                    jsonTime.put("minute", calendarT.get(Calendar.MINUTE));
                    jsonTime.put("second", calendarT.get(Calendar.SECOND));
                    valueObject.put(name, jsonTime);
                    break;
                default:
                    break;
            }
        }
        rootObject.put(NGWUtil.NGWKEY_FIELDS, valueObject);
    }

    if (0 != (mSyncType & Constants.SYNC_GEOMETRY)) {
        //may be found geometry in cache by id is faster
        GeoGeometry geometry = GeoGeometryFactory.fromBlob(
                cursor.getBlob(cursor.getColumnIndex(Constants.FIELD_GEOM)));

        geometry.setCRS(GeoConstants.CRS_WEB_MERCATOR);
        if (mCRS != GeoConstants.CRS_WEB_MERCATOR)
            geometry.project(mCRS);

        rootObject.put(NGWUtil.NGWKEY_GEOM, geometry.toWKT(true));
        //rootObject.put("id", cursor.getLong(cursor.getColumnIndex(FIELD_ID)));
    }

    return rootObject.toString();
}
 
Example 20
Source File: CursorHelper.java    From KJFrameForAndroid with Apache License 2.0 4 votes vote down vote up
/**
 * 获取一个已保存的JavaBean对象
 * 
 * @param cursor
 *            游标
 * @param clazz
 *            JavaBean.class
 * @param db
 *            KJDB对象引用
 * @return
 */
public static <T> T getEntity(Cursor cursor, Class<T> clazz, KJDB db) {
    try {
        if (cursor != null) {
            // 读取表信息
            TableInfo table = TableInfo.get(clazz);
            // 读取列数
            int columnCount = cursor.getColumnCount();
            if (columnCount > 0) {
                // 创建JavaBean对象
                T entity = clazz.newInstance();
                // 设置JavaBean的每一个属性
                for (int i = 0; i < columnCount; i++) {
                    String column = cursor.getColumnName(i);
                    Property property = table.propertyMap.get(column);
                    if (property != null) {
                        property.setValue(entity, cursor.getString(i));
                    } else {
                        if (table.getId().getColumn().equals(column)) {
                            table.getId().setValue(entity,
                                    cursor.getString(i));
                        }
                    }

                }
                /**
                 * 处理OneToMany的lazyLoad形式
                 */
                for (OneToMany oneToManyProp : table.oneToManyMap.values()) {
                    if (oneToManyProp.getDataType() == OneToManyLazyLoader.class) {
                        OneToManyLazyLoader oneToManyLazyLoader = new OneToManyLazyLoader(
                                entity, clazz, oneToManyProp.getOneClass(),
                                db);
                        oneToManyProp.setValue(entity, oneToManyLazyLoader);
                    }
                }

                /**
                 * 处理ManyToOne的lazyLoad形式
                 */
                for (ManyToOne manyToOneProp : table.manyToOneMap.values()) {
                    if (manyToOneProp.getDataType() == ManyToOneLazyLoader.class) {
                        ManyToOneLazyLoader manyToOneLazyLoader = new ManyToOneLazyLoader(
                                entity, clazz,
                                manyToOneProp.getManyClass(), db);
                        manyToOneProp.setValue(entity, manyToOneLazyLoader);
                    }
                }
                return entity;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}