List of usage examples for android.database Cursor getDouble
double getDouble(int columnIndex);
From source file:com.example.android.diegobaldi.sunshine.DetailActivity.java
/** * Runs on the main thread when a load is complete. If initLoader is called (we call it from * onCreate in DetailActivity) and the LoaderManager already has completed a previous load * for this Loader, onLoadFinished will be called immediately. Within onLoadFinished, we bind * the data to our views so the user can see the details of the weather on the date they * selected from the forecast.//from w w w . j a v a 2s . c o m * * @param loader The cursor loader that finished. * @param data The cursor that is being returned. */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { /* * Before we bind the data to the UI that will display that data, we need to check the * cursor to make sure we have the results that we are expecting. In order to do that, we * check to make sure the cursor is not null and then we call moveToFirst on the cursor. * Although it may not seem obvious at first, moveToFirst will return true if it contains * a valid first row of data. * * If we have valid data, we want to continue on to bind that data to the UI. If we don't * have any data to bind, we just return from this method. */ boolean cursorHasValidData = false; if (data != null && data.moveToFirst()) { /* We have valid data, continue on to bind the data to the UI */ cursorHasValidData = true; } if (!cursorHasValidData) { /* No data to display, simply return and do nothing */ return; } /**************** * Weather Icon * ****************/ /* Read weather condition ID from the cursor (ID provided by Open Weather Map) */ int weatherId = data.getInt(INDEX_WEATHER_CONDITION_ID); /* Use our utility method to determine the resource ID for the proper art */ int weatherImageId = SunshineWeatherUtils.getLargeArtResourceIdForWeatherCondition(weatherId); /* Set the resource ID on the icon to display the art */ mDetailBinding.primaryInfo.weatherIcon.setImageResource(weatherImageId); /**************** * Weather Date * ****************/ /* * Read the date from the cursor. It is important to note that the date from the cursor * is the same date from the weather SQL table. The date that is stored is a GMT * representation at midnight of the date when the weather information was loaded for. * * When displaying this date, one must add the GMT offset (in milliseconds) to acquire * the date representation for the local date in local time. * SunshineDateUtils#getFriendlyDateString takes care of this for us. */ long localDateMidnightGmt = data.getLong(INDEX_WEATHER_DATE); String dateText = SunshineDateUtils.getFriendlyDateString(this, localDateMidnightGmt, true); mDetailBinding.primaryInfo.date.setText(dateText); /*********************** * Weather Description * ***********************/ /* Use the weatherId to obtain the proper description */ String description = SunshineWeatherUtils.getStringForWeatherCondition(this, weatherId); /* Create the accessibility (a11y) String from the weather description */ String descriptionA11y = getString(R.string.a11y_forecast, description); /* Set the text and content description (for accessibility purposes) */ mDetailBinding.primaryInfo.weatherDescription.setText(description); mDetailBinding.primaryInfo.weatherDescription.setContentDescription(descriptionA11y); /* Set the content description on the weather image (for accessibility purposes) */ mDetailBinding.primaryInfo.weatherIcon.setContentDescription(descriptionA11y); /************************** * High (max) temperature * **************************/ /* Read high temperature from the cursor (in degrees celsius) */ double highInCelsius = data.getDouble(INDEX_WEATHER_MAX_TEMP); /* * If the user's preference for weather is fahrenheit, formatTemperature will convert * the temperature. This method will also append either C or F to the temperature * String. */ String highString = SunshineWeatherUtils.formatTemperature(this, highInCelsius); /* Create the accessibility (a11y) String from the weather description */ String highA11y = getString(R.string.a11y_high_temp, highString); /* Set the text and content description (for accessibility purposes) */ mDetailBinding.primaryInfo.highTemperature.setText(highString); mDetailBinding.primaryInfo.highTemperature.setContentDescription(highA11y); /************************* * Low (min) temperature * *************************/ /* Read low temperature from the cursor (in degrees celsius) */ double lowInCelsius = data.getDouble(INDEX_WEATHER_MIN_TEMP); /* * If the user's preference for weather is fahrenheit, formatTemperature will convert * the temperature. This method will also append either C or F to the temperature * String. */ String lowString = SunshineWeatherUtils.formatTemperature(this, lowInCelsius); String lowA11y = getString(R.string.a11y_low_temp, lowString); /* Set the text and content description (for accessibility purposes) */ mDetailBinding.primaryInfo.lowTemperature.setText(lowString); mDetailBinding.primaryInfo.lowTemperature.setContentDescription(lowA11y); /************ * Humidity * ************/ /* Read humidity from the cursor */ float humidity = data.getFloat(INDEX_WEATHER_HUMIDITY); String humidityString = getString(R.string.format_humidity, humidity); String humidityA11y = getString(R.string.a11y_humidity, humidityString); /* Set the text and content description (for accessibility purposes) */ mDetailBinding.extraDetails.humidity.setText(humidityString); mDetailBinding.extraDetails.humidity.setContentDescription(humidityA11y); mDetailBinding.extraDetails.humidityLabel.setContentDescription(humidityA11y); /**************************** * Wind speed and direction * ****************************/ /* Read wind speed (in MPH) and direction (in compass degrees) from the cursor */ float windSpeed = data.getFloat(INDEX_WEATHER_WIND_SPEED); float windDirection = data.getFloat(INDEX_WEATHER_DEGREES); String windString = SunshineWeatherUtils.getFormattedWind(this, windSpeed, windDirection); String windA11y = getString(R.string.a11y_wind, windString); /* Set the text and content description (for accessibility purposes) */ mDetailBinding.extraDetails.windMeasurement.setText(windString); mDetailBinding.extraDetails.windMeasurement.setContentDescription(windA11y); mDetailBinding.extraDetails.windLabel.setContentDescription(windA11y); /************ * Pressure * ************/ /* Read pressure from the cursor */ float pressure = data.getFloat(INDEX_WEATHER_PRESSURE); /* * Format the pressure text using string resources. The reason we directly access * resources using getString rather than using a method from SunshineWeatherUtils as * we have for other data displayed in this Activity is because there is no * additional logic that needs to be considered in order to properly display the * pressure. */ String pressureString = getString(R.string.format_pressure, pressure); String pressureA11y = getString(R.string.a11y_pressure, pressureString); /* Set the text and content description (for accessibility purposes) */ mDetailBinding.extraDetails.pressure.setText(pressureString); mDetailBinding.extraDetails.pressure.setContentDescription(pressureA11y); mDetailBinding.extraDetails.pressureLabel.setContentDescription(pressureA11y); /* Store the forecast summary String in our forecast summary field to share later */ mForecastSummary = String.format("%s - %s - %s/%s", dateText, description, highString, lowString); }
From source file:inforuh.eventfinder.ui.DetailActivity.java
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data == null) { return;/*from w w w . j av a2 s.c o m*/ } if (data.moveToFirst()) { String title = data.getString(Event.TITLE); collapsingToolbar.setTitle(""); eventTitle.setText(title); eventContent.setText(Html.fromHtml(data.getString(Event.CONTENT))); Glide.with(this).load(data.getString(Event.IMAGE)).diskCacheStrategy(DiskCacheStrategy.SOURCE) .centerCrop().into(eventImage); String startDate = data.getString(Event.START_DATE); String endDate = data.getString(Event.END_DATE); Date startDateFormat = Config.parseDate(startDate, TimeZone.getDefault()); Date endDateFormat = Config.parseDate(endDate, TimeZone.getDefault()); Calendar startCal = Calendar.getInstance(); Calendar endCal = Calendar.getInstance(); startCal.setTime(startDateFormat); endCal.setTime(endDateFormat); int startMonth = startCal.get(Calendar.MONTH); int startDateInWeek = startCal.get(Calendar.DAY_OF_MONTH); int startYear = startCal.get(Calendar.YEAR); int endMonth = endCal.get(Calendar.MONTH); int endDateInWeek = endCal.get(Calendar.DAY_OF_MONTH); int endYear = endCal.get(Calendar.YEAR); String completeDate; if (getResources().getConfiguration().locale.getDisplayName().equals(Locale.US.getDisplayName())) { String formattedStartDate = Config.formatMonth(this, startMonth) + " " + Config.formatDate(this, startDateInWeek) + ", " + startYear; String formattedEndDate = Config.formatMonth(this, endMonth) + " " + Config.formatDate(this, endDateInWeek) + ", " + endYear; completeDate = formattedStartDate + " - " + formattedEndDate; } else { String formattedStartDate = Config.formatDate(this, startDateInWeek) + " " + Config.formatMonth(this, startMonth) + " " + startYear; String formattedEndDate = Config.formatDate(this, endDateInWeek) + " " + Config.formatMonth(this, endMonth) + " " + endYear; completeDate = formattedStartDate + " - " + formattedEndDate; } eventDate.setText(completeDate); String location = data.getString(Event.LOCATION); eventLocation.setText(location); String price = getString(R.string.ticket_price).toUpperCase() + " " + data.getString(Event.PRICE).toUpperCase(); eventPrice.setText(price); String name = data.getString(Event.ORGANIZER); contactName.setText(name); String contact = data.getString(Event.CONTACT_MAIN); contactMain.setText(contact); String twitter = "Twitter: " + data.getString(Event.CONTACT_TWITTER); contactTwitter.setText(twitter); String facebook = "Facebook: " + data.getString(Event.CONTACT_FACEBOOK); contactFacebook.setText(facebook); String line = "Line: " + data.getString(Event.CONTACT_LINE); contactLine.setText(line); String instagram = "Instagram: " + data.getString(Event.CONTACT_INSTAGRAM); contactInstagram.setText(instagram); String path = "Path: " + data.getString(Event.CONTACT_PATH); contactPath.setText(path); String url = data.getString(Event.URL); shareMessage = title + ", " + completeDate + ", " + url + " #eventfinderid"; Glide.with(this).load(data.getString(Event.BARCODE)).diskCacheStrategy(DiskCacheStrategy.SOURCE) .centerCrop().into(eventBarcode); if (googleMap != null) { setUpEventLocation(data.getDouble(Event.LONGITUDE), data.getDouble(Event.LATITUDE), data.getFloat(Event.MAP_ZOOM)); } } }
From source file:hu.fnf.devel.atlas.Atlas.java
private void changeViewLevel(int evelId, int pageId, int amountOrId) { setContentView(evelId);//from w w w. j a va 2s . co m AtlasData.pushPos(AtlasData.DETAILS, pageId); switch (evelId) { case R.layout.detail_view: TextView id = (TextView) findViewById(R.id.id); TextView tag = (TextView) findViewById(R.id.tag); if (amountOrId >= 0) { id.setText(String.valueOf(amountOrId)); } else { id.setText(String.valueOf(amountOrId)); tag.setText("MANUAL"); } ContentResolver cr = getContentResolver(); /* * load categories */ Uri.Builder builder = new Builder(); builder.scheme("content"); builder.authority(AtlasData.DB_AUTHORITY); builder.appendPath(AtlasData.TABLE_CATEGORIES); builder.appendPath("all"); Cursor item = cr.query(builder.build(), AtlasData.CATEGORIES_COLUMNS, null, null, null); if (item != null && item.moveToFirst()) { do { Category c = new Category(item.getString(AtlasData.CATEGORIES_ID), item.getString(AtlasData.CATEGORIES_NAME), item.getString(AtlasData.CATEGORIES_AMOUNT), item.getString(AtlasData.CATEGORIES_DEPTH), item.getString(AtlasData.CATEGORIES_COLORR), item.getString(AtlasData.CATEGORIES_COLORG), item.getString(AtlasData.CATEGORIES_COLORB)); categories.put(c.getName(), c); } while (item.moveToNext()); item.close(); } /* * transaction details */ TextView amountText = (TextView) findViewById(R.id.taskAmount); TextView fromText = (TextView) findViewById(R.id.taskFrom); TextView toText = (TextView) findViewById(R.id.taskTo); TextView dateText = (TextView) findViewById(R.id.taskDate); ListView cats = (ListView) findViewById(R.id.taskCats); ArrayList<Category> cat_list = new ArrayList<Category>(); CatAddAdapter cat_adapter = new CatAddAdapter(getApplicationContext(), R.layout.addcat_view, cat_list); if (amountOrId >= 0) { builder = new Builder(); builder.scheme("content"); builder.authority(AtlasData.DB_AUTHORITY); builder.appendPath(AtlasData.TABLE_TRANSACTIONS); builder.appendPath("tasks"); builder.appendPath(String.valueOf(amountOrId)); item = cr.query(builder.build(), AtlasData.TRANSACTIONS_COLUMNS, null, null, null); if (item.moveToFirst()) { switch (item.getInt(AtlasData.TRANSACTIONS_TYPEID)) { case AtlasData.CARD_PAYMENT: tag.setText(item.getString(AtlasData.TRANSACTIONS_TO)); break; case AtlasData.CARD_CASHWITHDRAWAL: tag.setText(item.getString(AtlasData.TRANSACTIONS_TO)); break; case AtlasData.TRANSFER_INCOME: tag.setText(item.getString(AtlasData.TRANSACTIONS_FROM)); break; case AtlasData.TRANSFER_OUTCOME: tag.setText(item.getString(AtlasData.TRANSACTIONS_TO)); break; case AtlasData.TRANSFER_REPEATING: tag.setText(item.getString(AtlasData.TRANSACTIONS_TO)); break; } amountText.setText(item.getString(AtlasData.TRANSACTIONS_AMOUNT)); fromText.setText(item.getString(AtlasData.TRANSACTIONS_FROM)); toText.setText(item.getString(AtlasData.TRANSACTIONS_TO)); dateText.setText(AtlasData.getStringDateFromInt(item.getInt(AtlasData.TRANSACTIONS_DATE))); cat_adapter.setAmount(item.getDouble(AtlasData.TRANSACTIONS_AMOUNT)); } else { Log.e("Atlas", "cannot load data for view!"); return; } item.close(); } else { Calendar cal = new GregorianCalendar(TimeZone.getDefault()); dateText.setText(AtlasData.getStringDateFromInt((int) (cal.getTimeInMillis() / 1000L))); double amount = amountOrId * -1; amountText.setText(String.valueOf(amount)); cat_adapter.setAmount(amount); } cats.setAdapter(cat_adapter); Spinner spinner = (Spinner) findViewById(R.id.taskSpinner); builder = new Builder(); builder.scheme("content"); builder.authority(AtlasData.DB_AUTHORITY); builder.appendPath(AtlasData.TABLE_CATEGORIES); builder.appendPath("tip"); builder.appendQueryParameter(AtlasData.DATA_COLUMNS[AtlasData.DATA_TAG], String.valueOf(tag.getText())); item = cr.query(builder.build(), AtlasData.CATEGORIES_COLUMNS, null, null, null); ArrayList<String> array_spinner = new ArrayList<String>(); if (item.moveToFirst()) { do { array_spinner.add(item.getString(AtlasData.CATEGORIES_NAME)); } while (item.moveToNext()); } ArrayAdapter<String> arrayadapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.custom_simple_spinner, array_spinner); spinner.setAdapter(arrayadapter); item.close(); break; default: break; } Log.d("Atlas", "changeViewLevel to " + AtlasData.DETAILS + " : " + pageId); pager.setCurrentItem(pageId); setPagerSwipeActions(); }
From source file:cn.apputest.ctria.sql.DBManager.java
public CarBasicInfoDataEntity queryTheCursorCarBasicInfo(String plateNumber, String plateNumber_gua) { // System.out.println("query database"); DateFormat newdate = new DateFormat(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date dateTime1 = null;//from w ww . ja v a 2 s . c o m try { dateTime1 = dateFormat.parse(newdate.getDate3()); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } CarBasicInfoDataEntity carbasicinfo = new CarBasicInfoDataEntity(); Cursor maxweight_c = db.rawQuery( "SELECT SUM_QUALITY FROM or_car where PLATE_NUMBER='" + plateNumber + "' COLLATE NOCASE", null); Cursor traction_quality_c = db.rawQuery( "SELECT TRACTION_QUALITY FROM or_car where PLATE_NUMBER='" + plateNumber + "' COLLATE NOCASE", null); Cursor check_quality_c = db.rawQuery( "SELECT CHECK_QUALITY FROM or_car where PLATE_NUMBER='" + plateNumber + "' COLLATE NOCASE", null); Cursor check_quality_tail_c = db.rawQuery( "SELECT CHECK_QUALITY FROM or_car where PLATE_NUMBER='" + plateNumber_gua + "' COLLATE NOCASE", null); Cursor maxweight_tail_c = db.rawQuery( "SELECT SUM_QUALITY FROM or_car where PLATE_NUMBER='" + plateNumber_gua + "' COLLATE NOCASE", null); Cursor reorgannize_quality_c = db.rawQuery( "SELECT REORGANIZE_QUALITY FROM or_car where PLATE_NUMBER='" + plateNumber + "' COLLATE NOCASE", null); Cursor permitcard_c = db.rawQuery("SELECT EXPIRE_DATE FROM or_permit_run_cert where PLATE_NUMBER='" + plateNumber + "' COLLATE NOCASE", null); Cursor transportCardHead_c = db.rawQuery( "SELECT EXPIRE_DATE FROM or_transport_cert where PLATE_NUMBER='" + plateNumber + "' COLLATE NOCASE", null); Cursor transportCardTail_c = db.rawQuery("SELECT EXPIRE_DATE FROM or_transport_cert where PLATE_NUMBER='" + plateNumber_gua + "' COLLATE NOCASE", null); Cursor insuranceHead_c = db.rawQuery( "SELECT INSURANCE_DATE FROM or_car_insurance where CAR_NUMBER='" + plateNumber + "' COLLATE NOCASE", null); Cursor insuranceTail_c = db.rawQuery("SELECT INSURANCE_DATE FROM or_car_insurance where CAR_NUMBER='" + plateNumber_gua + "' COLLATE NOCASE", null); Cursor insuranceCargo_c = db .rawQuery("SELECT INSURANCE_TIME FROM or_carrier_warranty where LICENSE_NUMBER='" + plateNumber_gua + "' COLLATE NOCASE", null); Cursor specialequipusage_c = db .rawQuery("SELECT NEXT_CHECKOUT_DATE FROM or_special_equipment where CAR_NUMBER='" + plateNumber_gua + "' COLLATE NOCASE", null); carbasicinfo.setMaxweight(0); carbasicinfo.setTraction_quality(0); carbasicinfo.setCheck_quality(0); carbasicinfo.setReorganize_quality(0); carbasicinfo.setCheck_quality_tail(0); carbasicinfo.setMaxweight_tail(0); carbasicinfo.setStatus4InsuranceCertCargo(-1); carbasicinfo.setStatus4InsuranceCertHead(-1); carbasicinfo.setStatus4InsuranceCertTail(-1); carbasicinfo.setStatus4PermitRunCert(-1); carbasicinfo.setStatus4SEquipCheck(-1); carbasicinfo.setStatus4TransportCertHead(-1); carbasicinfo.setStatus4TransportCertTail(-1); while (maxweight_c.moveToNext()) { double a = maxweight_c.getDouble(maxweight_c.getColumnIndex("SUM_QUALITY")); carbasicinfo.setMaxweight(a); } maxweight_c.close(); while (maxweight_tail_c.moveToNext()) { double a = maxweight_tail_c.getDouble(maxweight_tail_c.getColumnIndex("SUM_QUALITY")); carbasicinfo.setMaxweight_tail(a); } maxweight_tail_c.close(); while (check_quality_tail_c.moveToNext()) { double a = check_quality_tail_c.getDouble(check_quality_tail_c.getColumnIndex("CHECK_QUALITY")); carbasicinfo.setCheck_quality_tail(a); } check_quality_tail_c.close(); while (traction_quality_c.moveToNext()) { double a = traction_quality_c.getDouble(traction_quality_c.getColumnIndex("TRACTION_QUALITY")); carbasicinfo.setTraction_quality(a); } traction_quality_c.close(); while (check_quality_c.moveToNext()) { double a = check_quality_c.getDouble(check_quality_c.getColumnIndex("CHECK_QUALITY")); carbasicinfo.setCheck_quality(a); } check_quality_c.close(); while (reorgannize_quality_c.moveToNext()) { double a = reorgannize_quality_c.getDouble(reorgannize_quality_c.getColumnIndex("REORGANIZE_QUALITY")); carbasicinfo.setReorganize_quality(a); } reorgannize_quality_c.close(); while (permitcard_c.moveToNext()) { String endTime = permitcard_c.getString(permitcard_c.getColumnIndex("EXPIRE_DATE")); if (!StringUtils.isNotBlank(endTime)) { carbasicinfo.setStatus4PermitRunCert(-1); } else { Date dateTime2 = null; try { dateTime2 = dateFormat.parse(endTime); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } int i = dateTime1.compareTo(dateTime2); if (i > 0) { carbasicinfo.setStatus4PermitRunCert(1); } else { carbasicinfo.setStatus4PermitRunCert(0); } } } permitcard_c.close(); while (transportCardHead_c.moveToNext()) { String endTime = transportCardHead_c.getString(transportCardHead_c.getColumnIndex("EXPIRE_DATE")); if (!StringUtils.isNotBlank(endTime)) { carbasicinfo.setStatus4TransportCertHead(-1); } else { Date dateTime2 = null; try { dateTime2 = dateFormat.parse(endTime); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } int i = dateTime1.compareTo(dateTime2); if (i > 0) { carbasicinfo.setStatus4TransportCertHead(1); } else { carbasicinfo.setStatus4TransportCertHead(0); } } } transportCardHead_c.close(); while (transportCardTail_c.moveToNext()) { String endTime = transportCardTail_c.getString(transportCardTail_c.getColumnIndex("EXPIRE_DATE")); if (!StringUtils.isNotBlank(endTime)) { carbasicinfo.setStatus4TransportCertTail(-1); } else { Date dateTime2 = null; try { dateTime2 = dateFormat.parse(endTime); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } int i = dateTime1.compareTo(dateTime2); if (i > 0) { carbasicinfo.setStatus4TransportCertTail(1); } else { carbasicinfo.setStatus4TransportCertTail(0); } } } transportCardTail_c.close(); while (insuranceHead_c.moveToNext()) { String endTime = insuranceHead_c.getString(insuranceHead_c.getColumnIndex("INSURANCE_DATE")); if (StringUtils.isNotBlank(endTime)) { String a[] = endTime.split(","); endTime = a[1]; } if (!StringUtils.isNotBlank(endTime)) { carbasicinfo.setStatus4InsuranceCertHead(-1); } else { Date dateTime2 = null; try { dateTime2 = dateFormat.parse(endTime); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } int i = dateTime1.compareTo(dateTime2); if (i > 0) { carbasicinfo.setStatus4InsuranceCertHead(1); } else { carbasicinfo.setStatus4InsuranceCertHead(0); } } } insuranceHead_c.close(); while (insuranceTail_c.moveToNext()) { String endTime = insuranceTail_c.getString(insuranceTail_c.getColumnIndex("INSURANCE_DATE")); if (StringUtils.isNotBlank(endTime)) { String a[] = endTime.split(","); endTime = a[1]; } if (!StringUtils.isNotBlank(endTime)) { carbasicinfo.setStatus4InsuranceCertTail(-1); } else { Date dateTime2 = null; try { dateTime2 = dateFormat.parse(endTime); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } int i = dateTime1.compareTo(dateTime2); if (i > 0) { carbasicinfo.setStatus4InsuranceCertTail(1); } else { carbasicinfo.setStatus4InsuranceCertTail(0); } } } insuranceTail_c.close(); while (insuranceCargo_c.moveToNext()) { String endTime = insuranceCargo_c.getString(insuranceCargo_c.getColumnIndex("INSURANCE_TIME")); if (StringUtils.isNotBlank(endTime)) { String a[] = endTime.split(","); endTime = a[1]; } if (!StringUtils.isNotBlank(endTime)) { carbasicinfo.setStatus4InsuranceCertCargo(-1); } else { Date dateTime2 = null; try { dateTime2 = dateFormat.parse(endTime); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } int i = dateTime1.compareTo(dateTime2); if (i > 0) { carbasicinfo.setStatus4InsuranceCertCargo(1); } else { carbasicinfo.setStatus4InsuranceCertCargo(0); } } } insuranceCargo_c.close(); while (specialequipusage_c.moveToNext()) { String endTime = specialequipusage_c .getString(specialequipusage_c.getColumnIndex("NEXT_CHECKOUT_DATE")); if (!StringUtils.isNotBlank(endTime)) { carbasicinfo.setStatus4SEquipCheck(-1); } else { Date dateTime2 = null; try { dateTime2 = dateFormat.parse(endTime); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } int i = dateTime1.compareTo(dateTime2); if (i > 0) { carbasicinfo.setStatus4SEquipCheck(1); } else { carbasicinfo.setStatus4SEquipCheck(0); } } } specialequipusage_c.close(); return carbasicinfo; }
From source file:org.liberty.android.fantastischmemopro.DatabaseHelper.java
public List<Item> getListItems(int id, int windowSize, int flag, String filter) { /* id: from which ID * list: the return list//from ww w . ja va 2 s . c o m * ret: only ret items * flag = 0 means no condition * flag = 1 means new items, the items user have never seen (acq=0) * flag = 2 means item due, they need to be reviewed. (ret) * flag = 3 means items that is ahead of time (cram) * flag = 4 means both ret and acq items, but ret comes first * flag = 5: shuffle items no other condition */ HashMap<String, String> hm = new HashMap<String, String>(); List<Item> list = new ArrayList<Item>(); Cursor result; String query = "SELECT learn_tbl._id, date_learn, interval, grade, easiness, acq_reps, ret_reps, lapses, acq_reps_since_lapse, ret_reps_since_lapse, question, answer, note, category FROM dict_tbl INNER JOIN learn_tbl ON dict_tbl._id=learn_tbl._id WHERE dict_tbl._id >= " + id + " "; if (flag == 1) { query += "AND acq_reps = 0 "; } else if (flag == 2 || flag == 4) { query += "AND round((julianday(date('now', 'localtime')) - julianday(date_learn))) - interval >= 0 AND acq_reps > 0 "; } else if (flag == 3) { query = "SELECT learn_tbl._id, date_learn, interval, grade, easiness, acq_reps, ret_reps, lapses, acq_reps_since_lapse, ret_reps_since_lapse, question, answer, note, category FROM dict_tbl INNER JOIN learn_tbl ON dict_tbl._id=learn_tbl._id WHERE round((julianday(date('now', 'localtime')) - julianday(date_learn))) - interval < 0 AND acq_reps > 0 "; } if (filter != null) { if (Pattern.matches("#\\d+-\\d+", filter)) { Pattern p = Pattern.compile("\\d+"); Matcher m = p.matcher(filter); m.find(); String min = m.group(); m.find(); String max = m.group(); query += "AND learn_tbl._id >=" + min + " AND learn_tbl._id <= " + max + " "; } else if (Pattern.matches("#\\d+", filter)) { Pattern p = Pattern.compile("\\d+"); Matcher m = p.matcher(filter); m.find(); String min = m.group(); query += "AND learn_tbl._id >= " + min + " "; } else if (!filter.equals("")) { /* Replace * and ? to % and _ used in SQL */ filter = filter.replace("*", "%"); filter = filter.replace("?", "_"); /* First remove white spaces at beginning */ String realFilter = filter.replaceAll("^\\s+", ""); String control = filter.length() >= 2 ? filter.substring(0, 2) : ""; /* Also remove the control text */ realFilter = realFilter.replaceAll("^%\\w\\s+", ""); Log.v(TAG, "Control " + control); Log.v(TAG, "Filter " + realFilter); if (control.equals("%q")) { query += "AND ((question LIKE '" + realFilter + "')) "; } else if (control.equals("%a")) { query += "AND ((answer LIKE '" + realFilter + "')) "; } else if (control.equals("%n")) { query += "AND ((note LIKE '" + realFilter + "')) "; } else if (control.equals("%c")) { query += "AND ((category LIKE '" + realFilter + "')) "; } else { query += "AND ((question LIKE '" + realFilter + "') OR (answer LIKE '" + realFilter + "') OR (note LIKE '" + realFilter + "') OR (category LIKE '" + realFilter + "')) "; } } } if (flag == 3 || flag == 5) { query += "ORDER BY RANDOM() "; } if (windowSize >= 0) { query += "LIMIT " + windowSize; } try { result = myDatabase.rawQuery(query, null); } catch (Exception e) { Log.e(TAG, "Query list items error", e); return null; } if (result.getCount() > 0) { result.moveToFirst(); do { hm.put("_id", Integer.toString(result.getInt(result.getColumnIndex("_id")))); hm.put("question", result.getString(result.getColumnIndex("question"))); hm.put("answer", result.getString(result.getColumnIndex("answer"))); hm.put("note", result.getString(result.getColumnIndex("note"))); hm.put("category", result.getString(result.getColumnIndex("category"))); hm.put("date_learn", result.getString(result.getColumnIndex("date_learn"))); hm.put("interval", Integer.toString(result.getInt(result.getColumnIndex("interval")))); hm.put("grade", Integer.toString(result.getInt(result.getColumnIndex("grade")))); hm.put("easiness", Double.toString(result.getDouble(result.getColumnIndex("easiness")))); hm.put("acq_reps", Integer.toString(result.getInt(result.getColumnIndex("acq_reps")))); hm.put("ret_reps", Integer.toString(result.getInt(result.getColumnIndex("ret_reps")))); hm.put("lapses", Integer.toString(result.getInt(result.getColumnIndex("lapses")))); hm.put("acq_reps_since_lapse", Integer.toString(result.getInt(result.getColumnIndex("acq_reps_since_lapse")))); hm.put("ret_reps_since_lapse", Integer.toString(result.getInt(result.getColumnIndex("ret_reps_since_lapse")))); Item resultItem = new Item(); resultItem.setData(hm); list.add(resultItem); } while (result.moveToNext()); } result.close(); if (flag == 4) { int remainingSize = windowSize - list.size(); if (remainingSize > 0) { /* Get the new items (acq = 0) */ List<Item> retList = getListItems(id, remainingSize, 1, filter); list.addAll(retList); } } return list; }
From source file:com.nextgis.mobile.fragment.AttributesFragment.java
private String parseAttributes(String data) throws RuntimeException { String selection = Constants.FIELD_ID + " = ?"; Cursor attributes = mLayer.query(null, selection, new String[] { mItemId + "" }, null, null); if (null == attributes || attributes.getCount() == 0) return data; if (attributes.moveToFirst()) { for (int i = 0; i < attributes.getColumnCount(); i++) { String column = attributes.getColumnName(i); String text, alias;//from w ww . j a va2 s . c o m if (column.startsWith(Constants.FIELD_GEOM_)) continue; if (column.equals(Constants.FIELD_GEOM)) { switch (mLayer.getGeometryType()) { case GTPoint: try { GeoPoint pt = (GeoPoint) GeoGeometryFactory.fromBlob(attributes.getBlob(i)); data += getRow(getString(R.string.coordinates), formatCoordinates(pt)); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } continue; case GTMultiPoint: try { GeoMultiPoint mpt = (GeoMultiPoint) GeoGeometryFactory.fromBlob(attributes.getBlob(i)); data += getRow(getString(R.string.center), formatCoordinates(mpt.getEnvelope().getCenter())); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } continue; case GTLineString: try { GeoLineString line = (GeoLineString) GeoGeometryFactory.fromBlob(attributes.getBlob(i)); data += getRow(getString(R.string.length), LocationUtil.formatLength(getContext(), line.getLength(), 3)); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } continue; case GTMultiLineString: try { GeoMultiLineString multiline = (GeoMultiLineString) GeoGeometryFactory .fromBlob(attributes.getBlob(i)); data += getRow(getString(R.string.length), LocationUtil.formatLength(getContext(), multiline.getLength(), 3)); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } continue; case GTPolygon: try { GeoPolygon polygon = (GeoPolygon) GeoGeometryFactory.fromBlob(attributes.getBlob(i)); data += getRow(getString(R.string.perimeter), LocationUtil.formatLength(getContext(), polygon.getPerimeter(), 3)); data += getRow(getString(R.string.area), LocationUtil.formatArea(getContext(), polygon.getArea())); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } continue; case GTMultiPolygon: try { GeoMultiPolygon polygon = (GeoMultiPolygon) GeoGeometryFactory .fromBlob(attributes.getBlob(i)); data += getRow(getString(R.string.perimeter), LocationUtil.formatLength(getContext(), polygon.getPerimeter(), 3)); data += getRow(getString(R.string.area), LocationUtil.formatArea(getContext(), polygon.getArea())); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } continue; default: continue; } } Field field = mLayer.getFieldByName(column); int fieldType = field != null ? field.getType() : Constants.NOT_FOUND; switch (fieldType) { case GeoConstants.FTInteger: text = attributes.getInt(i) + ""; break; case GeoConstants.FTReal: NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(4); nf.setGroupingUsed(false); text = nf.format(attributes.getDouble(i)); break; case GeoConstants.FTDate: case GeoConstants.FTTime: case GeoConstants.FTDateTime: text = formatDateTime(attributes.getLong(i), fieldType); break; default: text = toString(attributes.getString(i)); Pattern pattern = Pattern.compile(URL_PATTERN); Matcher match = pattern.matcher(text); while (match.matches()) { String url = text.substring(match.start(), match.end()); text = text.replaceFirst(URL_PATTERN, "<a href = '" + url + "'>" + url + "</a>"); match = pattern.matcher(text.substring(match.start() + url.length() * 2 + 17)); } break; } if (field != null) alias = field.getAlias(); else if (column.equals(Constants.FIELD_ID)) alias = Constants.FIELD_ID; else alias = ""; data += getRow(alias, text); } } attributes.close(); return data; }
From source file:org.opendatakit.utilities.test.AbstractODKDatabaseUtilsTest.java
public void testWriteDataIntoExisitingTableWithNumber_ExpectPass() throws ActionNotAuthorizedException { String tableId = testTable;/*from ww w . java 2 s . co m*/ String testCol = "testColumn"; String testColType = ElementDataType.number.name(); List<Column> columns = new ArrayList<Column>(); columns.add(new Column(testCol, testCol, testColType, "[]")); OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(db, tableId, columns); ODKDatabaseImplUtils.AccessContext accessContext = ODKDatabaseImplUtils.get().getAccessContext(db, tableId, activeUser, RoleConsts.ADMIN_ROLES_LIST); double testVal = 5.5; ContentValues cvValues = new ContentValues(); cvValues.put(testCol, testVal); ODKDatabaseImplUtils.get().insertRowWithId(db, tableId, orderedColumns, cvValues, LocalizationUtils.genUUID(), activeUser, RoleConsts.ADMIN_ROLES_LIST, currentLocale); // Select everything out of the table String sel = "SELECT * FROM " + tableId + " WHERE " + testCol + " = ?"; String[] selArgs = { "" + testVal }; Cursor cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext); double val = 0; while (cursor.moveToNext()) { int ind = cursor.getColumnIndex(testCol); int type = cursor.getType(ind); assertEquals(type, Cursor.FIELD_TYPE_FLOAT); val = cursor.getDouble(ind); } assertEquals(val, testVal); // Drop the table now that the test is done ODKDatabaseImplUtils.get().deleteTableAndAllData(db, tableId); }
From source file:org.opendatakit.utilities.test.AbstractODKDatabaseUtilsTest.java
public void testWriteDataIntoExisitingTableWithGeopoint_ExpectPass() throws ActionNotAuthorizedException { String tableId = testTable;/* w ww . j a va 2s . c om*/ String testCol = "testColumn"; String testColLat = "testColumn_latitude"; String testColLong = "testColumn_longitude"; String testColAlt = "testColumn_altitude"; String testColAcc = "testColumn_accuracy"; double pos_lat = 5.55; double pos_long = 6.6; double pos_alt = 7.77; double pos_acc = 8.88; String testColType = ElementType.GEOPOINT; List<Column> columns = new ArrayList<Column>(); columns.add(new Column(testCol, testCol, testColType, "[\"" + testColLat + "\",\"" + testColLong + "\",\"" + testColAlt + "\",\"" + testColAcc + "\"]")); columns.add(new Column(testColLat, "latitude", ElementDataType.number.name(), "[]")); columns.add(new Column(testColLong, "longitude", ElementDataType.number.name(), "[]")); columns.add(new Column(testColAlt, "altitude", ElementDataType.number.name(), "[]")); columns.add(new Column(testColAcc, "accuracy", ElementDataType.number.name(), "[]")); OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(db, tableId, columns); ODKDatabaseImplUtils.AccessContext accessContext = ODKDatabaseImplUtils.get().getAccessContext(db, tableId, activeUser, RoleConsts.ADMIN_ROLES_LIST); ContentValues cvValues = new ContentValues(); cvValues.put(testColLat, pos_lat); cvValues.put(testColLong, pos_long); cvValues.put(testColAlt, pos_alt); cvValues.put(testColAcc, pos_acc); ODKDatabaseImplUtils.get().insertRowWithId(db, tableId, orderedColumns, cvValues, LocalizationUtils.genUUID(), activeUser, RoleConsts.ADMIN_ROLES_LIST, currentLocale); // Select everything out of the table String sel = "SELECT * FROM " + tableId + " WHERE " + testColLat + " = ?"; String[] selArgs = { "" + pos_lat }; Cursor cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext); double valLat = 0; double valLong = 0; double valAlt = 0; double valAcc = 0; while (cursor.moveToNext()) { int ind = cursor.getColumnIndex(testColLat); int type = cursor.getType(ind); assertEquals(type, Cursor.FIELD_TYPE_FLOAT); valLat = cursor.getDouble(ind); ind = cursor.getColumnIndex(testColLong); type = cursor.getType(ind); assertEquals(type, Cursor.FIELD_TYPE_FLOAT); valLong = cursor.getDouble(ind); ind = cursor.getColumnIndex(testColAlt); type = cursor.getType(ind); assertEquals(type, Cursor.FIELD_TYPE_FLOAT); valAlt = cursor.getDouble(ind); ind = cursor.getColumnIndex(testColAcc); type = cursor.getType(ind); assertEquals(type, Cursor.FIELD_TYPE_FLOAT); valAcc = cursor.getDouble(ind); } assertEquals(valLat, pos_lat); assertEquals(valLong, pos_long); assertEquals(valAlt, pos_alt); assertEquals(valAcc, pos_acc); // Drop the table now that the test is done ODKDatabaseImplUtils.get().deleteTableAndAllData(db, tableId); }
From source file:org.opendatakit.utilities.AbstractODKDatabaseUtilsTest.java
@Test public void testWriteDataIntoExistingTableWithNumber_ExpectPass() throws ActionNotAuthorizedException { String tableId = testTable;/*from www . j a v a2 s . c om*/ String testCol = "testColumn"; String testColType = ElementDataType.number.name(); List<Column> columns = new ArrayList<Column>(); columns.add(new Column(testCol, testCol, testColType, "[]")); OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(db, tableId, columns); ODKDatabaseImplUtils.AccessContext accessContext = ODKDatabaseImplUtils.get().getAccessContext(db, tableId, activeUser, RoleConsts.ADMIN_ROLES_LIST); double testVal = 5.5; ContentValues cvValues = new ContentValues(); cvValues.put(testCol, testVal); ODKDatabaseImplUtils.get().insertRowWithId(db, tableId, orderedColumns, cvValues, LocalizationUtils.genUUID(), activeUser, RoleConsts.ADMIN_ROLES_LIST, currentLocale); // Select everything out of the table String sel = "SELECT * FROM " + tableId + " WHERE " + testCol + " = ?"; String[] selArgs = { "" + testVal }; Cursor cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext); double val = 0; while (cursor.moveToNext()) { int ind = cursor.getColumnIndex(testCol); int type = cursor.getType(ind); assertEquals(type, Cursor.FIELD_TYPE_FLOAT); val = cursor.getDouble(ind); } assertEquals(val, testVal, 0.0); // cursor.close(); // Drop the table now that the test is done ODKDatabaseImplUtils.get().deleteTableAndAllData(db, tableId); }
From source file:org.opendatakit.utilities.AbstractODKDatabaseUtilsTest.java
@Test public void testWriteDataIntoExistingTableWithGeopoint_ExpectPass() throws ActionNotAuthorizedException { String tableId = testTable;//from ww w . java2 s. co m String testCol = "testColumn"; String testColLat = "testColumn_latitude"; String testColLong = "testColumn_longitude"; String testColAlt = "testColumn_altitude"; String testColAcc = "testColumn_accuracy"; double pos_lat = 5.55; double pos_long = 6.6; double pos_alt = 7.77; double pos_acc = 8.88; String testColType = ElementType.GEOPOINT; List<Column> columns = new ArrayList<Column>(); columns.add(new Column(testCol, testCol, testColType, "[\"" + testColLat + "\",\"" + testColLong + "\",\"" + testColAlt + "\",\"" + testColAcc + "\"]")); columns.add(new Column(testColLat, "latitude", ElementDataType.number.name(), "[]")); columns.add(new Column(testColLong, "longitude", ElementDataType.number.name(), "[]")); columns.add(new Column(testColAlt, "altitude", ElementDataType.number.name(), "[]")); columns.add(new Column(testColAcc, "accuracy", ElementDataType.number.name(), "[]")); OrderedColumns orderedColumns = ODKDatabaseImplUtils.get().createOrOpenTableWithColumns(db, tableId, columns); ODKDatabaseImplUtils.AccessContext accessContext = ODKDatabaseImplUtils.get().getAccessContext(db, tableId, activeUser, RoleConsts.ADMIN_ROLES_LIST); ContentValues cvValues = new ContentValues(); cvValues.put(testColLat, pos_lat); cvValues.put(testColLong, pos_long); cvValues.put(testColAlt, pos_alt); cvValues.put(testColAcc, pos_acc); ODKDatabaseImplUtils.get().insertRowWithId(db, tableId, orderedColumns, cvValues, LocalizationUtils.genUUID(), activeUser, RoleConsts.ADMIN_ROLES_LIST, currentLocale); // Select everything out of the table String sel = "SELECT * FROM " + tableId + " WHERE " + testColLat + " = ?"; String[] selArgs = { "" + pos_lat }; Cursor cursor = ODKDatabaseImplUtils.get().rawQuery(db, sel, selArgs, null, accessContext); double valLat = 0; double valLong = 0; double valAlt = 0; double valAcc = 0; while (cursor.moveToNext()) { int ind = cursor.getColumnIndex(testColLat); int type = cursor.getType(ind); assertEquals(type, Cursor.FIELD_TYPE_FLOAT); valLat = cursor.getDouble(ind); ind = cursor.getColumnIndex(testColLong); type = cursor.getType(ind); assertEquals(type, Cursor.FIELD_TYPE_FLOAT); valLong = cursor.getDouble(ind); ind = cursor.getColumnIndex(testColAlt); type = cursor.getType(ind); assertEquals(type, Cursor.FIELD_TYPE_FLOAT); valAlt = cursor.getDouble(ind); ind = cursor.getColumnIndex(testColAcc); type = cursor.getType(ind); assertEquals(type, Cursor.FIELD_TYPE_FLOAT); valAcc = cursor.getDouble(ind); } assertEquals(valLat, pos_lat, 0.0); assertEquals(valLong, pos_long, 0.0); assertEquals(valAlt, pos_alt, 0.0); assertEquals(valAcc, pos_acc, 0.0); //cursor.close(); // Drop the table now that the test is done ODKDatabaseImplUtils.get().deleteTableAndAllData(db, tableId); }