Refactoring sqlite

This commit is contained in:
Victor Shcherb 2013-01-04 18:29:59 +01:00
parent 96c73d405d
commit 3d25c396e5
7 changed files with 150 additions and 1002 deletions

View file

@ -1,145 +0,0 @@
package net.osmand.plus;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import net.osmand.LogUtil;
import net.osmand.ResultMatcher;
import net.osmand.data.Amenity;
import net.osmand.data.AmenityType;
import net.osmand.osm.MapUtils;
import net.sf.junidecode.Junidecode;
import org.apache.commons.logging.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Xml;
public class NameFinderPoiFilter extends PoiFilter {
public static final String FILTER_ID = "name_finder"; //$NON-NLS-1$
private static final Log log = LogUtil.getLog(NameFinderPoiFilter.class);
private static final int LIMIT = 300;
List<Amenity> searchedAmenities = new ArrayList<Amenity>();
private String query = ""; //$NON-NLS-1$
private String lastError = ""; //$NON-NLS-1$
public NameFinderPoiFilter(OsmandApplication application) {
super(null, application);
this.name = application.getString(R.string.poi_filter_nominatim); //$NON-NLS-1$
this.distanceToSearchValues = new double[] {1, 2, 5, 10, 20, 30, 100, 250 };
this.filterId = FILTER_ID;
}
@Override
public List<Amenity> searchAgain(double lat, double lon) {
MapUtils.sortListOfMapObject(searchedAmenities, lat, lon);
return searchedAmenities;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
@Override
protected List<Amenity> searchAmenities(double lat, double lon, double topLatitude,
double bottomLatitude, double leftLongitude, double rightLongitude, ResultMatcher<Amenity> matcher) {
searchedAmenities.clear();
String viewbox = "viewboxlbrt="+((float) leftLongitude)+","+((float) bottomLatitude)+","+((float) rightLongitude)+","+((float) topLatitude);
try {
lastError = "";
String urlq = "http://nominatim.openstreetmap.org/search/"+URLEncoder.encode(query)+ "?format=xml&addressdetails=1&limit="+LIMIT+"&bounded=1&"+viewbox;
log.info(urlq);
URL url = new URL(urlq); //$NON-NLS-1$
InputStream stream = url.openStream();
XmlPullParser parser = Xml.newPullParser();
parser.setInput(stream, "UTF-8"); //$NON-NLS-1$
int eventType;
int namedDepth= 0;
Amenity a = null;
while ((eventType = parser.next()) != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("searchresults")) { //$NON-NLS-1$
String err = parser.getAttributeValue("", "error"); //$NON-NLS-1$ //$NON-NLS-2$
if (err != null && err.length() > 0) {
lastError = err;
stream.close();
return searchedAmenities;
}
}
if (parser.getName().equals("place")) { //$NON-NLS-1$
namedDepth++;
if (namedDepth == 1) {
try {
a = new Amenity();
a.setLocation(Double.parseDouble(parser.getAttributeValue("", "lat")), //$NON-NLS-1$//$NON-NLS-2$
Double.parseDouble(parser.getAttributeValue("", "lon"))); //$NON-NLS-1$//$NON-NLS-2$
a.setId(Long.parseLong(parser.getAttributeValue("", "place_id"))); //$NON-NLS-1$ //$NON-NLS-2$
String name = parser.getAttributeValue("", "display_name"); //$NON-NLS-1$//$NON-NLS-2$
a.setName(name);
a.setEnName(Junidecode.unidecode(name));
a.setType(AmenityType.OTHER);
a.setSubType(parser.getAttributeValue("", "type")); //$NON-NLS-1$//$NON-NLS-2$
if (matcher == null || matcher.publish(a)) {
searchedAmenities.add(a);
}
} catch (NullPointerException e) {
log.info("Invalid attributes", e); //$NON-NLS-1$
} catch (NumberFormatException e) {
log.info("Invalid attributes", e); //$NON-NLS-1$
}
}
} else if (a != null && parser.getName().equals(a.getSubType())) {
if (parser.next() == XmlPullParser.TEXT) {
String name = parser.getText();
if (name != null) {
a.setName(name);
a.setEnName(Junidecode.unidecode(name));
}
}
}
} else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals("place")) { //$NON-NLS-1$
namedDepth--;
if(namedDepth == 0){
a = null;
}
}
}
}
stream.close();
} catch (IOException e) {
log.error("Error loading name finder poi", e); //$NON-NLS-1$
lastError = getApplication().getString(R.string.input_output_error); //$NON-NLS-1$
} catch (XmlPullParserException e) {
log.error("Error parsing name finder poi", e); //$NON-NLS-1$
lastError = getApplication().getString(R.string.input_output_error); //$NON-NLS-1$
}
MapUtils.sortListOfMapObject(searchedAmenities, lat, lon);
return searchedAmenities;
}
public String getLastError() {
return lastError;
}
public List<Amenity> getSearchedAmenities() {
return searchedAmenities;
}
}

View file

