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

The following examples show how to use android.database.Cursor#getDouble() . 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: LitePalTestCase.java    From LitePal with Apache License 2.0 6 votes vote down vote up
protected Cellphone getCellPhone(long id) {
	Cellphone cellPhone = null;
	Cursor cursor = Connector.getDatabase().query(getTableName(Cellphone.class), null, "id = ?",
			new String[] { String.valueOf(id) }, null, null, null);
	if (cursor.moveToFirst()) {
		cellPhone = new Cellphone();
		double newPrice = cursor.getDouble(cursor.getColumnIndexOrThrow("price"));
		char inStock = cursor.getString(cursor.getColumnIndexOrThrow("instock")).charAt(0);
		String brand = cursor.getString(cursor.getColumnIndexOrThrow("brand"));
		cellPhone.setBrand(brand);
		cellPhone.setInStock(inStock);
		cellPhone.setPrice(newPrice);
	}
	cursor.close();
	return cellPhone;
}
 
Example 2
Source File: LocationService.java    From Androzic with GNU General Public License v3.0 6 votes vote down vote up
public Track getTrack(long limit)
{
	if (trackDB == null)
		openDatabase();
	Track track = new Track();
	if (trackDB == null)
		return track;
	String limitStr = limit > 0 ? " LIMIT " + limit : "";
	Cursor cursor = trackDB.rawQuery("SELECT * FROM track ORDER BY _id DESC" + limitStr, null);
	for (boolean hasItem = cursor.moveToLast(); hasItem; hasItem = cursor.moveToPrevious())
	{
		double latitude = cursor.getDouble(cursor.getColumnIndex("latitude"));
		double longitude = cursor.getDouble(cursor.getColumnIndex("longitude"));
		double elevation = cursor.getDouble(cursor.getColumnIndex("elevation"));
		double speed = cursor.getDouble(cursor.getColumnIndex("speed"));
		double bearing = cursor.getDouble(cursor.getColumnIndex("track"));
		double accuracy = cursor.getDouble(cursor.getColumnIndex("accuracy"));
		int code = cursor.getInt(cursor.getColumnIndex("code"));
		long time = cursor.getLong(cursor.getColumnIndex("datetime"));
		track.addPoint(code == 0, latitude, longitude, elevation, speed, bearing, accuracy, time);
	}
	cursor.close();
	return track;
}
 
Example 3
Source File: EditLocationActivity.java    From PressureNet with GNU General Public License v3.0 5 votes vote down vote up
public void populateFields() {
	// get the row id from the intent and load
	// the correct data
	Intent intent = getIntent();
	if (intent != null) {
		try {
			long rowId = intent.getLongExtra("rowId", -1);
			if (rowId == -1) {
				return;
			}

			PnDb pn = new PnDb(getApplicationContext());
			pn.open();
			Cursor c = pn.fetchLocation(rowId);
			pn.close();

			initialName = c.getString(1);
			initialLatitude = c.getDouble(2);
			initialLongitude = c.getDouble(3);
			initialRowId = rowId;

			editLocationName.setText(initialName);
			editLatitude.setText(initialLatitude + "");
			editLongitude.setText(initialLongitude + "");

		} catch (Exception e) {
			// meh
		}
	}

}
 
Example 4
Source File: UserDaoImpl.java    From AndroidTranslucentUI with Apache License 2.0 5 votes vote down vote up
/**
 * ��ѯ�����û�
 */