@ -27,6 +27,8 @@ import net.osmand.plus.activities.SettingsActivity;
import net.osmand.plus.api.ExternalServiceAPI;
import net.osmand.plus.api.InternalOsmAndAPI;
import net.osmand.plus.api.InternalToDoAPI;
import net.osmand.plus.api.SQLiteAPI;
import net.osmand.plus.api.SQLiteAPIImpl;
import net.osmand.plus.api.SettingsAPI;
import net.osmand.plus.render.NativeOsmandLibrary;
import net.osmand.plus.render.RendererRegistry;
@ -87,6 +89,7 @@ public class OsmandApplication extends Application implements ClientContext {
ExternalServiceAPI externalServiceAPI;
InternalToDoAPI internalToDoAPI;
InternalOsmAndAPI internalOsmAndAPI;
SQLiteAPI sqliteAPI;
@Override
public void onCreate() {
@ -96,6 +99,7 @@ public class OsmandApplication extends Application implements ClientContext {
externalServiceAPI = new net.osmand.plus.api.ExternalServiceAPIImpl(this);
internalToDoAPI = new net.osmand.plus.api.InternalToDoAPIImpl(this);
internalOsmAndAPI = new net.osmand.plus.api.InternalOsmAndAPIImpl(this);
sqliteAPI = new SQLiteAPIImpl(this);
osmandSettings = createOsmandSettingsInstance();
@ -612,4 +616,10 @@ public class OsmandApplication extends Application implements ClientContext {
return internalOsmAndAPI;
}
@Override
public SQLiteAPI getSQLiteAPI() {
// TODO Auto-generated method stub
return null;
}
}

View file

@ -1,323 +0,0 @@
package net.osmand.plus;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.osmand.OsmAndFormatter;
import net.osmand.ResultMatcher;
import net.osmand.data.Amenity;
import net.osmand.data.AmenityType;
import net.osmand.data.IndexConstants;
import net.osmand.osm.MapUtils;
public class PoiFilter {
public final static String STD_PREFIX = "std_"; //$NON-NLS-1$
public final static String USER_PREFIX = "user_"; //$NON-NLS-1$
public final static String CUSTOM_FILTER_ID = USER_PREFIX + "custom_id"; //$NON-NLS-1$
public final static String BY_NAME_FILTER_ID = USER_PREFIX + "by_name"; //$NON-NLS-1$
private Map<AmenityType, LinkedHashSet<String>> acceptedTypes = new LinkedHashMap<AmenityType, LinkedHashSet<String>>();
private String filterByName = null;
protected String filterId;
protected String name;
protected String nameFilter;
protected boolean isStandardFilter;
protected final OsmandApplication application;
protected int distanceInd = 1;
// in kilometers
protected double[] distanceToSearchValues = new double[] {1, 2, 3, 5, 10, 30, 100, 250 };
// constructor for standard filters
public PoiFilter(AmenityType type, OsmandApplication application){
this.application = application;
isStandardFilter = true;
filterId = STD_PREFIX + type;
name = type == null ? application.getString(R.string.poi_filter_closest_poi) : OsmAndFormatter.toPublicString(type,
application); //$NON-NLS-1$
if(type == null){
initSearchAll();
} else {
acceptedTypes.put(type, null);
}
}
// constructor for user defined filters
public PoiFilter(String name, String filterId, Map<AmenityType, LinkedHashSet<String>> acceptedTypes, OsmandApplication app){
application = app;
isStandardFilter = false;
if(filterId == null){
filterId = USER_PREFIX + name.replace(' ', '_').toLowerCase();
}
this.filterId = filterId;
this.name = name;
if(acceptedTypes == null){
initSearchAll();
} else {
this.acceptedTypes.putAll(acceptedTypes);
}
}
public void setNameFilter(String nameFilter) {
if(nameFilter != null) {
this.nameFilter = nameFilter.toLowerCase();
} else {
clearNameFilter();
}
}
public String getNameFilter() {
return nameFilter;
}
public void clearNameFilter(){
nameFilter = null;
}
private void initSearchAll(){
for(AmenityType t : AmenityType.values()){
acceptedTypes.put(t, null);
}
distanceToSearchValues = new double[] {0.5, 1, 2, 3, 5, 10, 15, 30, 100};
}
public boolean isSearchFurtherAvailable(){
return distanceInd < distanceToSearchValues.length - 1;
}
public List<Amenity> searchFurther(double latitude, double longitude, ResultMatcher<Amenity> matcher){
if(distanceInd < distanceToSearchValues.length - 1){
distanceInd ++;
}
List<Amenity> amenityList = searchAmenities( latitude, longitude, matcher);
MapUtils.sortListOfMapObject(amenityList, latitude, longitude);
return amenityList;
}
public String getSearchArea(){
double val = distanceToSearchValues[distanceInd];
if(val >= 1){
return " < " + ((int) val)+ " " + application.getString(R.string.km); //$NON-NLS-1$//$NON-NLS-2$
} else {
return " < 500 " + application.getString(R.string.m); //$NON-NLS-1$
}
}
public void clearPreviousZoom(){
distanceInd = 0;
}
public List<Amenity> initializeNewSearch(double lat, double lon, int firstTimeLimit, ResultMatcher<Amenity> matcher){
clearPreviousZoom();
List<Amenity> amenityList = searchAmenities(lat, lon, matcher);
MapUtils.sortListOfMapObject(amenityList, lat, lon);
if (firstTimeLimit > 0) {
while (amenityList.size() > firstTimeLimit) {
amenityList.remove(amenityList.size() - 1);
}
}
return amenityList;
}
private List<Amenity> searchAmenities(double lat, double lon, ResultMatcher<Amenity> matcher) {
double baseDistY = MapUtils.getDistance(lat, lon, lat - 1, lon);
double baseDistX = MapUtils.getDistance(lat, lon, lat, lon - 1);
double distance = distanceToSearchValues[distanceInd] * 1000;
double topLatitude = Math.min(lat + (distance/ baseDistY ), 84.);
double bottomLatitude = Math.max(lat - (distance/ baseDistY ), -84.);
double leftLongitude = Math.max(lon - (distance / baseDistX), -180);
double rightLongitude = Math.min(lon + (distance/ baseDistX), 180);
return searchAmenities(lat, lon, topLatitude, bottomLatitude, leftLongitude, rightLongitude, matcher);
}
public ResultMatcher<Amenity> getResultMatcher(final ResultMatcher<Amenity> matcher){
final String filter = nameFilter;
if(filter != null) {
final boolean en = application.getSettings().USE_ENGLISH_NAMES.get();
return new ResultMatcher<Amenity>() {
@Override
public boolean publish(Amenity object) {
if(!OsmAndFormatter.getPoiStringWithoutType(object, en).toLowerCase().contains(filter) ||
(matcher != null && !matcher.publish(object))) {
return false;
}
return true;
}
@Override
public boolean isCancelled() {
return false || (matcher != null && matcher.isCancelled());
}
};
}
return matcher;
}
protected List<Amenity> searchAmenities(double lat, double lon, double topLatitude,
double bottomLatitude, double leftLongitude, double rightLongitude, final ResultMatcher<Amenity> matcher) {
return application.getResourceManager().searchAmenities(this,
topLatitude, leftLongitude, bottomLatitude, rightLongitude, lat, lon, matcher);
}
public List<Amenity> searchAgain(double lat, double lon) {
List<Amenity> amenityList = searchAmenities(lat, lon, null);
MapUtils.sortListOfMapObject(amenityList, lat, lon);
return amenityList;
}
public String getName(){
return name;
}
/**
* @param type
* @return null if all subtypes are accepted/ empty list if type is not accepted at all
*/
public Set<String> getAcceptedSubtypes(AmenityType type){
if(!acceptedTypes.containsKey(type)){
return Collections.emptySet();
}
return acceptedTypes.get(type);
}
public boolean isTypeAccepted(AmenityType t){
return acceptedTypes.containsKey(t);
}
public boolean acceptTypeSubtype(AmenityType t, String subtype){
if(!acceptedTypes.containsKey(t)){
return false;
}
LinkedHashSet<String> set = acceptedTypes.get(t);
if(set == null){
return true;
}
return set.contains(subtype);
}
public void clearFilter(){
acceptedTypes = new LinkedHashMap<AmenityType, LinkedHashSet<String>>();
}
public boolean areAllTypesAccepted(){
if(AmenityType.values().length == acceptedTypes.size()){
for(AmenityType a : acceptedTypes.keySet()){
if(acceptedTypes.get(a) != null){
return false;
}
}
return true;
}
return false;
}
public void setTypeToAccept(AmenityType type, boolean accept){
if(accept){
acceptedTypes.put(type, new LinkedHashSet<String>());
} else {
acceptedTypes.remove(type);
}
}
public void setMapToAccept(Map<AmenityType, List<String>> newMap) {
Iterator<Entry<AmenityType, List<String>>> iterator = newMap.entrySet().iterator();
acceptedTypes.clear();
while(iterator.hasNext()){
Entry<AmenityType, List<String>> e = iterator.next();
if(e.getValue() == null){
acceptedTypes.put(e.getKey(), null);
} else {
acceptedTypes.put(e.getKey(), new LinkedHashSet<String>(e.getValue()));
}
}
}
public String buildSqlWhereFilter(){
if(areAllTypesAccepted()){
return null;
}
assert IndexConstants.POI_TABLE != null : "use constants here to show table usage "; //$NON-NLS-1$
if(acceptedTypes.size() == 0){
return "1 > 1"; //$NON-NLS-1$
}
StringBuilder b = new StringBuilder();
b.append("("); //$NON-NLS-1$
boolean first = true;
for(AmenityType a : acceptedTypes.keySet()){
if(first){
first = false;
} else {
b.append(" OR "); //$NON-NLS-1$
}
b.append("(type = '").append(AmenityType.valueToString(a)).append("'"); //$NON-NLS-1$ //$NON-NLS-2$
if(acceptedTypes.get(a) != null){
LinkedHashSet<String> list = acceptedTypes.get(a);
b.append(" AND subtype IN ("); //$NON-NLS-1$
boolean bfirst = true;
for(String s : list){
if(bfirst){
bfirst = false;
} else {
b.append(", "); //$NON-NLS-1$
}
b.append("'").append(s).append("'"); //$NON-NLS-1$ //$NON-NLS-2$
}
b.append(")"); //$NON-NLS-1$
}
b.append(")"); //$NON-NLS-1$
}
b.append(")"); //$NON-NLS-1$
return b.toString();
}
public Map<AmenityType, LinkedHashSet<String>> getAcceptedTypes(){
return new LinkedHashMap<AmenityType, LinkedHashSet<String>>(acceptedTypes);
}
public void selectSubTypesToAccept(AmenityType t, LinkedHashSet<String> accept){
acceptedTypes.put(t, accept);
}
public String getFilterId(){
return filterId;
}
public String getFilterByName() {
return filterByName;
}
public void setFilterByName(String filterByName) {
this.filterByName = filterByName;
}
public boolean isStandardFilter(){
return isStandardFilter;
}
public void setStandardFilter(boolean isStandardFilter) {
this.isStandardFilter = isStandardFilter;
}
public OsmandApplication getApplication() {
return application;
}
}

View file

@ -1,455 +0,0 @@
package net.osmand.plus;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import net.osmand.data.AmenityType;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
public class PoiFiltersHelper {
private final OsmandApplication application;
private NameFinderPoiFilter nameFinderPOIFilter;
private List<PoiFilter> cacheUserDefinedFilters;
private List<PoiFilter> cacheOsmDefinedFilters;
private static final String UDF_CAR_AID = "car_aid";
private static final String UDF_FOR_TOURISTS = "for_tourists";
private static final String UDF_FOOD_SHOP = "food_shop";
private static final String UDF_FUEL = "fuel";
private static final String UDF_SIGHTSEEING = "sightseeing";
private static final String UDF_EMERGENCY = "emergency";
private static final String UDF_PUBLIC_TRANSPORT = "public_transport";
private static final String UDF_ENTERTAINMENT = "entertainment";
private static final String UDF_ACCOMODATION = "accomodation";
private static final String UDF_RESTAURANTS = "restaurants";
private static final String UDF_PARKING = "parking";
private static final String[] DEL = new String[] {};
public PoiFiltersHelper(OsmandApplication application){
this.application = application;
}
public NameFinderPoiFilter getNameFinderPOIFilter() {
if(nameFinderPOIFilter == null){
nameFinderPOIFilter = new NameFinderPoiFilter(application);
}
return nameFinderPOIFilter;
}
public PoiFilter getFilterById(String filterId){
if(filterId == null){
return null;
}
if(filterId.equals(NameFinderPoiFilter.FILTER_ID)){
return getNameFinderPOIFilter();
}
if(filterId.startsWith(PoiFilter.USER_PREFIX)){
List<PoiFilter> filters = getUserDefinedPoiFilters();
for(PoiFilter f : filters){
if(f.getFilterId().equals(filterId)){
return f;
}
}
} else if(filterId.startsWith(PoiFilter.STD_PREFIX)){
List<PoiFilter> filters = getOsmDefinedPoiFilters();
for(PoiFilter f : filters){
if(f.getFilterId().equals(filterId)){
return f;
}
}
}
return null;
}
private void putAll(Map<AmenityType, LinkedHashSet<String>> types, AmenityType tp){
types.put(tp, null);
}
private void putValues(Map<AmenityType, LinkedHashSet<String>> types, AmenityType tp,String... vls){
LinkedHashSet<String> list = new LinkedHashSet<String>();
for(String v: vls){
list.add(v);
}
types.put(tp, list);
}
private List<PoiFilter> getUserDefinedDefaultFilters() {
List<PoiFilter> filters = new ArrayList<PoiFilter>();
filters.add(new PoiFilter(application.getString(R.string.poi_filter_car_aid), PoiFilter.USER_PREFIX + UDF_CAR_AID,
configureDefaultUserDefinedFilter(null, UDF_CAR_AID), application));
filters.add(new PoiFilter(application.getString(R.string.poi_filter_for_tourists), PoiFilter.USER_PREFIX + UDF_FOR_TOURISTS,
configureDefaultUserDefinedFilter(null, UDF_FOR_TOURISTS), application));
filters.add(new PoiFilter(application.getString(R.string.poi_filter_fuel), PoiFilter.USER_PREFIX + UDF_FUEL,
configureDefaultUserDefinedFilter(null, UDF_FUEL), application));
filters.add(new PoiFilter(application.getString(R.string.poi_filter_food_shop), PoiFilter.USER_PREFIX + UDF_FOOD_SHOP,
configureDefaultUserDefinedFilter(null, UDF_FOOD_SHOP), application));
filters.add(new PoiFilter(application.getString(R.string.poi_filter_sightseeing), PoiFilter.USER_PREFIX + UDF_SIGHTSEEING,
configureDefaultUserDefinedFilter(null, UDF_SIGHTSEEING), application));
// UDF_EMERGENCY = "emergency";
// UDF_ENTERTAINMENT = "entertainment";
filters.add(new PoiFilter(application.getString(R.string.poi_filter_accomodation), PoiFilter.USER_PREFIX + UDF_ACCOMODATION,
configureDefaultUserDefinedFilter(null, UDF_ACCOMODATION), application));
filters.add(new PoiFilter(application.getString(R.string.poi_filter_restaurants), PoiFilter.USER_PREFIX + UDF_RESTAURANTS,
configureDefaultUserDefinedFilter(null, UDF_RESTAURANTS), application));
filters.add(new PoiFilter(application.getString(R.string.poi_filter_public_transport),
PoiFilter.USER_PREFIX + UDF_PUBLIC_TRANSPORT, configureDefaultUserDefinedFilter(null, UDF_PUBLIC_TRANSPORT), application));
filters.add(new PoiFilter(application.getString(R.string.poi_filter_parking), PoiFilter.USER_PREFIX + UDF_PARKING,
configureDefaultUserDefinedFilter(null, UDF_PARKING), application));
return filters;
}
private Map<AmenityType, LinkedHashSet<String>> configureDefaultUserDefinedFilter(Map<AmenityType, LinkedHashSet<String>> types, String key) {
if(types == null) {
types = new LinkedHashMap<AmenityType, LinkedHashSet<String>>();
}
if(UDF_CAR_AID.equals(key)){
putValues(types, AmenityType.TRANSPORTATION, "fuel", "car_wash", "car_repair","car", "car_sharing");
putValues(types, AmenityType.SHOP, "fuel", "car_wash", "car_repair","car", "car_parts");
} else if(UDF_SIGHTSEEING.equals(key)){
putAll(types, AmenityType.HISTORIC);
putAll(types, AmenityType.TOURISM);
putAll(types, AmenityType.OSMWIKI);
putValues(types, AmenityType.OTHER, "place_of_worship");
} else if(UDF_FOR_TOURISTS.equals(key)){
putAll(types, AmenityType.HISTORIC);
putAll(types, AmenityType.TOURISM);
putAll(types, AmenityType.FINANCE);
putAll(types, AmenityType.OSMWIKI);
putValues(types, AmenityType.OTHER, "place_of_worship", "internet_access_wlan", "internet_access_wired",
"internet_access_terminal", "internet_access_public", "internet_access_service",
"embassy","emergency_phone","marketplace",
"post_office","telephone", "toilets");
} else if(UDF_FUEL.equals(key)){
putValues(types, AmenityType.TRANSPORTATION, "fuel");
} else if (UDF_FOOD_SHOP.equals(key)) {
putValues(types, AmenityType.SHOP, "alcohol", "bakery", "beverages", "butcher", "convenience", "department_store",
"convenience", "farm", "general", "ice_cream", "kiosk", "supermarket", "variety_store");
} else if (UDF_SIGHTSEEING.equals(key)) {
putAll(types, AmenityType.HISTORIC);
putValues(types, AmenityType.TOURISM, "attraction",
"artwork","zoo","theme_park", "museum","viewpoint");
putValues(types, AmenityType.OTHER, "place_of_worship");
} else if (UDF_ACCOMODATION.equals(key)) {
putValues(types, AmenityType.TOURISM, "camp_site",
"caravan_site","picnic_site","alpine_hut", "chalet","guest_house",
"hostel", "hotel","motel");
} else if (UDF_PARKING.equals(key)) {
putValues(types, AmenityType.TRANSPORTATION, "parking",
"bicycle_parking");
} else if (UDF_PUBLIC_TRANSPORT.equals(key)) {
putValues(types, AmenityType.TRANSPORTATION, "public_transport_stop_position", "public_transport_platform",
"public_transport_station",
// railway
"railway_platform", "railway_station", "halt", "tram_stop", "subway_entrance", "railway_buffer_stop",
// bus, cars, bicycle
"bus_stop", "platform", "ferry_terminal", "taxi", "bicycle_rental", "bus_station", "car_rental", "car_sharing",
// aero
"airport", "aerodrome", "terminal", "gate",
// aerial ways ( hide ways)
// "aerialway_cable_car", "aerialway_gondola", "aerialway_chair_lift", "aerialway_mixed_lift", "aerialway_drag_lift", "aerialway_goods",
"aerialway_station"
// ways (hide ways)
// "rail", "tram", "light_rail", "subway", "railway_narrow_gauge", "railway_monorail", "railway_funicular"
);
} else if (UDF_RESTAURANTS.equals(key)) {
putValues(types, AmenityType.SUSTENANCE, "restaurant",
"cafe", "food_court", "fast_food", "pub", "bar", "biergarten");
} else if (UDF_EMERGENCY.equals(key)) {
putAll(types, AmenityType.HEALTHCARE);
putAll(types, AmenityType.EMERGENCY);
} else if (UDF_ENTERTAINMENT.equals(key)) {
putAll(types, AmenityType.ENTERTAINMENT);
}
return types;
}
public List<PoiFilter> getUserDefinedPoiFilters(){
if(cacheUserDefinedFilters == null){
cacheUserDefinedFilters = new ArrayList<PoiFilter>();
PoiFilter filter = new PoiFilter(application.getString(R.string.poi_filter_custom_filter), PoiFilter.CUSTOM_FILTER_ID,
new LinkedHashMap<AmenityType, LinkedHashSet<String>>(), application); //$NON-NLS-1$
filter.setStandardFilter(true);
cacheUserDefinedFilters.add(filter);
filter = new SearchByNameFilter(application);
cacheUserDefinedFilters.add(filter);
PoiFilterDbHelper helper = openDbHelper();
List<PoiFilter> userDefined = helper.getFilters(helper.getReadableDatabase());
final Collator instance = Collator.getInstance();
Collections.sort(userDefined, new Comparator<PoiFilter>() {
@Override
public int compare(PoiFilter object1, PoiFilter object2) {
return instance.compare(object1.getName(), object2.getName());
}
});
cacheUserDefinedFilters.addAll(userDefined);
helper.close();
}
return Collections.unmodifiableList(cacheUserDefinedFilters);
}
public static String getOsmDefinedFilterId(AmenityType t){
return PoiFilter.STD_PREFIX + t;
}
public void updateFilters(boolean onlyAddFilters){
PoiFilterDbHelper helper = openDbHelper();
helper.upgradeFilters(helper.getWritableDatabase(), onlyAddFilters);
helper.close();
}
public List<PoiFilter> getOsmDefinedPoiFilters(){
if(cacheOsmDefinedFilters == null){
cacheOsmDefinedFilters = new ArrayList<PoiFilter>();
for(AmenityType t : AmenityType.values()){
cacheOsmDefinedFilters.add(new PoiFilter(t, application));
}
final Collator instance = Collator.getInstance();
Collections.sort(cacheOsmDefinedFilters, new Comparator<PoiFilter>() {
@Override
public int compare(PoiFilter object1, PoiFilter object2) {
return instance.compare(object1.getName(), object2.getName());
}
});
cacheOsmDefinedFilters.add(0, new PoiFilter(null, application));
}
return Collections.unmodifiableList(cacheOsmDefinedFilters);
}
private PoiFilterDbHelper openDbHelper(){
return new PoiFilterDbHelper(application.getApplicationContext());
}
public boolean removePoiFilter(PoiFilter filter){
if(filter.getFilterId().equals(PoiFilter.CUSTOM_FILTER_ID) ||
filter.getFilterId().equals(PoiFilter.BY_NAME_FILTER_ID)){
return false;
}
PoiFilterDbHelper helper = openDbHelper();
if(helper == null){
return false;
}
boolean res = helper.deleteFilter(helper.getWritableDatabase(), filter);
if(res){
cacheUserDefinedFilters.remove(filter);
}
helper.close();
return res;
}
public boolean createPoiFilter(PoiFilter filter){
PoiFilterDbHelper helper = openDbHelper();
if(helper == null){
return false;
}
boolean res = helper.addFilter(filter, helper.getWritableDatabase(), false);
if(res){
cacheUserDefinedFilters.add(filter);
}
helper.close();
return res;
}
public boolean editPoiFilter(PoiFilter filter) {
if (filter.getFilterId().equals(PoiFilter.CUSTOM_FILTER_ID) ||
filter.getFilterId().equals(PoiFilter.BY_NAME_FILTER_ID)) {
return false;
}
PoiFilterDbHelper helper = openDbHelper();
if (helper != null) {
boolean res = helper.editFilter(helper.getWritableDatabase(), filter);
helper.close();
return res;
}
return false;
}
public class PoiFilterDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "poi_filters"; //$NON-NLS-1$
private static final int DATABASE_VERSION = 2;
private static final String FILTER_NAME = "poi_filters"; //$NON-NLS-1$
private static final String FILTER_COL_NAME = "name"; //$NON-NLS-1$
private static final String FILTER_COL_ID = "id"; //$NON-NLS-1$
private static final String FILTER_COL_FILTERBYNAME = "filterbyname"; //$NON-NLS-1$
private static final String FILTER_TABLE_CREATE = "CREATE TABLE " + FILTER_NAME + " (" + //$NON-NLS-1$ //$NON-NLS-2$
FILTER_COL_NAME + ", " + FILTER_COL_ID + ", " + FILTER_COL_FILTERBYNAME + ");"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
private static final String CATEGORIES_NAME = "categories"; //$NON-NLS-1$
private static final String CATEGORIES_FILTER_ID = "filter_id"; //$NON-NLS-1$
private static final String CATEGORIES_COL_CATEGORY = "category"; //$NON-NLS-1$
private static final String CATEGORIES_COL_SUBCATEGORY = "subcategory"; //$NON-NLS-1$
private static final String CATEGORIES_TABLE_CREATE = "CREATE TABLE " + CATEGORIES_NAME + " (" + //$NON-NLS-1$ //$NON-NLS-2$
CATEGORIES_FILTER_ID + ", " + CATEGORIES_COL_CATEGORY + ", " + CATEGORIES_COL_SUBCATEGORY + ");"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
PoiFilterDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(FILTER_TABLE_CREATE);
db.execSQL(CATEGORIES_TABLE_CREATE);
upgradeFilters(db, true);
}
public void upgradeFilters(SQLiteDatabase db, boolean onlyAdd) {
List<PoiFilter> filters = PoiFilterDbHelper.this.getFilters(db);
List<PoiFilter> def = getUserDefinedDefaultFilters();
for(PoiFilter f : filters){
PoiFilter std = null;
for(PoiFilter d : def){
if(f.getFilterId().equals(d.getFilterId())){
std = d;
break;
}
}
for(String toDel : DEL) {
if(f.getFilterId().equals(toDel)) {
deleteFilter(db, f);
}
}
if(std != null){
if(!onlyAdd){
editFilter(db, std);
} else {
updateName(db, std);
}
def.remove(std);
}
}
for(PoiFilter d : def){
addFilter(d, db, false);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion == 2 || newVersion == 3) {
upgradeFilters(db, false);
} else {
upgradeFilters(db, true);
}
}
protected boolean addFilter(PoiFilter p, SQLiteDatabase db, boolean addOnlyCategories){
if(db != null){
if(!addOnlyCategories){
db.execSQL("INSERT INTO " + FILTER_NAME + " VALUES (?, ?, ?)",new Object[]{p.getName(), p.getFilterId(), p.getFilterByName()}); //$NON-NLS-1$ //$NON-NLS-2$
}
Map<AmenityType, LinkedHashSet<String>> types = p.getAcceptedTypes();
SQLiteStatement insertCategories = db.compileStatement("INSERT INTO " + CATEGORIES_NAME + " VALUES (?, ?, ?)"); //$NON-NLS-1$ //$NON-NLS-2$
for(AmenityType a : types.keySet()){
if(types.get(a) == null){
insertCategories.bindString(1, p.getFilterId());
insertCategories.bindString(2, AmenityType.valueToString(a));
insertCategories.bindNull(3);
insertCategories.execute();
} else {
for(String s : types.get(a)){
insertCategories.bindString(1, p.getFilterId());
insertCategories.bindString(2, AmenityType.valueToString(a));
insertCategories.bindString(3, s);
insertCategories.execute();
}
}
}
insertCategories.close();
return true;
}
return false;
}
protected List<PoiFilter> getFilters(SQLiteDatabase db){
ArrayList<PoiFilter> list = new ArrayList<PoiFilter>();
if(db != null){
Cursor query = db.rawQuery("SELECT " + CATEGORIES_FILTER_ID +", " + CATEGORIES_COL_CATEGORY +"," + CATEGORIES_COL_SUBCATEGORY +" FROM " + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
CATEGORIES_NAME, null);
Map<String, Map<AmenityType, LinkedHashSet<String>>> map = new LinkedHashMap<String, Map<AmenityType,LinkedHashSet<String>>>();
if(query.moveToFirst()){
do {
String filterId = query.getString(0);
if(!map.containsKey(filterId)){
map.put(filterId, new LinkedHashMap<AmenityType, LinkedHashSet<String>>());
}
Map<AmenityType, LinkedHashSet<String>> m = map.get(filterId);
AmenityType a = AmenityType.fromString(query.getString(1));
String subCategory = query.getString(2);
if(subCategory == null){
m.put(a, null);
} else {
if(m.get(a) == null){
m.put(a, new LinkedHashSet<String>());
}
m.get(a).add(subCategory);
}
} while(query.moveToNext());
}
query.close();
query = db.rawQuery("SELECT " + FILTER_COL_ID +", " + FILTER_COL_NAME +"," + FILTER_COL_FILTERBYNAME +" FROM " + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
FILTER_NAME, null);
if(query.moveToFirst()){
do {
String filterId = query.getString(0);
if(map.containsKey(filterId)){
PoiFilter filter = new PoiFilter(query.getString(1), filterId, map.get(filterId), application);
filter.setFilterByName(query.getString(2));
list.add(filter);
}
} while(query.moveToNext());
}
query.close();
}
return list;
}
protected boolean editFilter(SQLiteDatabase db, PoiFilter filter) {
if (db != null) {
db.execSQL("DELETE FROM " + CATEGORIES_NAME + " WHERE " + CATEGORIES_FILTER_ID + " = ?", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
new Object[] { filter.getFilterId() });
addFilter(filter, db, true);
updateName(db, filter);
return true;
}
return false;
}
private void updateName(SQLiteDatabase db, PoiFilter filter) {
db.execSQL("UPDATE " + FILTER_NAME + " SET " + FILTER_COL_FILTERBYNAME + " = ?, " + FILTER_COL_NAME + " = ? " + " WHERE " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ FILTER_COL_ID + "= ?", new Object[] { filter.getFilterByName(), filter.getName(), filter.getFilterId() }); //$NON-NLS-1$
}
protected boolean deleteFilter(SQLiteDatabase db, PoiFilter p){
if(db != null){
db.execSQL("DELETE FROM " + FILTER_NAME + " WHERE " +FILTER_COL_ID + " = ?",new Object[]{p.getFilterId()}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
db.execSQL("DELETE FROM " + CATEGORIES_NAME + " WHERE " +CATEGORIES_FILTER_ID + " = ?", new Object[]{p.getFilterId()}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return true;
}
return false;
}
}
}

View file

@ -1,79 +0,0 @@
package net.osmand.plus;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import net.osmand.ResultMatcher;
import net.osmand.data.Amenity;
import net.osmand.data.AmenityType;
import net.osmand.osm.MapUtils;
public class SearchByNameFilter extends PoiFilter {
public static final String FILTER_ID = PoiFilter.BY_NAME_FILTER_ID; //$NON-NLS-1$
List<Amenity> searchedAmenities = new ArrayList<Amenity>();
private String query = ""; //$NON-NLS-1$
public SearchByNameFilter(OsmandApplication application) {
super(application.getString(R.string.poi_filter_by_name), FILTER_ID, new LinkedHashMap<AmenityType, LinkedHashSet<String>>(), application);
this.distanceToSearchValues = new double[] {100, 1000, 5000};
this.isStandardFilter = true;
}
@Override
public List<Amenity> searchAgain(double lat, double lon) {
MapUtils.sortListOfMapObject(searchedAmenities, lat, lon);
return searchedAmenities;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
@Override
protected List<Amenity> searchAmenities(double lat, double lon, double topLatitude,
double bottomLatitude, double leftLongitude, double rightLongitude, final ResultMatcher<Amenity> matcher) {
searchedAmenities.clear();
final int limit = distanceInd == 0 ? 500 : -1;
List<Amenity> result = application.getResourceManager().searchAmenitiesByName(query,
topLatitude, leftLongitude, bottomLatitude, rightLongitude, lat, lon, new ResultMatcher<Amenity>() {
boolean elimit = false;
@Override
public boolean publish(Amenity object) {
if(limit != -1 && searchedAmenities.size() > limit) {
elimit = true;
}
if(matcher.publish(object)) {
searchedAmenities.add(object);
return true;
}
return false;
}
@Override
public boolean isCancelled() {
return matcher.isCancelled() || elimit;
}
});
MapUtils.sortListOfMapObject(result, lat, lon);
searchedAmenities = result;
return searchedAmenities;
}
public List<Amenity> getSearchedAmenities() {
return searchedAmenities;
}
}

View file

@ -3,10 +3,14 @@ package net.osmand.plus.api;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import net.osmand.NativeLibrary;
import net.osmand.ResultMatcher;
import net.osmand.access.AccessibilityMode;
import net.osmand.data.Amenity;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.PoiFilter;
import net.osmand.plus.ResourceManager;
import net.osmand.plus.render.NativeOsmandLibrary;
@ -74,5 +78,17 @@ public class InternalOsmAndAPIImpl implements InternalOsmAndAPI {
return ((AccessibilityManager) app.getSystemService(Context.ACCESSIBILITY_SERVICE)).isEnabled();
}
@Override
public List<Amenity> searchAmenities(PoiFilter filter, double topLatitude, double leftLongitude, double bottomLatitude,
double rightLongitude, double lat, double lon, ResultMatcher<Amenity> matcher) {
return app.getResourceManager().searchAmenities(filter, topLatitude, leftLongitude, bottomLatitude, rightLongitude, lat, lon, matcher);
}
@Override
public List<Amenity> searchAmenitiesByName(String searchQuery, double topLatitude, double leftLongitude, double bottomLatitude,
double rightLongitude, double lat, double lon, ResultMatcher<Amenity> matcher) {
return app.getResourceManager().searchAmenitiesByName(searchQuery, topLatitude, leftLongitude, bottomLatitude, rightLongitude, lat, lon, matcher);
}
}

View file

@ -0,0 +1,124 @@
package net.osmand.plus.api;
import net.osmand.plus.OsmandApplication;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class SQLiteAPIImpl implements SQLiteAPI {
private OsmandApplication app;
public SQLiteAPIImpl(OsmandApplication app) {
this.app = app;
}
@Override
public SQLiteConnection getOrCreateDatabase(String name, boolean readOnly) {
android.database.sqlite.SQLiteDatabase db = app.openOrCreateDatabase(name,
readOnly? SQLiteDatabase.OPEN_READONLY : SQLiteDatabase.OPEN_READWRITE, null);
if(db == null) {
return null;
}
return new SQLiteDatabaseWrapper(db) ;
}
public class SQLiteDatabaseWrapper implements SQLiteConnection {
android.database.sqlite.SQLiteDatabase ds;
public SQLiteDatabaseWrapper(android.database.sqlite.SQLiteDatabase ds) {
super();
this.ds = ds;
}
@Override
public int getVersion() {
return ds.getVersion();
}
@Override
public void close() {
ds.close();
}
@Override
public SQLiteCursor rawQuery(String sql, String[] selectionArgs) {
final Cursor c = ds.rawQuery(sql, selectionArgs);
if(c == null) {
return null;
}
return new SQLiteCursor() {
@Override
public boolean moveToNext() {
return c.moveToNext();
}
@Override
public boolean moveToFirst() {
return c.moveToFirst();
}
@Override
public String getString(int ind) {
return c.getString(ind);
}
@Override
public void close() {
c.close();
}
};
}
@Override
public void execSQL(String query) {
ds.execSQL(query);
}
@Override
public void execSQL(String query, Object[] objects) {
ds.execSQL(query, objects);
}
@Override
public SQLiteStatement compileStatement(String query) {
final android.database.sqlite.SQLiteStatement st = ds.compileStatement(query);
if(st == null) {
return null;
}
return new SQLiteStatement() {
@Override
public void execute() {
st.execute();
}
@Override
public void close() {
st.close();
}
@Override
public void bindString(int i, String value) {
st.bindString(i, value);
}
@Override
public void bindNull(int i) {
st.bindNull(i);
}
};
}
@Override
public void setVersion(int newVersion) {
ds.setVersion(newVersion);
}
}
}