@Override
public List<UserBean> find() {
	// TODO Auto-generated method stub
	List<UserBean> userBeans = null;  
       SQLiteDatabase db = dbHelper.getReadableDatabase();  

       Cursor cursor = db.query(AppConstants.TABLE_USER, null, null, null, null, null, null);  
       if(cursor != null){  
       	userBeans = new ArrayList<UserBean>();  
           while(cursor.moveToNext()){  
           	UserBean userBean = new UserBean();  
               String userId = cursor.getString(cursor.getColumnIndex("userId"));  
               String userPassword = cursor.getString(cursor.getColumnIndex("userPassword"));  
               String userNickName = cursor.getString(cursor.getColumnIndex("userNickName"));  
               String userPhone = cursor.getString(cursor.getColumnIndex("userPhone"));  
               String userEmail = cursor.getString(cursor.getColumnIndex("userEmail"));  
               String userImagePath = cursor.getString(cursor.getColumnIndex("userImagePath"));  
               double userLongitude = cursor.getDouble(cursor.getColumnIndex("userLongitude"));  
               double userLatitude = cursor.getDouble(cursor.getColumnIndex("userLatitude"));  
               
               userBean.setUserId(userId);
               userBean.setUserPassword(userPassword);
               userBean.setUserNickName(userNickName);
               userBean.setUserPhone(userPhone);
               userBean.setUserEmail(userEmail);
               userBean.setUserImagePath(userImagePath);
               userBean.setUserLongitude(userLongitude);
               userBean.setUserLatitude(userLatitude);
               
               userBeans.add(userBean);  
           }  
       }  
       return userBeans;
}
 
Example 5
Source File: BoxedTypesFieldsIgnoreNullStorIOSQLiteGetResolver.java    From storio with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@NonNull
public BoxedTypesFieldsIgnoreNull mapFromCursor(@NonNull StorIOSQLite storIOSQLite, @NonNull Cursor cursor) {
    BoxedTypesFieldsIgnoreNull object = new BoxedTypesFieldsIgnoreNull();

    if (!cursor.isNull(cursor.getColumnIndex("field1"))) {
        object.field1 = cursor.getInt(cursor.getColumnIndex("field1")) == 1;
    }
    if (!cursor.isNull(cursor.getColumnIndex("field2"))) {
        object.field2 = cursor.getShort(cursor.getColumnIndex("field2"));
    }
    if (!cursor.isNull(cursor.getColumnIndex("field3"))) {
        object.field3 = cursor.getInt(cursor.getColumnIndex("field3"));
    }
    if (!cursor.isNull(cursor.getColumnIndex("field4"))) {
        object.field4 = cursor.getLong(cursor.getColumnIndex("field4"));
    }
    if (!cursor.isNull(cursor.getColumnIndex("field5"))) {
        object.field5 = cursor.getFloat(cursor.getColumnIndex("field5"));
    }
    if (!cursor.isNull(cursor.getColumnIndex("field6"))) {
        object.field6 = cursor.getDouble(cursor.getColumnIndex("field6"));
    }

    return object;
}
 
Example 6
Source File: StatsResult.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public double getTotal_insulin() {
    if (total_insulin < 0) {
        Cursor cursor = Cache.openDatabase().rawQuery("select sum(insulin) from treatments  where timestamp >= " + from + " AND timestamp <= " + to, null);
        cursor.moveToFirst();
        total_insulin = cursor.getDouble(0);
        cursor.close();
    }
    return total_insulin;
}
 
Example 7
Source File: MapsActivity.java    From Finder with GNU General Public License v3.0 5 votes vote down vote up
private void trackRedraw() {
    Cursor query =  db.query("tracking_table", new String[] {"_id", "lat", "lon", "speed", "date"}, "track_id = ?", new String[] {String.valueOf(track_id)}, null, null, "_id ASC");

    Cursor last_point =  db.rawQuery("SELECT lat, lon, _id FROM tracking_table WHERE _id = (SELECT MAX(_id) FROM tracking_table WHERE track_id = ?)", new String[] {String.valueOf(track_id)});
    last_point.moveToFirst();
    Double lat = last_point.getDouble(0);
    Double lon = last_point.getDouble(1);
    last_point.close();

    //zoom to latest point, because BoundBox don't work in OsmDroid library (this is known lib bug)
    mapController.setCenter(new GeoPoint(lat, lon));
    mapController.setZoom(15d);
    List<GeoPoint> track = new ArrayList<>();

    while (query.moveToNext()) {
        GeoPoint gp = new GeoPoint(query.getDouble(1), query.getDouble(2));
        track.add(gp);
        Marker marker = new Marker(map);
        marker.setPosition(gp);
        marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
        map.getOverlays().add(marker);
        marker.setTitle(getString(R.string.date_time, query.getString(4), query.getFloat(3)));
    }
    query.close();
    line.setPoints(track);
    GeoPoint center = new GeoPoint(lat, lon);
    mapController.setCenter(center);
}
 
Example 8
Source File: LocalVideo.java    From medialibrary with Apache License 2.0 5 votes vote down vote up
private void loadFromCursor(Cursor cursor) {
    id = cursor.getInt(INDEX_ID);
    caption = cursor.getString(INDEX_CAPTION);
    mimeType = cursor.getString(INDEX_MIME_TYPE);
    latitude = cursor.getDouble(INDEX_LATITUDE);
    longitude = cursor.getDouble(INDEX_LONGITUDE);
    dateTakenInMs = cursor.getLong(INDEX_DATE_TAKEN);
    dateAddedInSec = cursor.getLong(INDEX_DATE_ADDED);
    dateModifiedInSec = cursor.getLong(INDEX_DATE_MODIFIED);
    filePath = cursor.getString(INDEX_DATA);
    durationInSec = cursor.getInt(INDEX_DURATION) / 1000;
    bucketId = cursor.getInt(INDEX_BUCKET_ID);
    fileSize = cursor.getLong(INDEX_SIZE);
    parseResolution(cursor.getString(INDEX_RESOLUTION));
}
 
Example 9
Source File: RealAttribute.java    From droitatedDB with Apache License 2.0 5 votes vote down vote up
@Override
public Object getNonNullValueFromCursor(final Cursor originalCursor) {
    if (Double.class.isAssignableFrom(type()) || double.class.isAssignableFrom(type())) {
        return originalCursor.getDouble(columnIndex());
    }
    return originalCursor.getFloat(columnIndex());
}
 
Example 10
Source File: LitePalTestCase.java    From LitePal with Apache License 2.0 5 votes vote down vote up
protected Computer getComputer(long id) {
	Computer computer = null;
	Cursor cursor = Connector.getDatabase().query(getTableName(Computer.class), null, "id = ?",
			new String[] { String.valueOf(id) }, null, null, null);
	if (cursor.moveToFirst()) {
		computer = new Computer("", 0);
		double newPrice = cursor.getDouble(cursor.getColumnIndexOrThrow("price"));
		String brand = cursor.getString(cursor.getColumnIndexOrThrow("brand"));
		computer.setBrand(brand);
		computer.setPrice(newPrice);
	}
	cursor.close();
	return computer;
}
 
Example 11
Source File: ProductAdapter.java    From restaurant-bot with GNU General Public License v3.0 5 votes vote down vote up
public ArrayList<Product> readData(){

        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<Product> data = new ArrayList<Product>();

        String[] projection = {
                PRODUCT_ID,
                PRODUCT_TITLE,
                PRODUCT_DESCRIPTION,
                PRODUCT_COST,
                PRODUCT_IMAGE,
                PRODUCT_RATING,
                PRODUCT_TOTAL_COST,
                PRODUCT_TOTAL_ORDER
        };

        String sortOrder =
               PRODUCT_TITLE + " ASC";

        Cursor c = db.query(
                TABLE_PRODUCT,
                projection,
                null,
                null,
                null,
                null,
                sortOrder
        );

        while(c.moveToNext()){
            Product product = new Product(c.getString(1),c.getString(2),c.getDouble(3),c.getString(4),c.getDouble(6),c.getInt(7));
            product.setRatinng(c.getDouble(5));
            data.add(product);
        };
        c.close();
        db.close();
        return data;
    }
 
Example 12
Source File: DetailFragment.java    From Advanced_Android_Development with Apache License 2.0 4 votes vote down vote up
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (data != null && data.moveToFirst()) {
        ViewParent vp = getView().getParent();
        if ( vp instanceof CardView ) {
            ((View)vp).setVisibility(View.VISIBLE);
        }

        // Read weather condition ID from cursor
        int weatherId = data.getInt(COL_WEATHER_CONDITION_ID);

        if ( Utility.usingLocalGraphics(getActivity()) ) {
            mIconView.setImageResource(Utility.getArtResourceForWeatherCondition(weatherId));
        } else {
            // Use weather art image
            Glide.with(this)
                    .load(Utility.getArtUrlForWeatherCondition(getActivity(), weatherId))
                    .error(Utility.getArtResourceForWeatherCondition(weatherId))
                    .crossFade()
                    .into(mIconView);
        }

        // Read date from cursor and update views for day of week and date
        long date = data.getLong(COL_WEATHER_DATE);
        String dateText = Utility.getFullFriendlyDayString(getActivity(),date);
        mDateView.setText(dateText);

        // Get description from weather condition ID
        String description = Utility.getStringForWeatherCondition(getActivity(), weatherId);
        mDescriptionView.setText(description);
        mDescriptionView.setContentDescription(getString(R.string.a11y_forecast, description));

        // For accessibility, add a content description to the icon field. Because the ImageView
        // is independently focusable, it's better to have a description of the image. Using
        // null is appropriate when the image is purely decorative or when the image already
        // has text describing it in the same UI component.
        mIconView.setContentDescription(getString(R.string.a11y_forecast_icon, description));

        // Read high temperature from cursor and update view
        boolean isMetric = Utility.isMetric(getActivity());

        double high = data.getDouble(COL_WEATHER_MAX_TEMP);
        String highString = Utility.formatTemperature(getActivity(), high);
        mHighTempView.setText(highString);
        mHighTempView.setContentDescription(getString(R.string.a11y_high_temp, highString));

        // Read low temperature from cursor and update view
        double low = data.getDouble(COL_WEATHER_MIN_TEMP);
        String lowString = Utility.formatTemperature(getActivity(), low);
        mLowTempView.setText(lowString);
        mLowTempView.setContentDescription(getString(R.string.a11y_low_temp, lowString));

        // Read humidity from cursor and update view
        float humidity = data.getFloat(COL_WEATHER_HUMIDITY);
        mHumidityView.setText(getActivity().getString(R.string.format_humidity, humidity));
        mHumidityView.setContentDescription(getString(R.string.a11y_humidity, mHumidityView.getText()));
        mHumidityLabelView.setContentDescription(mHumidityView.getContentDescription());

        // Read wind speed and direction from cursor and update view
        float windSpeedStr = data.getFloat(COL_WEATHER_WIND_SPEED);
        float windDirStr = data.getFloat(COL_WEATHER_DEGREES);
        mWindView.setText(Utility.getFormattedWind(getActivity(), windSpeedStr, windDirStr));
        mWindView.setContentDescription(getString(R.string.a11y_wind, mWindView.getText()));
        mWindLabelView.setContentDescription(mWindView.getContentDescription());

        // Read pressure from cursor and update view
        float pressure = data.getFloat(COL_WEATHER_PRESSURE);
        mPressureView.setText(getString(R.string.format_pressure, pressure));
        mPressureView.setContentDescription(getString(R.string.a11y_pressure, mPressureView.getText()));
        mPressureLabelView.setContentDescription(mPressureView.getContentDescription());

        // We still need this for the share intent
        mForecast = String.format("%s - %s - %s/%s", dateText, description, high, low);

    }
    AppCompatActivity activity = (AppCompatActivity)getActivity();
    Toolbar toolbarView = (Toolbar) getView().findViewById(R.id.toolbar);

    // We need to start the enter transition after the data has loaded
    if ( mTransitionAnimation ) {
        activity.supportStartPostponedEnterTransition();

        if ( null != toolbarView ) {
            activity.setSupportActionBar(toolbarView);

            activity.getSupportActionBar().setDisplayShowTitleEnabled(false);
            activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    } else {
        if ( null != toolbarView ) {
            Menu menu = toolbarView.getMenu();
            if ( null != menu ) menu.clear();
            toolbarView.inflateMenu(R.menu.detailfragment);
            finishCreatingMenu(toolbarView.getMenu());
        }
    }
}
 
Example 13
Source File: DataManager.java    From RunMap with Apache License 2.0 4 votes vote down vote up
/**
 * 按日期检索位置信息,以升序形式返回
 * @param dayTime
 * @return
 */
public SparseArray<List<TrackPoint>> readTrackPointFormDataBase(String dayTime) {
    SparseArray<List<TrackPoint>> groupResult = new SparseArray<>();

    SQLiteDatabase db = mLocationDataBase.getReadableDatabase();

    int recordCount = queryRecordCountToday(dayTime);
    for(int i=0;i <= recordCount;i++) {
        String query_sql = "select * from " + LocationDataBase.TABLE_LOCATION
                + " where " + LocationDataBase.FILED_TIME_DAY + " = " + dayTime
            + " and "+ LocationDataBase.FILED_RECORD_COUNT + " = " + i
                + " order by " + LocationDataBase.FILED_TIME_STAMP + " asc ";
        Cursor cursor = db.rawQuery(query_sql, null);
        try {
            while (cursor.moveToNext()) {
                int latitudeIndex = cursor.getColumnIndex(LocationDataBase.FILED_LATITUDE);
                int longitudeIndex = cursor.getColumnIndex(LocationDataBase.FILED_LONGITUDE);
                int timeStampIndex = cursor.getColumnIndex(LocationDataBase.FILED_TIME_STAMP);
                int buildingIndex = cursor.getColumnIndex(LocationDataBase.FILED_BUILD_NAME);
                int countIndex = cursor.getColumnIndex(LocationDataBase.FILED_RECORD_COUNT);
                double latitude = cursor.getDouble(latitudeIndex);
                double longitude = cursor.getDouble(longitudeIndex);
                long timeStamp = Long.valueOf(cursor.getString(timeStampIndex));
                String building = cursor.getString(buildingIndex);
                int count = cursor.getInt(countIndex);
                List<TrackPoint> pointList = groupResult.get(count);
                if (pointList == null) {
                    pointList = new ArrayList<>();
                    groupResult.put(count, pointList);
                }
                TrackPoint point = new TrackPoint(new LatLng(latitude, longitude), building, timeStamp);
                pointList.add(point);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    return groupResult;
}
 
Example 14
Source File: DoubleColumnConverter.java    From android-open-project-demo with Apache License 2.0 4 votes vote down vote up
@Override
public Double getFieldValue(final Cursor cursor, int index) {
    return cursor.isNull(index) ? null : cursor.getDouble(index);
}
 
Example 15
Source File: LocationsFileDbHelper.java    From your-local-weather with GNU General Public License v3.0 4 votes vote down vote up
public Location getLocationById(long id) {
    SQLiteDatabase db = getReadableDatabase();

    String[] projection = {
            LocationsContract.Locations.COLUMN_NAME_ADDRESS,
            LocationsContract.Locations.COLUMN_NAME_ORDER_ID,
            LocationsContract.Locations.COLUMN_NAME_LONGITUDE,
            LocationsContract.Locations.COLUMN_NAME_LATITUDE,
            LocationsContract.Locations.COLUMN_NAME_LOCALE,
            LocationsContract.Locations.COLUMN_NAME_LOCATION_NICKNAME,
            LocationsContract.Locations.COLUMN_NAME_LOCATION_ACCURACY,
            LocationsContract.Locations.COLUMN_NAME_ENABLED,
            LocationsContract.Locations.COLUMN_NAME_LAST_UPDATE_TIME_IN_MS,
            LocationsContract.Locations.COLUMN_NAME_LOCATION_UPDATE_SOURCE,
            LocationsContract.Locations.COLUMN_NAME_ADDRESS_FOUND
    };

    Cursor cursor = null;
    try {
        cursor = db.query(
            LocationsContract.Locations.TABLE_NAME,
            projection,
            LocationsContract.Locations._ID + "=" + id,
            null,
            null,
            null,
            null
        );

        if (!cursor.moveToNext()) {
            return null;
        }

        byte[] cachedAddressBytes = cursor.getBlob(
                cursor.getColumnIndexOrThrow(LocationsContract.Locations.COLUMN_NAME_ADDRESS));
        Address address = null;
        if (cachedAddressBytes != null) {
            address = LocationsDbHelper.getAddressFromBytes(cachedAddressBytes);
        }

        int orderId = cursor.getInt(cursor.getColumnIndexOrThrow(LocationsContract.Locations.COLUMN_NAME_ORDER_ID));
        double longitude = cursor.getDouble(cursor.getColumnIndexOrThrow(LocationsContract.Locations.COLUMN_NAME_LONGITUDE));
        double latitude = cursor.getDouble(cursor.getColumnIndexOrThrow(LocationsContract.Locations.COLUMN_NAME_LATITUDE));
        String locale = cursor.getString(cursor.getColumnIndexOrThrow(LocationsContract.Locations.COLUMN_NAME_LOCALE));
        String nickname = cursor.getString(cursor.getColumnIndexOrThrow(LocationsContract.Locations.COLUMN_NAME_LOCATION_NICKNAME));
        float accuracy = cursor.getFloat(cursor.getColumnIndexOrThrow(LocationsContract.Locations.COLUMN_NAME_LOCATION_ACCURACY));
        long locationUpdateTime = cursor.getLong(cursor.getColumnIndexOrThrow(LocationsContract.Locations.COLUMN_NAME_LAST_UPDATE_TIME_IN_MS));
        String locationSource = cursor.getString(cursor.getColumnIndexOrThrow(LocationsContract.Locations.COLUMN_NAME_LOCATION_UPDATE_SOURCE));
        boolean addressFound = 1 == cursor.getInt(cursor.getColumnIndexOrThrow(LocationsContract.Locations.COLUMN_NAME_ADDRESS_FOUND));
        boolean enabled = 1 == cursor.getInt(cursor.getColumnIndexOrThrow(LocationsContract.Locations.COLUMN_NAME_ENABLED));

        if (locale == null) {
            locale = PreferenceUtil.getLanguage(context);
        }

        return new Location(
                id,
                orderId,
                nickname,
                locale,
                longitude,
                latitude,
                accuracy,
                locationSource,
                locationUpdateTime,
                addressFound,
                enabled,
                address);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
 
Example 16
Source File: TransactionsDAO.java    From fingen with Apache License 2.0 4 votes vote down vote up
/**
 * @param filterListHelper - автоматически добавляет фильтр исключающий закрытые счета
 */
@SuppressWarnings("unchecked")
public synchronized ListSumsByCabbage getGroupedSums(FilterListHelper filterListHelper,
                                                     boolean takeSearchString,
                                                     ArrayList<Long> selectedIDs,
                                                     Context context) {
    //Создаем экземпляр результирующей записи "валюта - сумма"
    ListSumsByCabbage listSumsByCabbage = new ListSumsByCabbage();

    //Получаем актуальный список фильтров
    List<AbstractFilter> filterList = filterListHelper.getFilters();

    if (filterListHelper.getSearchString().isEmpty() || !takeSearchString) {
        createTempTransactionsTable(filterList, context);
    } else {
        createTempTransactionsTable(filterList, Translit.toTranslit(filterListHelper.getSearchString().toLowerCase()).replaceAll("'", "''"), context);
    }

    HashSet<Long> accIDs = FilterManager.getAccountIDsFromFilters(filterList, AccountsDAO.getInstance(context).getAllModelsIDs());
    String accIDsString = TextUtils.join(",", accIDs);

    String selectedTransactionsTable = "";
    if (selectedIDs != null && !selectedIDs.isEmpty()) {
        mDatabase.execSQL("DROP TABLE IF EXISTS temp_sel_Transactions;");
        mDatabase.execSQL("CREATE TEMP TABLE temp_sel_Transactions (_id INTEGER NOT NULL PRIMARY KEY)");
        mDatabase.beginTransaction();
        ContentValues cv = new ContentValues();
        for (Long id : selectedIDs) {
            cv.put("_id", id);
            mDatabase.insert("temp_sel_Transactions", null, cv);
        }
        mDatabase.setTransactionSuccessful();
        mDatabase.endTransaction();
        selectedTransactionsTable = " AS t INNER JOIN temp_sel_Transactions AS st ON t._id = st._id ";
    }

    String sql = "SELECT\n" +
            "c._id,\n" +
            "IFNULL((SELECT TOTAL(CASE WHEN Income = 1 THEN Amount ELSE 0 END) FROM temp_all_Transactions" + selectedTransactionsTable + " WHERE c._id = Currency AND NOT (ExcludeTransfer = 1)), 0) AS InAmountSum,\n" +
            "IFNULL((SELECT TOTAL(CASE WHEN Income = 0 THEN Amount ELSE 0 END) FROM temp_all_Transactions" + selectedTransactionsTable + " WHERE c._id = Currency AND NOT (ExcludeTransfer = 1)), 0) AS OutAmountSum,\n" +
            "IFNULL((SELECT TOTAL(StartBalance) FROM ref_Accounts WHERE Currency = c._id AND _id IN (" + accIDsString + ")), 0) AS StartBalance\n" +
            "FROM ref_Currencies c\n" +
            "ORDER BY c.OrderNumber ASC";
    if (BuildConfig.DEBUG) {
        Log.d(SQLTAG, sql);
    }

    Cursor cursor = mDatabase.rawQuery(sql, null);
    if (cursor != null) {
        try {
            if (cursor.moveToFirst()) {
                SumsByCabbage sumsByCabbage;
                while (!cursor.isAfterLast()) {
                    sumsByCabbage = new SumsByCabbage(cursor.getLong(0),
                            new BigDecimal(cursor.getDouble(1)),
                            new BigDecimal(cursor.getDouble(2)));
                    sumsByCabbage.setStartBalance(new BigDecimal(cursor.getDouble(3)));
                    listSumsByCabbage.getmList().add(sumsByCabbage);
                    cursor.moveToNext();
                }
            }
        } finally {
            cursor.close();
        }
    }

    return listSumsByCabbage;
}
 
Example 17
Source File: TaskDb.java    From SyncManagerAndroid-DemoGoogleTasks with MIT License 4 votes vote down vote up
public static double fieldByNameDouble(Cursor cur, String fldName) {
       return cur.getDouble(cur.getColumnIndex(fldName));
}
 
Example 18
Source File: BarometerNetworkActivity.java    From PressureNet with GNU General Public License v3.0 4 votes vote down vote up
private boolean prepareTemperatureAnimation() {
	if (mMap == null) {
		return false;
	}
	forecastRecents.clear();
	temperatureAnimationMarkerOptions.clear();
	
	if(liveMapForecasts.size()<1) {
		log("app attempting to play temperature animation; size 0, bailing");
		noAnimationResults();
		return false;
	} else {
		animationProgress.setEnabled(true);
		imageButtonPlay.setEnabled(true);
		try {
			imageButtonPlay.setImageAlpha(255);	
		} catch (NoSuchMethodError nsme) {
			log("app could not set image alpha");
		} catch(RuntimeException re) {
			log("my location button error");
		} catch (Exception e) {
			log("unknown imagealphaerror " + e.getMessage());
		}
	}
	
	PnDb db = new PnDb(getApplicationContext());
	db.open();
	for(ForecastLocation location : liveMapForecasts) {
		Cursor forecastCursor = db.getTemperatureForecastsById(location.getLocationID());
		ArrayList<TemperatureForecast> currentLocationTemperatures = new ArrayList<TemperatureForecast>();
		while(forecastCursor.moveToNext()) {
			// id = 1
			String mapStartTime = forecastCursor.getString(2);
			int mapHour = forecastCursor.getInt(3);
			int mapScale = forecastCursor.getInt(4);
			double mapValue = forecastCursor.getDouble(5);
			TemperatureForecast forecast = new TemperatureForecast(location.getLocationID(), mapScale, mapValue, mapStartTime, mapHour);
			forecast.setLatitude(location.getLatitude());
			forecast.setLongitude(location.getLongitude());
			forecast.setContext(getApplicationContext());
			forecast.prepareDisplayValue();
			currentLocationTemperatures.add(forecast);
			// log("forecast temp details " + mapValue + " " + mapStartTime + " " + mapHour);
			forecastRecents.add(forecast);
		}
		location.setTemperatures(currentLocationTemperatures);
		log("location " + location.getLocationID() + " has " + location.getTemperatures().size() + " temperature forecasts");
	}
	
	if(liveMapForecasts.size()>0){
		if(liveMapForecasts.get(0).getTemperatures().size()>0) {
			
			
			
			int animationLength = liveMapForecasts.get(0).getTemperatures().size() - 1;
			activeForecastStartTime = liveMapForecasts.get(0).getTemperatures().get(0).getStartTime();
			animationProgress.setMax(animationLength);
			updateAnimationTime("left", activeForecastStartTime, 0);
			updateAnimationTime("right", activeForecastStartTime, animationLength);
		} 
	} 
	
	db.close();
	
	prepareTemperatureAnimationMarkers(temperatureAnimationStep);
	return true;

}
 
Example 19
Source File: BackgroundService.java    From BackPackTrackII with GNU General Public License v3.0 4 votes vote down vote up
public static void getAltitude(long from, long to, Context context) throws IOException, JSONException {
    Log.i(TAG, "Get altitude" +
            " from=" + SimpleDateFormat.getDateTimeInstance().format(new Date(from)) +
            " to=" + SimpleDateFormat.getDateTimeInstance().format(new Date(to)));

    DatabaseHelper dh = null;
    Cursor cursor = null;
    boolean first = true;
    try {
        dh = new DatabaseHelper(context);
        cursor = dh.getLocations(from, to, true, true, true, 0);

        int colID = cursor.getColumnIndex("ID");
        int colTime = cursor.getColumnIndex("time");
        int colProvider = cursor.getColumnIndex("provider");
        int colLatitude = cursor.getColumnIndex("latitude");
        int colLongitude = cursor.getColumnIndex("longitude");
        int colAltitudeType = cursor.getColumnIndex("altitude_type");

        while (cursor.moveToNext()) {
            long id = cursor.getLong(colID);
            long time = cursor.getLong(colTime);
            final String provider = cursor.getString(colProvider);
            double latitude = cursor.getDouble(colLatitude);
            double longitude = cursor.getDouble(colLongitude);
            int altitude_type = (cursor.isNull(colAltitudeType) ? ALTITUDE_NONE : cursor.getInt(colAltitudeType));

            if ((altitude_type & ALTITUDE_KEEP) == 0 &&
                    (altitude_type & ~ALTITUDE_KEEP) != ALTITUDE_LOOKUP) {
                Location location = new Location(provider);
                location.setLatitude(latitude);
                location.setLongitude(longitude);
                location.setTime(time);
                GoogleElevationApi.getElevation(location, context);
                if (first)
                    first = false;
                else
                    try {
                        // Max. 5 requests/second
                        Thread.sleep(200);
                    } catch (InterruptedException ignored) {
                    }
                Log.i(TAG, "New altitude for location=" + location);
                dh.updateLocationAltitude(id, location.getAltitude(), ALTITUDE_LOOKUP);
            }
        }
    } finally {
        if (cursor != null)
            cursor.close();
        if (dh != null)
            dh.close();
    }
}
 
Example 20
Source File: DoubleType.java    From CPOrm with MIT License 4 votes vote down vote up
@Override
public Object getColumnValue(Cursor cursor, int columnIndex) {
    return cursor.getDouble(columnIndex);
}