This commit is contained in:
macgregor 2012-09-06 23:08:46 +05:30
commit 7c6f612bfd
98 changed files with 8497 additions and 0 deletions

5
android/db/README Normal file
View File

@ -0,0 +1,5 @@
//"to create sqlite database... "
//on cygwin go to directory of "D:\APPS\SPATIALITE\sqlite-shell-win32-x86-3071000"
//and execute following to create database
./sqlite3.exe database_name

125
android/db/create-new.sql Normal file
View File

@ -0,0 +1,125 @@
--create spatialite DB
--sudo -usudo -u postgres /usr/local/pgsql/bin/pg_dump --data-only --column-inserts mumbai_final | sed 's/false/0/g' | sed 's/true/1/g' | grep -v "^SET" >best-11-04-2012.sql
--gzip best-11-04-2012.sql
-- scp download db
--spatialite best-11-04-2012 <postgrres-best-11-04-2012.sql
--create spatialite DB
--sudo -usudo -u postgres /usr/local/pgsql/bin/pg_dump --data-only --column-inserts mumbai_final | sed 's/false/0/g' | sed 's/true/1/g' | grep -v "^SET" >best-11-04-2012.sql
--gzip best-11-04-2012.sql
delete from routes;
delete from stop_geo;
delete from stops_on_trip;
delete from trips_freq;
delete from schedule_rules;
delete from stop_names;
delete from trips;
stop_geo stops_on_trip trips_freq
schedule_rules stop_names trips
-- nohup postgres -D /usr/local/pgsql/data >>/var/log/postgres/server.log 2>&1 &
-- createdb gtmadrid
-- createlang plpgsql <yourdatabase>
-- /usr/local/pgsql$ psql -f ./share/contrib/postgis-1.5/postgis.sql -d gtmadrid
-- cat ./share/contrib/postgis-1.5/postgis.sql | sudo -u postgres /usr/local/pgsql/bin/psql mumbai_final
drop table stop_names;
CREATE TABLE stop_names (
_stopID varchar(7) PRIMARY KEY not null,
_stopName varchar(44) not null
);
CREATE INDEX ix_stop_names_stopName ON stop_names ( _stopName );
drop table stop_geo;
CREATE TABLE stop_geo (
_stopID varchar(7) PRIMARY KEY not null,
_stopLoc GEOMETRY NOT NULL
);
CREATE INDEX ix_stop_geo_loc ON stop_geo GIST ( _stopLoc );
drop table stops_on_trip;
CREATE TABLE stops_on_trip (
_tripID varchar(30) not null,
_stopID varchar(7) not null,
_stopSeq integer NOT NULL,
_stopDept time with time zone NOT NULL,
_stopDeptOnNextDay boolean not NULL,
_stopArri time with time zone NOT NULL,
_stopArriOnNextDay boolean not NULL,
PRIMARY KEY(_tripID, _stopID, _stopSeq)
);
CREATE INDEX ix_stops_on_trip_tripID ON stops_on_trip (_tripID);
CREATE INDEX ix_stops_on_trip_stopID ON stops_on_trip (_stopID);
CREATE INDEX ix_stops_on_trip_stopSeq ON stops_on_trip (_stopSeq);
CREATE INDEX ix_stops_on_trip_stopDept ON stops_on_trip (_stopDept);
CREATE INDEX ix_stops_on_trip_stopArri ON stops_on_trip (_stopArri);
CREATE INDEX ix_stops_on_trip_stopDeptOnNextDay ON stops_on_trip (_stopDeptOnNextDay);
CREATE INDEX ix_stops_on_trip_stopArriOnNextDay ON stops_on_trip (_stopArriOnNextDay);
CREATE INDEX ix_stops_on_trip_stopDeptEx ON stops_on_trip (_stopDept,_stopDeptOnNextDay);
CREATE INDEX ix_stops_on_trip_stopArriEx ON stops_on_trip (_stopArri,_stopArriOnNextDay);
drop table trips;
CREATE TABLE trips (
_tripID varchar(30) NOT NULL,
_routeID varchar(4) not null,
_serviceID varchar(15) NOT NULL,
_tripHeadSign varchar(17) not null,
PRIMARY KEY(_tripID)
);
CREATE INDEX ix_trips_routeID ON trips (_routeID);
CREATE INDEX ix_trips_serviceID ON trips (_serviceID);
CREATE INDEX ix_trips_tripHeadSign ON trips (_tripHeadSign);
drop table trips_freq;
CREATE TABLE trips_freq (
_tripID varchar(30) NOT NULL,
_start time with time zone NOT NULL,
_end time with time zone NOT NULL,
_end_next_day boolean not null,
_headways integer not null,
_freq integer default null
);
CREATE INDEX ix_trips_freq_tripID ON trips_freq (_tripID);
drop table routes;
CREATE TABLE routes (
_routeID varchar(4) not null,
_agencyID varchar(3) not null,
_routeName varchar(5) NOT NULL,
_routeLongName varchar(80) NOT NULL,
_routeType varchar(6) not NULL,
PRIMARY KEY(_routeID)
);
CREATE INDEX ix_routes_agencyID ON routes (_agencyID);
CREATE INDEX ix_routes_routeName ON routes (_routeName);
CREATE INDEX ix_routes_routeType ON routes (_routeType);
drop table schedule_rules;
CREATE TABLE schedule_rules (
_serviceID varchar(15) NOT NULL,
_serviceDay varchar(3) not null,
_startPeriodDate DATE not null,
_endPeriodDate DATE not null,
PRIMARY KEY(_serviceID, _serviceDay)
);
CREATE INDEX ix_schedule_rules_serviceID ON schedule_rules (_serviceID);
CREATE INDEX ix_schedule_rules_serviceDay ON schedule_rules (_serviceDay);
CREATE INDEX ix_schedule_rules_startPeriodDate ON schedule_rules (_startPeriodDate);
CREATE INDEX ix_schedule_rules_endPeriodDate ON schedule_rules (_endPeriodDate);
-- //////////////////////////////////////

106
android/db/create.sql Normal file
View File

@ -0,0 +1,106 @@
CREATE TABLE stop_names (
_stopID TEXT NOT NULL,
_stopName TEXT NOT NULL
);
CREATE INDEX ix_stop_names_stopName ON stop_names ( _stopName );
CREATE TABLE stop_geo (
_stopID varchar(7) PRIMARY KEY not null,
_stopLoc GEOMETRY not null
);
--SELECT AddGeometryColumn('stop_geo', '_stopLoc', 4326, 'POINT', 2);
CREATE INDEX ix_stop_geo_loc ON stop_geo ( _stopLoc );
/* CREATE TABLE stops_on_trip (
_tripID varchar(11) not null,
_stopID varchar(7) not null,
_stopSeq integer NOT NULL,
_stopDept time with time zone NOT NULL,
_stopDeptOnNextDay boolean not NULL,
_stopArri time with time zone NOT NULL,
_stopArriOnNextDay boolean not NULL,
PRIMARY KEY(_tripID, _stopID)
);
CREATE INDEX ix_stops_on_trip_tripID ON stops_on_trip (_tripID);
CREATE INDEX ix_stops_on_trip_stopID ON stops_on_trip (_stopID);
CREATE INDEX ix_stops_on_trip_stopSeq ON stops_on_trip (_stopSeq);
CREATE INDEX ix_stops_on_trip_stopDept ON stops_on_trip (_stopDept);
CREATE INDEX ix_stops_on_trip_stopArri ON stops_on_trip (_stopArri);
CREATE INDEX ix_stops_on_trip_stopDeptOnNextDay ON stops_on_trip (_stopDeptOnNextDay);
CREATE INDEX ix_stops_on_trip_stopArriOnNextDay ON stops_on_trip (_stopArriOnNextDay);
CREATE INDEX ix_stops_on_trip_stopDeptEx ON stops_on_trip (_stopDept,_stopDeptOnNextDay);
CREATE INDEX ix_stops_on_trip_stopArriEx ON stops_on_trip (_stopArri,_stopArriOnNextDay);
CREATE TABLE trips (
_tripID varchar(11) NOT NULL,
_routeID varchar(3) not null,
_serviceID varchar(2) not null,
_tripHeadSign varchar(17) not null,
PRIMARY KEY(_tripID)
);
CREATE INDEX ix_trips_routeID ON trips (_routeID);
CREATE INDEX ix_trips_serviceID ON trips (_serviceID);
CREATE INDEX ix_trips__tripHeadSign ON trips (_tripHeadSign); */
--///////////////////////////////////////////////////////////
CREATE TABLE stops_on_trip_frequency (
_uniqtripID varchar(31) not null,
_stopID varchar(7) not null,
_stopSeq integer NOT NULL,
PRIMARY KEY(_uniqtripID, _stopID)
);
CREATE INDEX ix_stops_on_trip_frequency_uniqtripID ON stops_on_trip_frequency (_uniqtripID);
CREATE INDEX ix_stops_on_trip_frequency_stopID ON stops_on_trip_frequency (_stopID);
CREATE INDEX ix_stops_on_trip_frequency_stopSeq ON stops_on_trip_frequency (_stopSeq);
CREATE TABLE trips_sum (
_tripID varchar(11) NOT NULL,
_routeID varchar(3) not null,
_serviceID varchar(2) not null,
_tripHeadSign varchar(17) not null,
_uniqtripID varchar(31) not null,
_start time with time zone NOT NULL,
_start_next_day boolean not null,
_end time with time zone NOT NULL,
_end_next_day boolean not null,
_freq integer not null,
PRIMARY KEY(_tripID)
);
CREATE INDEX ix_trips_routeID ON trips_sum (_routeID);
CREATE INDEX ix_trips_serviceID ON trips_sum (_serviceID);
CREATE INDEX ix_trips_tripHeadSign ON trips_sum (_tripHeadSign);
CREATE INDEX ix_trips_uniqtripID ON trips_sum (_uniqtripID);
CREATE TABLE schedule_rules (
_serviceID varchar(2) NOT NULL,
_serviceDay dayOfWeek not null,
_startPeriodDate DATE not null,
_endPeriodDate DATE not null,
PRIMARY KEY(_serviceID, _serviceDay)
);
CREATE INDEX ix_schedule_rules_serviceID ON schedule_rules (_serviceID);
CREATE INDEX ix_schedule_rules_serviceDay ON schedule_rules (_serviceDay);
CREATE INDEX ix_schedule_rules_startPeriodDate ON schedule_rules (_startPeriodDate);
CREATE INDEX ix_schedule_rules_endPeriodDate ON schedule_rules (_endPeriodDate);
CREATE TABLE routes (
_routeID varchar(3) not null,
_agencyID varchar(3) not null,
_routeName varchar(5) NOT NULL,
_routeLongName varchar(54) NOT NULL,
_routeType transportType not NULL,
PRIMARY KEY(_routeID)
);
CREATE INDEX ix_routes_agencyID ON routes (_agencyID);
CREATE INDEX ix_routes_routeName ON routes (_routeName);
CREATE INDEX ix_routes_routeType ON routes (_routeType);

View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.best.ui"
android:versionCode="1"
android:versionName="1.0">
<application android:label="@string/app_name"
android:icon="@drawable/bestlogo">
<activity android:name="Best" android:theme="@style/Theme.Transparent"
android:clearTaskOnLaunch="true"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"></action>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="SplashScreen1" android:theme="@style/Theme.Transparent" android:clearTaskOnLaunch="true" >
</activity>
<activity android:name="Find" android:configChanges="orientation|keyboardHidden" android:theme="@android:style/Theme.NoTitleBar" android:clearTaskOnLaunch="true"/>
<activity android:name="Routes" android:theme="@android:style/Theme.NoTitleBar" android:clearTaskOnLaunch="true" />
<activity android:name="Map" android:theme="@android:style/Theme.NoTitleBar" android:clearTaskOnLaunch="true" />
<activity android:name="ListLocation" android:theme="@android:style/Theme.Dialog" android:clearTaskOnLaunch="true" />
</application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-sdk android:minSdkVersion="4"
android:targetSdkVersion="8"
android:maxSdkVersion="11" />
</manifest>

12
android/mobile/TODO.txt Normal file
View File

@ -0,0 +1,12 @@
1. INdex shud be created for all the where columns.
2. Bus searching shud be different , either start of stmt or strat of word.
3. check splash screen in the start.
1. GPS shud be working and on near by stop show both, users location as well as near by bus location.
2. check performance of query.
Nikita:-
1. Reset max sdk version in AndroidManifest.xml in tag <uses-sdk>. Now it is set as API level 11.
2. Nearby stops button face.
3. Off GPS when not required.

View File

@ -0,0 +1,17 @@
# This file is used to override default values used by the Ant build system.
#
# This file must be checked in Version Control Systems, as it is
# integral to the build system of your project.
# This file is only used by the Ant script.
# You can use this to override default values such as
# 'source.dir' for the location of your java source folder and
# 'out.dir' for the location of your output folder.
# You can also use it define how the release builds are signed by declaring
# the following properties:
# 'key.store' for the location of your keystore and
# 'key.alias' for the name of the key to use.
# The password will be asked during the build when you use the 'release' target.

85
android/mobile/build.xml Normal file
View File

@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="chalobest" default="help">
<!-- The local.properties file is created and updated by the 'android' tool.
It contains the path to the SDK. It should *NOT* be checked into
Version Control Systems. -->
<loadproperties srcFile="local.properties" />
<!-- The ant.properties file can be created by you. It is only edited by the
'android' tool to add properties to it.
This is the place to change some Ant specific build properties.
Here are some properties you may want to change/update:
source.dir
The name of the source directory. Default is 'src'.
out.dir
The name of the output directory. Default is 'bin'.
For other overridable properties, look at the beginning of the rules
files in the SDK, at tools/ant/build.xml
Properties related to the SDK location or the project target should
be updated using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your
application and should be checked into Version Control Systems.
-->
<property file="ant.properties" />
<!-- The project.properties file is created and updated by the 'android'
tool, as well as ADT.
This contains project specific properties such as project target, and library
dependencies. Lower level build properties are stored in ant.properties
(or in .classpath for Eclipse projects).
This file is an integral part of the build system for your
application and should be checked into Version Control Systems. -->
<loadproperties srcFile="project.properties" />
<!-- quick check on sdk.dir -->
<fail
message="sdk.dir is missing. Make sure to generate local.properties using 'android update project'"
unless="sdk.dir"
/>
<!-- extension targets. Uncomment the ones where you want to do custom work
in between standard targets -->
<!--
<target name="-pre-build">
</target>
<target name="-pre-compile">
</target>
/* This is typically used for code obfuscation.
Compiled code location: ${out.classes.absolute.dir}
If this is not done in place, override ${out.dex.input.absolute.dir} */
<target name="-post-compile">
</target>
-->
<!-- Import the actual build file.
To customize existing targets, there are two options:
- Customize only one target:
- copy/paste the target into this file, *before* the
<import> task.
- customize it to your needs.
- Customize the whole content of build.xml
- copy/paste the content of the rules files (minus the top node)
into this file, replacing the <import> task.
- customize to your needs.
***********************
****** IMPORTANT ******
***********************
In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
in order to avoid having your file be overridden by tools such as "android update project"
-->
<!-- version-tag: 1 -->
<import file="${sdk.dir}/tools/ant/build.xml" />
</project>

7
android/mobile/deploy.sh Normal file
View File

@ -0,0 +1,7 @@
#!/bin/bash
#
#
pushd bin/
/cygdrive/c/Program\ Files/Android/android-sdk-windows/platform-tools/adb.exe install chalobest-debug.apk
popd

View File

@ -0,0 +1,2 @@
set solib-search-path /root/android_spatial_test/spatialite-android-read-only/spatialite-android/obj/local/armeabi
directory /root/android_spatial_test/android-ndk-r7b/platforms/android-14/arch-arm/usr/include /root/android_spatial_test/spatialite-android-read-only/spatialite-android/jni/geos-3.2.2/source/headers /root/android_spatial_test/android-ndk-r7b/sources/cxx-stl/gnu-libstdc++/include /root/android_spatial_test/android-ndk-r7b/sources/cxx-stl/gnu-libstdc++/libs/armeabi/include /root/android_spatial_test/spatialite-android-read-only/spatialite-android/jni/libiconv-1.13.1 /root/android_spatial_test/spatialite-android-read-only/spatialite-android/jni/libiconv-1.13.1/include /root/android_spatial_test/spatialite-android-read-only/spatialite-android/jni/libiconv-1.13.1/lib /root/android_spatial_test/spatialite-android-read-only/spatialite-android/jni/libiconv-1.13.1/libcharset/include /root/android_spatial_test/spatialite-android-read-only/spatialite-android/jni/libspatialite-amalgamation-3.0.1/headers/spatialite /root/android_spatial_test/spatialite-android-read-only/spatialite-android/jni/javasqlite-20120209/native/ /root/android_spatial_test/spatialite-android-read-only/spatialite-android/jni/proj-4.7.0/src geos-3.2.2/capi

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,10 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must *NOT* be checked in Version Control Systems,
# as it contains information specific to your local configuration.
# location of the SDK. This is only used by Ant
# For customization when using a Version Control System, please read the
# header note.
sdk.dir=C:\\Program Files\\Android\\android-sdk-windows

View File

@ -0,0 +1,40 @@
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontpreverify
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class com.android.vending.licensing.ILicensingService
-keepclasseswithmembernames class * {
native <methods>;
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}
-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}

View File

@ -0,0 +1,11 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "ant.properties", and override values to adapt the script to your
# project structure.
# Project target.
target=android-8

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
/* //device/apps/common/res/anim/ease_in_interpolator.xml
**
** Copyright 2007, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
-->
<accelerateInterpolator xmlns:android="http://schemas.android.com/apk/res/android" factor="1" />

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
/* //device/apps/common/res/anim/ease_out_interpolator.xml
**
** Copyright 2007, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
-->
<decelerateInterpolator xmlns:android="http://schemas.android.com/apk/res/android" factor="1" />

View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
/* //device/apps/common/res/anim/fade_in.xml
**
** Copyright 2007, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
-->
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@anim/decelerate_interpolator">
<scale android:fromXScale="0.9" android:toXScale="1.0"
android:fromYScale="0.9" android:toYScale="1.0"
android:pivotX="50%" android:pivotY="50%"
android:duration="3000" />
<alpha android:fromAlpha="0.0" android:toAlpha="1.0"
android:duration="3000" />
</set>

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
/* //device/apps/common/res/anim/fade_out.xml
**
** Copyright 2007, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
-->
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@anim/accelerate_interpolator">
<scale android:fromXScale="1.0" android:toXScale="0.9"
android:fromYScale="1.0" android:toYScale="0.9"
android:pivotX="50%" android:pivotY="50%"
android:duration="2000" />
<alpha android:fromAlpha="1.0" android:toAlpha="0.0"
android:duration="2000"/>
</set>

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale android:fromXScale="0.6" android:toXScale="1.0"
android:fromYScale="0.6" android:toYScale="1.0"
android:pivotX="50%" android:pivotY="50%"
android:duration="500" />
<alpha android:interpolator="@anim/decelerate_interpolator"
android:fromAlpha="0.0" android:toAlpha="1.0"
android:duration="500" />
</set>

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale android:fromXScale="0.6" android:toXScale="1.0"
android:fromYScale="0.6" android:toYScale="1.0"
android:pivotX="50%" android:pivotY="50%"
android:duration="500" />
<alpha android:interpolator="@anim/accelerate_interpolator"
android:fromAlpha="0.0" android:toAlpha="1.0"
android:duration="500" />
</set>

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false">
<shape>
<gradient
android:startColor="#ebebeb"
android:endColor="#b6b4b6"
android:angle="270" />
<stroke
android:width="1dp"
android:color="#b4b5b4" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<item android:state_pressed="true"
android:drawable="@drawable/focused_application_background_static" />
<item android:state_focused="true"
android:drawable="@drawable/focused_application_background_static" />
</selector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 253 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 864 B

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:startColor="#ebebeb"
android:endColor="#b6b4b6"
android:angle="270" />
<corners
android:radius="4dp" />
<stroke
android:width="1dp"
android:color="#767373" />
</shape>
</item>
</selector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 791 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/focused_application_background_static" />
<item android:state_focused="true"
android:drawable="@drawable/focused_application_background_static" />
</selector>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false"
android:drawable="@android:drawable/editbox_background" />
<item android:state_pressed="true"
android:drawable="@drawable/focused_application_background_static" />
<item android:state_focused="true"
android:drawable="@drawable/focused_application_background_static" />
</selector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 363 B

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:state_focused="true"
android:state_selected="true"
android:state_checkable="true"
android:state_checked="true"
android:state_enabled="true"
android:state_window_focused="true" />
</selector>
<!-- android:drawable="@android:drawable/btn_application_selector"-->

Binary file not shown.

After

Width:  |  Height:  |  Size: 350 B

View File

@ -0,0 +1,233 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rellayoutmain"
android:background="#efefef"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="@+id/titlelinearlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/besthead"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="@drawable/bestheadbar"/>
</LinearLayout>
<!--<LinearLayout
android:id="@+id/titlelinearlayout"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:background="#d2d3d2"
android:gravity="center"
android:layout_marginTop="10dp">
<ImageView
android:id="@+id/busicon"
android:layout_width="0dp"
android:layout_weight="0.1"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:src="@drawable/appicon"/>
<TextView
android:id="@+id/title_bar_text"
android:textColor="#070707"
android:text="Chalobest"
android:fadingEdge="horizontal"
android:textSize="16sp"
android:gravity="center_vertical"
android:layout_width="0dp"
android:layout_weight="0.7"
android:layout_height="40dp" />
<ImageButton
android:id="@+id/expandable"
android:layout_width="29dp"
android:layout_height="30dp"
android:layout_marginRight="10dp"
android:background="@drawable/image_btn_pressd"
android:src="@drawable/ic_minus_trans"
android:visibility="invisible"/>
<ImageButton
android:id="@+id/expandable"
android:layout_weight="0.079"
android:layout_marginTop="5dp"
android:layout_marginRight="15dp"
android:layout_alignParentRight="true"
android:src="@drawable/ic_minus_trans"/
</LinearLayout>-->
<ScrollView
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:layout_below="@id/titlelinearlayout">
<LinearLayout
android:id="@+id/mainlinearlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/explinearlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="@+id/linearlayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp">
<EditText
android:id="@+id/fromtxt"
android:layout_width="0dp"
android:layout_weight="0.7"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/findfrom"
android:layout_marginLeft="5dp"
android:paddingLeft="10dp"
android:background="@drawable/edittext"
android:singleLine="true"
android:hint="@+string/sourceHint"/>
<ImageButton
style="@android:style/Widget.Button.Inset"
android:id="@+id/findfrom"
android:layout_width="0dp"
android:layout_weight="0.1"
android:layout_height="35dp"
android:layout_marginLeft="10dp"
android:layout_toRightOf="@id/fromtxt"
android:background="@drawable/image_btn_pressd"
android:src="@drawable/magglass_tot_trans"/>
<Button
android:id="@+id/nearFrom"
android:layout_width="0dp"
android:layout_weight="0.1"
android:layout_height="35dp"
android:layout_gravity="right"
android:soundEffectsEnabled="true"
layout_alignRight="linearlayout1"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:background="@drawable/blue_button"
android:text="@+string/nearbyBtnText" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearlayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="15dp"
android:layout_below="@id/linearlayout1">
<EditText
android:id="@+id/totxt"
android:layout_width="0dp"
android:layout_weight="0.7"
android:layout_height="30dp"
android:paddingLeft="10dp"
android:layout_marginLeft="5dp"
android:background="@drawable/edittext"
android:layout_below="@id/fromtxt"
android:singleLine="true"
android:hint="@+string/destinationHint"/>
<ImageButton
android:id="@+id/findto"
android:layout_width="0dp"
android:layout_weight="0.1"
android:layout_height="35dp"
android:layout_marginLeft="10dp"
android:soundEffectsEnabled="true"
android:layout_toRightOf="@id/totxt"
android:background="@drawable/image_btn_pressd"
android:src="@drawable/magglass_tot_trans"/>
<Button
android:id="@+id/nearTo"
android:layout_width="0dp"
android:layout_weight="0.1"
android:layout_height="35dp"
android:layout_gravity="right"
android:soundEffectsEnabled="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:background="@drawable/blue_button"
android:text="@+string/nearbyBtnText" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearlayout3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal"
android:layout_marginTop="15dp"
android:layout_below="@id/linearlayout2">
<Button
android:id="@+id/findbus"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:gravity="center_horizontal"
android:soundEffectsEnabled="true"
android:background="@drawable/blue_button"
android:text="@+string/findBusText" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/linearlayout4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_below="@id/linearlayout3">
<TextView
android:id="@+id/txthead"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:padding="10dp"
android:text="@+string/busListHead"
android:background="#d2d2d2"
android:textColor="#070707"
android:visibility="invisible"/>
</LinearLayout>
<LinearLayout
android:id="@+id/linearlayout5"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_below="@id/linearlayout4">
<com.best.ui.ExpandedListView
android:id="@android:id/list"
android:label="Buses"
android:background="#efefef"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollY="0dp"
android:dividerHeight="0dp"
android:scrollbarSize="0dp"
android:fastScrollEnabled="false"
android:scrollbars="none"
/>
</LinearLayout>
</LinearLayout>
</ScrollView >
</RelativeLayout>
<!-- style="?android:attr/windowTitleStyle"-->

View File

@ -0,0 +1,89 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/linearlayoutlist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@drawable/listbackgrnd"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:id="@+id/innerlinearlayoutlist1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/busBlue"
android:layout_width="0dp"
android:layout_weight="0.1"
android:gravity="center"
android:layout_height="wrap_content"
android:src="@drawable/bus_blue_small"
android:background="@null"/>
<TextView
android:id="@+id/routename"
android:layout_width="0dp"
android:layout_weight="0.1"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="17sp"
android:paddingLeft="0dp"
android:textColor="#5a5858"/>
<!--<TextView
android:id="@+id/routename"
android:layout_width="0dp"
android:layout_weight="0.15"
android:layout_height="wrap_content"
android:gravity="center"
android:text="towards"
android:textSize="12sp"
android:paddingLeft="0dp"
android:textColor="#5a5858"/>-->
<TextView
android:id="@+id/bushead"
android:layout_width="0dp"
android:layout_weight="0.8"
android:layout_height="wrap_content"
android:gravity="left"
android:textSize="17sp"
android:paddingLeft="10dp"
android:textColor="#4a81af"/>
</LinearLayout>
<LinearLayout
android:id="@+id/innerlinearlayoutlist2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="10dp"
android:layout_below="@+id/innerlinearlayoutlist1">
<TextView
android:id="@+id/totaldist"
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="14sp"
android:paddingLeft="0dp"
android:textColor="#5a5858"/>
<TextView
android:id="@+id/stopsno"
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="14sp"
android:paddingLeft="0dp"
android:textColor="#5a5858"/>
</LinearLayout>
</LinearLayout>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp"
android:background="@drawable/listbackgrnd"
android:textColor="#4a81af">
</TextView>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/focused_application_background_static" />
<item android:state_focused="true"
android:drawable="@drawable/focused_application_background_static" />
</selector>

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout
android:id="@+id/newentrylayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Spinner
android:id="@+id/locationdropdown"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/newentrylayout"/>
</RelativeLayout>
</ScrollView>

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/linearlayoutlist1"
android:label="Somelabel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:background="@android:drawable/editbox_background"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/stopname"
android:layout_width="0dp"
android:layout_weight="0.75"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="#4a81af">
</TextView>
<TextView
android:id="@+id/dep"
android:layout_width="0dp"
android:layout_weight="0.25"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="16sp"
android:textColor="#5a5858">
</TextView>
</LinearLayout>
<!-- android:padding="10dp"-->

View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/mainlinearlayout"
android:label="Somelabel1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:background="@drawable/listbackgrnd"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:id="@+id/innerlinearlayout"
android:label="Somelabel1"
android:layout_width="0dp"
android:layout_weight="0.8"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@android:drawable/editbox_background">
<TextView
android:id="@+id/stopname"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:textColor="#4a81af"/>
<TextView
android:id="@+id/dist"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:textColor="#5a5858"
android:layout_below="@+id/stopname"/>
</LinearLayout>
<Button
android:id="@+id/map"
android:layout_width="0dp"
android:layout_weight="0.2"
android:layout_height="50dp"
android:text="Map" />
</LinearLayout>
<!--android:background="@android:drawable/editbox_background" android:layout_alignParentBottom="true" android:paddingTop="10dp"-->

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<org.osmdroid.views.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
/>

View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/routeslayout"
android:layout_width="fill_parent"
android:background="#efefef"
android:layout_height="fill_parent" >
<LinearLayout
android:id="@+id/listheader1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#d2d2d2"
android:padding="10dp">
<TextView
android:id="@+id/stopnameHead"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="Stop Name"
android:textColor="#070707">
</TextView>
</LinearLayout>
<LinearLayout
android:id="@+id/linearlayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/listheader1">
<ListView
android:id="@android:id/list"
android:label="Buses"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
</LinearLayout>
</RelativeLayout>

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2006 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="fill_parent"
android:layout_height="20dp"
android:background="@android:drawable/editbox_background"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#2489ce"
android:typeface="monospace"
android:gravity="center"
android:paddingLeft="6dip"
/>

View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center"
android:id="@+id/TheSplashLayout"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/SplashImageView"
android:layout_gravity="center"
android:src="@drawable/bestlogo" >
</ImageView>
<TextView
android:id="@+id/msgtxt"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:paddingTop="15dp"
android:text="@+string/inittext"
android:layout_gravity="center"
android:background="#000000"
android:textColor="#f9f9f9"
android:layout_below="@id/SplashImageView"/>
</LinearLayout>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/fullRoute"
android:icon="@drawable/ic_tab_newsel"
android:title="Full Route" />
<item android:id="@+id/map"
android:icon="@drawable/ic_tab_newsel"
android:title="Map" />
</menu>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/mnuexitmain"
android:icon="@drawable/ic_tab_newsel"
android:title="Exit" />
</menu>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/map"
android:icon="@drawable/ic_tab_newsel"
android:title="Map" />
</menu>

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Best</string>
<string name="M_FIND_TAB_ID">find</string>
<string name="M_ROUT_TAB_ID">route</string>
<string name="fromListTitle">Select Your Start Location</string>
<string name="toListTitle">Select Destination</string>
<string name="nearByListTitle">Nearby Stops:</string>
<string name="sourceHint">Start: eg.Churchgate</string>
<string name="destinationHint">Destination: eg.Fort</string>
<string name="findBtnText">F</string>
<string name="nearbyBtnText">N</string>
<string name="findBusText">Find Bus</string>
<string name="busListHead">Buses Available</string>
<string name="inittext">Initializing Application for the first time...</string>
<string name="errMsgMoreChar">Please enter some more characters..</string>
<string name="errMsgEnterSrcLoc">Please enter some source location..</string>
<string name="errMsgEnterDestLoc">Please enter some destination location..</string>
<string name="errMsgEnterValidDest">Enter valid destination</string>
<string name="errMsgEnterValidSrc">Enter valid Source location</string>
<string name="errMsgNoStopsMatch">No matching stops found</string>
<string name="errMsgNoNearbyStop">No stops found near by</string>
<string name="noLocation">No such Location</string>
<string name="errNoMap">Sorry, unable to show map at this time.</string>
</resources>

View File

@ -0,0 +1,17 @@
<resources>
<style name="Theme.Transparent" parent="android:Theme">
<item name="android:windowNoTitle">true</item>
<item name="android:windowAnimationStyle">@style/Animations.SplashScreen</item>
</style>
<style name="Animations" parent="@android:Animation" />
<style name="Animations.SplashScreen">
<item name="android:windowEnterAnimation">@anim/fade_in_center</item>
<item name="android:windowExitAnimation">@anim/fade_out_center</item>
</style>
<declare-styleable name="ExpandablePanel">
<attr name="handle" format="reference" />
<attr name="content" format="reference" />
<attr name="collapsedHeight" format="dimension"/>
<attr name="animationDuration" format="integer"/>
</declare-styleable>
</resources>

View File

@ -0,0 +1,145 @@
////////////////////////////////////////////////
//
// A ChaloBEST (http://chalobest.in/) initiative
// Author: Vivek (Macgregor Techknowlogy)
// License: GPLv3
//
//
package com.best.data;
import java.util.List;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Hashtable;
import jsqlite.Callback;
import jsqlite.Exception;
import jsqlite.Stmt;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.util.Vector;
import android.content.Context;
import com.best.ui.Best;
import java.util.zip.GZIPInputStream;
public class DBHandle {
private static final String TAG = DBHandle.class.getName();
public static Context me = null;
public static String _DB_NAME = "chalobest";
public static String _DATA_DIR = "data";
public static String _DB_PATH = "data";
public static int _DB_FILE_IDENTIFIER = com.best.ui.R.raw.chalobest_sqlite;
public static void init(Context cont)
{me = cont;}
public static String[][] execQuery(String query , int maxRows)
{
String[][] resultSet = new String[ maxRows ][];
List<String[]> listResultSet = new ArrayList<String[]>();
try
{
if( maxRows > 0 )
{
jsqlite.Database db = new jsqlite.Database();
db.open( _DB_PATH, jsqlite.Constants.SQLITE_OPEN_READONLY );
Stmt resHandle = db.prepare( query );
int resCounter = 0;
while ( resHandle.step() )
{
if( resCounter < maxRows )
{
int no_col = resHandle.column_count();
resultSet[ resCounter ] = new String[ no_col ];
for(int index=0;index<no_col;index++)
resultSet[ resCounter ][ index ] = resHandle.column_string( index );
listResultSet.add(resultSet[ resCounter ]);
resCounter++;
}
}
}
} catch (Exception e) {System.out.println("DBHandle Excep:"+e.getMessage()); e.printStackTrace();}
return( listResultSet.toArray( new String[ listResultSet.size() ][] ) );
}
public static String[][] execQuery(String query)
{
Hashtable resultSet = new Hashtable();
String[][] ret = null;
int no_col = -1;
try
{
jsqlite.Database db = new jsqlite.Database();
db.open( _DB_PATH, jsqlite.Constants.SQLITE_OPEN_READONLY );
Stmt resHandle = db.prepare( query );
int resCounter = 0;
while ( resHandle.step() )
{
no_col = resHandle.column_count();
String[] row = new String[ no_col ];
for(int index=0; index < no_col; index++ )
row[ index ] = resHandle.column_string( index );
resultSet.put( resCounter, row );
resCounter++;
}
if( resultSet.size() > 0 && no_col > 0 )
{
ret = new String[ resultSet.size() ][ no_col ];
for(int cnt = 0; cnt < resultSet.size(); cnt++ )
{
ret[ cnt ] = ( String[] )resultSet.get( cnt );
}
}
} catch (Exception e) { System.out.println("DBHandle Excep:"+e.getMessage()); e.printStackTrace();}
return( ret );
}
public static boolean dbFileReady()
{
try{
File dataPath = me.getDir( _DATA_DIR, 0 );
File DBFile = new File( dataPath, _DB_NAME );
if(!DBFile.exists())
{
DBFile.createNewFile();
InputStream dbin = me.getResources().openRawResource( _DB_FILE_IDENTIFIER );
GZIPInputStream gzin = new GZIPInputStream( dbin );
OutputStream os = new FileOutputStream( DBFile );
int r;
byte []b = new byte[ 1024 ];
while((r = gzin.read(b)) != -1)
os.write(b, 0, r);
dbin.close();
os.close();
}
_DB_PATH = DBFile.getAbsolutePath();
return( true );
}catch(java.lang.Exception e){ Best.log( " DBHandle ERR : " +e.getMessage() ); e.printStackTrace(); }
return( false );
}
}

View File

@ -0,0 +1,759 @@
////////////////////////////////////////////////
//
// A ChaloBEST (http://chalobest.in/) initiative
// Author: Vivek (Macgregor Techknowlogy)
// License: GPLv3
//
//
package com.best.data;
import java.util.Vector;
import java.util.Hashtable;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Date;
import java.util.Calendar;
import java.util.Hashtable;
import org.osmdroid.util.GeoPoint;
import java.util.ArrayList;
import com.best.ui.Best;
import com.best.util.Funcs;
public class GTStore{
public static int M_MAX_STOP_SEARCH_ROW_BY_TEXT = 30;
public static int M_MAX_RANGE = 500;
public static int M_STOP_NEAR_POINT_DISTANCE_INDEX = 0;
public static int M_STOP_NEAR_POINT_LAT_INDEX = 1;
public static int M_STOP_NEAR_POINT_LON_INDEX = 2;
public static int M_STOP_INFO_ID_INDEX = 0;
public static int M_STOP_INFO_LAT_INDEX = 1;
public static int M_STOP_INFO_LON_INDEX = 2;
public static int M_STOP_INFO_SEQ_INDEX = 3;
public static int M_STOP_INFO_ARR_TIME_INDEX = 4;
public static int M_STOP_INFO_ARR_DISTANCE_INDEX = 5;
public static double M_WALING_DISTANCE_KM = 0.3;
public static double GEO_DELTA = 0.003;
public static String[][] getAllStopsByText(String matchString, Double lat, Double lon)
{
try{
String query = "select g._stopID, _stopName, Distance( _stopLoc ,ST_GeomFromText('POINT("+ lat +" "+ lon +" )'))*111 distance from stop_names n, stop_geo g where n._stopID = g._stopID and ( _stopName like '"+matchString+"%' or _stopName like '% "+matchString+"%' ) limit "+M_MAX_STOP_SEARCH_ROW_BY_TEXT+";";
System.out.println("===query=="+query);
String[][] resultSet=DBHandle.execQuery( query, M_MAX_STOP_SEARCH_ROW_BY_TEXT );
return( resultSet );
}catch(Exception e){ System.out.println("===EXEC ERR=="+e.getMessage() ); }
return( null );
}
public static String[][] getNearByStops(Double lat, Double lon)
{
String[][] resultSet = DBHandle.execQuery( "select g._stopID,_stopName, Distance( _stopLoc, ST_GeomFromText('POINT(" + lat + " " + lon + ")') )*111 distance from stop_geo g, stop_names n where g._stopID = n._stopID and PtDistWithin( _stopLoc, ST_GeomFromText('POINT(" + lat + " " + lon + ")', 4326),"+M_MAX_RANGE+") order by distance asc limit 30;", M_MAX_STOP_SEARCH_ROW_BY_TEXT );
return(resultSet);
}
public static String[][] getLatitudeLongitude(String stopID)
{
String[][] resultSet=DBHandle.execQuery( "select _stopID,X(_stopLoc),Y(_stopLoc) from stop_geo where stop_geo._stopID="+stopID+";", 1 );
return(resultSet);
}
/* public static String[][] getRoutes(String fromStopID, String toStopID, String day, String timeStart,String timeEnd)
{
try{
// String _qryForAllRouteForFromStop = "select stops_on_trip._tripid , stops_on_trip._stopid, stops_on_trip._stopseq, stops_on_trip._stopdept,stops_on_trip._stopDeptOnNextDay from stops_on_trip, trips, schedule_rules where stops_on_trip._tripid = trips._tripid and trips._serviceid = schedule_rules._serviceid and stops_on_trip._stopid='"+fromStopID+"' and schedule_rules._serviceday='"+day+"' and schedule_rules._startperioddate<=date('now') and date('now')<=schedule_rules._endperioddate and stops_on_trip._stopDept > strftime('%H:%M:%S', '"+timeStart+"') and strftime('%H:%M:%S', '"+timeEnd+"') >(stops_on_trip._stopDept) and stops_on_trip._stopDeptOnNextDay=0";
// String _qryForAllRouteForFromStop = "select stops_on_trip._tripid , stops_on_trip._stopid, stops_on_trip._stopseq, stops_on_trip._stopdept,stops_on_trip._stopDeptOnNextDay from stops_on_trip, trips, schedule_rules where stops_on_trip._tripid = trips._tripid and trips._serviceid = schedule_rules._serviceid and stops_on_trip._stopid='714' and schedule_rules._serviceday='Thu'and strftime('%Y%m%d',schedule_rules._startperioddate) <=strftime('%Y%m%d','20120117') and strftime('%Y%m%d','20120117') <= strftime('%Y%m%d',schedule_rules._endperioddate) and stops_on_trip._stopDept > strftime('%H:%M:%S', '09:00:00') and strftime('%H:%M:%S', '09:25:00') >(stops_on_trip._stopDept) and stops_on_trip._stopDeptOnNextDay=0;";
String _qryForAllRouteForFromStop = "select stops_on_trip_frequency._uniqtripID,stops_on_trip_frequency._stopid, stops_on_trip_frequency._stopseq, trips_sum._tripid, trips_sum._start, trips_sum._start_next_day, trips_sum._freq, st_distance( stop_geo._stopLoc , st_pointFromText( 'POINT( lat lon )' ) )*111 as distd from stop_geo, stops_on_trip_frequency, schedule_rules, trips_sum where trips_sum._uniqtripID = stops_on_trip_frequency._uniqtripID and trips_sum._serviceid = schedule_rules._serviceid and stops_on_trip_frequency._stopid=stop_geo._stopid and schedule_rules._serviceday='Thu' and schedule_rules._startperioddate <='2012-01-17' and '2012-01-17' <= schedule_rules._endperioddateand stops_on_trip_frequency._stopid in ('714') order by distd;";
String[][] resultSet = DBHandle.execQuery( _qryForAllRouteForFromStop, M_MAX_STOP_SEARCH_ROW_BY_TEXT );
Hashtable _allEmergingRoutes = null;
if( resultSet != null )
{
String _tripIdSet = "";
_allEmergingRoutes = new Hashtable( resultSet.length );
for( int cnt=0; cnt < resultSet.length; cnt++ )
{
Vector _tripInfo = new Vector( 2 );
String _tripId = resultSet[ cnt ][ 0 ];
_tripInfo.add( resultSet[ cnt ][ 2 ] ); //StopSequence
_tripInfo.add( resultSet[ cnt ][ 3 ] ); //deprtrTime
_allEmergingRoutes.put( _tripId, _tripInfo );//trip id is key
_tripIdSet += ( ( cnt > 0 )?( "," ):( "" ) ) + "'"+_tripId+"'";
}
if( _tripIdSet.length() > 0 )
{
// String _qryForAllRouteForToStop = "select stops_on_trip._tripid, trips._tripHeadSign, routes._routeName, stops_on_trip._stopid , stops_on_trip._stopseq, stops_on_trip._stopArri, stops_on_trip._stopArriOnNextDay from stops_on_trip, stop_geo, trips, routes, schedule_rules where routes._routeID=trips._routeID and stops_on_trip._stopid=stop_geo._stopid and stops_on_trip._tripid=trips._tripid and trips._serviceid=schedule_rules._serviceid and schedule_rules._serviceday='"+ day +"' and schedule_rules._startperioddate<=date('now') and date('now')<=schedule_rules._endperioddate and trips._tripid in ("+ _tripIdSet +") and stops_on_trip._Stopid='"+toStopID+"';";
String _qryForAllRouteForToStop = "select stops_on_trip._tripid, trips._tripHeadSign, routes._routeName, stops_on_trip._stopid , stops_on_trip._stopseq, stops_on_trip._stopArri, stops_on_trip._stopArriOnNextDay from stops_on_trip, stop_geo, trips, routes, schedule_rules where routes._routeID=trips._routeID and stops_on_trip._stopid=stop_geo._stopid and stops_on_trip._tripid=trips._tripid and trips._serviceid=schedule_rules._serviceid and schedule_rules._serviceday='Thu' and strftime('%Y%m%d',schedule_rules._startperioddate)<=strftime('%Y%m%d','20120117') and strftime('%Y%m%d','20120117')<=strftime('%Y%m%d',schedule_rules._endperioddate ) and trips._tripid in ( 'LA0010052','LA0010053','LA0010081','LA0010082' ) and stops_on_trip._Stopid='1750';";
resultSet = DBHandle.execQuery( _qryForAllRouteForToStop, M_MAX_STOP_SEARCH_ROW_BY_TEXT );
if( resultSet != null && resultSet.length > 0 )
{
String[][] _returnArr = new String[ resultSet.length ][ 6 ];
for( int cnt=0; cnt < resultSet.length; cnt++ )
{
String _tripId = resultSet[ cnt ][ 0 ];
if( _allEmergingRoutes.containsKey( _tripId ) )
{
Vector v = ( Vector )_allEmergingRoutes.get( _tripId );
int _fromStopSeq = Integer.parseInt( ( String ) v.elementAt( 0 ) );
String _deptTime = ( String ) v.elementAt( 1 );
String _tripHeadSign = resultSet[ cnt ][ 1 ];
String _routeName = resultSet[ cnt ][ 2 ];
int _toStopSeq = Integer.parseInt( resultSet[ cnt ][ 4 ] );
String _arrivalTime = resultSet[ cnt ][ 5 ];
Best.log( _routeName+" -- "+_tripHeadSign+" -- "+(_toStopSeq - _fromStopSeq)+" -- "+_deptTime+" -- "+_arrivalTime );
if( _toStopSeq > _fromStopSeq )
{
_returnArr[ cnt ][ 0 ] = _tripId;
_returnArr[ cnt ][ 1 ] = _routeName;
_returnArr[ cnt ][ 2 ] = _tripHeadSign;
_returnArr[ cnt ][ 3 ] = (_toStopSeq - _fromStopSeq)+"";
_returnArr[ cnt ][ 4 ] = _deptTime;
_returnArr[ cnt ][ 5 ] = _arrivalTime;
}
}
//else shud never happen
}
return( _returnArr );
}
}
}
}catch(Exception e){}
return( null );
} */
public static String[][] getTripInfo(String tripID)
{
String q = "select _stopName, stop_names._stopID _stopID, _stopSeq ,X(_stopLoc),Y(_stopLoc) from trips, stops_on_trip, stop_names, stop_geo where trips._tripID = '"+tripID+"' and trips._tripID = stops_on_trip._tripID and stops_on_trip._stopID = stop_names._stopID and stop_geo._stopID = stop_names._stopID order by _stopSeq asc";
return ( DBHandle.execQuery( q ) );
}
/* public static Vector searchRoutes(int rec_level,String fromStopId,String lat_from,String lon_from,String lat_to,String lon_to,Calendar dept_date,Calendar dept_time)
{
double waling_distance_km = 0.3;
rec_level++;
Hashtable singleUniqueTrips = new Hashtable();
Hashtable tripTimes = new Hashtable();
Hashtable doneTrips = new Hashtable();
Vector workingTrips = null;
String dept_day = Funcs.getCurrentDay();
String q = "select stops_on_trip_frequency._uniqtripID,stops_on_trip_frequency._stopid, stops_on_trip_frequency._stopseq, trips_sum._tripid, trips_sum._start, trips_sum._start_next_day, trips_sum._freq, st_distance( stop_geo._stopLoc , st_pointFromText( 'POINT( "+lat_from+" "+lon_from+")' ) )*111 as distd from stop_geo, stops_on_trip_frequency, schedule_rules, trips_sum where trips_sum._uniqtripID = stops_on_trip_frequency._uniqtripID and trips_sum._serviceid = schedule_rules._serviceid and stops_on_trip_frequency._stopid=stop_geo._stopid and schedule_rules._serviceday='"+dept_day+"' and schedule_rules._startperioddate<=date( 'now' ) and date( 'now' )<=schedule_rules._endperioddate and stops_on_trip_frequency._stopid = '"+fromStopId+"' order by distd ;";
String[][] resultSet = DBHandle.execQuery( q );
if( resultSet != null )
{
for( int cnt = 0; cnt <= resultSet.length; cnt++ )
{
String utripID = resultSet[ cnt ][ 0 ];
String tripID = resultSet[ cnt ][ 3 ];
if( ! singleUniqueTrips.containsKey( utripID ) )
{
String stopID = resultSet[ cnt ][ 1 ];
int stopSeq = Integer.parseInt( resultSet[ cnt ][ 2 ] );
boolean start_time_tom = ( resultSet[ cnt ][5].equals( "t" ) );
String _dept_time = resultSet[ cnt ][ 4 ];
//TODO: needs to reworked
Calendar start_time = Funcs.addTime( dept_date, _dept_time );
if( !start_time_tom )
start_time = Funcs.getNextDay( start_time );
int stop_freq = Integer.parseInt( resultSet[ cnt ][ 6 ] );
long stop_time = ( start_time.getTimeInMillis() + ( stopSeq * stop_freq) );
/////////////////
if( ( ( stop_time - 1500 ) < dept_time.getTimeInMillis() ) && ( ( stop_time + 1500 ) > dept_time.getTimeInMillis() ) )
{
Vector v = new Vector();
v.add( start_time );
v.add( stop_freq );
tripTimes.put( tripID, v );
Vector vTripInfo = init_dec( stopID, lat_from, lon_from, stopSeq+"", stop_time+"", "" );
singleUniqueTrips.put( utripID, vTripInfo );
}
}
}
allKeys = tripTimes.keys();
String trip_list = "";
while( allKeys.hasMoreElements() )
trip_list = ( ( trip_list.length() > 0 )?( "," ):( "" ) )+"'"+( String )allKeys.nextElement()+"'";
if( singleUniqueTrips.size() > 0 )
{
q = "select stops_on_trip_frequency._uniqtripID, trips_sum._tripID, trips_sum._tripHeadSign, routes._routeName, stops_on_trip_frequency._stopid , stops_on_trip_frequency._stopseq, st_distance( stop_geo._stopLoc , st_pointFromText( 'POINT( "+lat_to+" "+lon_to+")' ) )*111 as distd, ST_X( stop_geo._stopLoc ) as xlat, ST_Y( stop_geo._stopLoc ) as ylon from stops_on_trip_frequency, stop_geo, trips_sum, routes where stops_on_trip_frequency._uniqtripID=trips_sum._uniqtripID and routes._routeID=trips_sum._routeID and stops_on_trip_frequency._stopid=stop_geo._stopid and trips_sum._tripID in ("+trip_list+") order by trips_sum._tripID, distd ;";
resultSet = DBHandle.execQuery( q );
if( resultSet != null )
{
int max_check = 0;
for( int cnt = 0; cnt <= resultSet.length; cnt++ )
{
String utripID = resultSet[ cnt ][ 0 ];
String tripID = resultSet[ cnt ][ 1 ];
String tripSign = resultSet[ cnt ][ 2 ];
String routeName = resultSet[ cnt ][ 3 ];
String stopID = resultSet[ cnt ][ 4 ];
int stopSeq = Integer.parseInt( resultSet[ cnt ][ 5 ] );
double stopDistanceFromDestination = Double.parseDouble( resultSet[ cnt ][ 6 ] );
String stopLat = resultSet[ cnt ][ 7 ];
String stopLon = resultSet[ cnt ][ 8 ];
if( !doneTrips.containsKey( utripID ) )
{
Vector start_stop_dec = ( Vector ) singleUniqueTrips.get( utripID );
if( start_stop_dec.size() == 6 )
{
int stored_stopSeq = Integer.parseInt( (String)start_stop_dec.elementAt( 3 ) );
if( stored_stopSeq < stopSeq )
{
if( stopDistanceFromDestination <= waling_distance_km )
{
Vector tripVector = ( Vector )tripTimes.get( tripID );
long stop_arr_time = Long.parseLong( ( String )tripVector.elementAt( 0 ) ) + ( Long.parseLong(( ( String )tripVector.elementAt( 1 ) ) ) * stopSeq );
doneTrips.put( utripID, true );
workingTrips = insertWorkingTrips( workingTrips, calc_createWorkingRoute( tripID, utripID, tripSign, routeName, start_stop_dec, init_dec( stopID, stopLat, stopLon, stopSeq+"", stop_arr_time+"", stopDistanceFromDestination+"" ), new Vector() ) );
}
}
}
}
}
}
}
}
return( workingTrips );
} */
public static Vector findRoutes(double lat_from,double lon_from,double lat_to,double lon_to,String srcDay)
{
Vector workingTrips = new Vector();
Hashtable allNearByStops = getAllNearByBustStops( lat_from, lon_from );
String[][] _allPassingRoutes = getAllPassingRoutesFromStops( Funcs.getHashKeys( allNearByStops ), lat_from, lon_from, srcDay );
if( _allPassingRoutes != null )
{
Hashtable tripTimes = new Hashtable();
Hashtable _uniqPassingRoutes = new Hashtable();
Hashtable singleUniqueTrips = new Hashtable();
Best.log( " _allPassingRoutes - size : " + _allPassingRoutes.length );
for( int cnt = 0; cnt < _allPassingRoutes.length; cnt++ )
{
String _uniqRouteId = _allPassingRoutes[ cnt ][ 0 ];
Best.log( " _allPassingRoutes - cnt : " + cnt + " -- " + _uniqRouteId );
if( !_uniqPassingRoutes.containsKey( _uniqRouteId ) )
{
Best.log( " _allPassingRoutes - new" );
String stopID = _allPassingRoutes[ cnt ][ 1 ];
Best.log( " _allPassingRoutes - stopID : " + stopID );
String _currTime = Funcs.getCurrentTime( true );
String _busStartTime = _allPassingRoutes[ cnt ][ 4 ];
int stopSeq = Integer.parseInt( _allPassingRoutes[ cnt ][ 2 ] );
int stop_freq = Integer.parseInt( _allPassingRoutes[ cnt ][ 6 ] );
double stop_time = ( Funcs.timeToSeconds( _busStartTime ) + ( stopSeq * stop_freq ) );
long dept_time = Funcs.timeToSeconds( _currTime );
Best.log( " stop_time: " + stop_time + " -- dept_time "+ dept_time );
if( ( ( stop_time - 1500 ) < dept_time ) && ( ( stop_time + 1500 ) > dept_time ) )
{
String tripID = _allPassingRoutes[ cnt ][ 3 ];
Vector v = new Vector( 2 );
v.add( Long.toString( dept_time ) );
v.add( Integer.toString( stop_freq ) );
tripTimes.put( tripID, v );
Vector _t = ( Vector ) allNearByStops.get( stopID );
Vector vTripInfo = init_dec( stopID, ( String ) _t.elementAt( M_STOP_NEAR_POINT_LAT_INDEX ), ( String ) _t.elementAt( M_STOP_NEAR_POINT_LON_INDEX ) , Integer.toString( stopSeq ), Double.toString( stop_time ), "0" );
singleUniqueTrips.put( _uniqRouteId, vTripInfo );
}
}
}
Best.log( " singleUniqueTrips - size : " + singleUniqueTrips.size() );
if( singleUniqueTrips.size() > 0 )
{
String trip_list = "'" + android.text.TextUtils.join( "','", Funcs.getHashKeys( tripTimes ) ) + "'";
String q = "select stops_on_trip_frequency._uniqtripID, trips_sum._tripID, trips_sum._tripHeadSign, routes._routeName, stops_on_trip_frequency._stopid , stops_on_trip_frequency._stopseq, st_distance( stop_geo._stopLoc , st_pointFromText( 'POINT( "+lat_to+" "+lon_to+")' ) )*111 as distd, ST_X( stop_geo._stopLoc ) as xlat, ST_Y( stop_geo._stopLoc ) as ylon from stops_on_trip_frequency, stop_geo, trips_sum, routes where stops_on_trip_frequency._uniqtripID=trips_sum._uniqtripID and routes._routeID=trips_sum._routeID and stops_on_trip_frequency._stopid=stop_geo._stopid and trips_sum._tripID in ("+trip_list+") order by trips_sum._tripID, distd;";
Best.log( " q2 : " + q );
String[][] allStopsFromTrips = DBHandle.execQuery( q );
if( allStopsFromTrips != null )
{
Best.log( " allStopsFromTrips : size : " + allStopsFromTrips.length );
int max_check = 0;
for( int cnt = 0; cnt < allStopsFromTrips.length; cnt++ )
{
Best.log( " allStopsFromTrips : cnt : " + cnt );
String utripID = allStopsFromTrips[ cnt ][ 0 ];
String tripID = allStopsFromTrips[ cnt ][ 1 ];
String tripSign = allStopsFromTrips[ cnt ][ 2 ];
String routeName = allStopsFromTrips[ cnt ][ 3 ];
String stopID = allStopsFromTrips[ cnt ][ 4 ];
int stopSeq = Integer.parseInt( allStopsFromTrips[ cnt ][ 5 ] );
double stopDistanceFromDestination = Double.parseDouble( allStopsFromTrips[ cnt ][ 6 ] );
String stopLat = allStopsFromTrips[ cnt ][ 7 ];
String stopLon = allStopsFromTrips[ cnt ][ 8 ];
Best.log( " allStopsFromTrips : " + utripID + " -- " + tripID );
Hashtable doneTrips = new Hashtable();
if( !doneTrips.containsKey( utripID ) )
{
if( singleUniqueTrips.containsKey( utripID ) )
{
Best.log( " -- " );
Vector vTripInfo = ( Vector ) singleUniqueTrips.get( utripID );
int _storedStopSeq = Integer.parseInt( ( String ) vTripInfo.elementAt( M_STOP_INFO_SEQ_INDEX ) );
if( _storedStopSeq < stopSeq )
{
if( stopDistanceFromDestination <= M_WALING_DISTANCE_KM )
{
Vector _tmp = ( Vector )tripTimes.get( tripID );
long stored_dept_time = Long.parseLong( (String) _tmp.elementAt( 0 ) );
int stored_freq = Integer.parseInt( (String) _tmp.elementAt( 1 ) );
double stop_arr_time = stored_dept_time + ( stored_freq * stopSeq );
//echo("calc time: ${tripID} start: ".$tripTimes[ $tripID ][ 'start_time' ]." - freq: ".$tripTimes[ $tripID ][ 'stop_freq' ]." - endseq: $stopSeq - startseq: ".$start_stop_dec[$this->_M_I_STOP_SEQ]." = ".$start_stop_dec['stoptime']." | $stop_arr_time \n");
//echo("Adding Trip: ".$singleUniqueTrips[ $utripID ][ 'stop_start' ][$this->_M_I_STOP_ID]." -> ${tripID} -> ${stopID} ( ${stopDistanceFromDestination})\n");
doneTrips.put( utripID, true );
workingTrips = insertWorkingTrips( workingTrips, calc_createWorkingRoute( tripID, utripID, tripSign, routeName, vTripInfo, init_dec( stopID, stopLat, stopLon, Integer.toString( stopSeq ), Double.toString( stop_arr_time ), Double.toString( stopDistanceFromDestination ) ), new Vector() ) );
}
}
}
}
}
}
}
}
return( workingTrips );
}
public static Hashtable getAllNearByBustStops(double latFrom,double lonFrom)
{
double swlat = ( latFrom - GEO_DELTA );
double swlon = ( lonFrom - GEO_DELTA );
double nelat = ( latFrom + GEO_DELTA );
double nelon = ( lonFrom + GEO_DELTA );
String q = "select _stopID,st_distance( stop_geo._stopLoc , st_pointFromText( 'POINT( "+latFrom+" "+lonFrom+" )' ) )*111 as distd, ST_X( stop_geo._stopLoc ) as xlat, ST_Y( stop_geo._stopLoc ) as ylon from stop_geo where ST_Contains( GeomFromText( 'Polygon(("+swlat+" "+swlon+","+nelat+" "+swlon+","+nelat+" "+nelon+","+swlat+" "+nelon+","+swlat+" "+swlon+"))' ), _stopLoc ) order by distd;";
Best.log( " getAllNearByBustStops : query" + q );
String[][] allStops = DBHandle.execQuery( q );
if( allStops != null )
{
Best.log( " getAllNearByBustStops : query_res_length " + allStops.length );
int len = allStops.length;
Hashtable _allStopNearPointHash = new Hashtable( len );
for( int i = 0; i < len; i++ )
{
String _stopID = allStops[ i ][ 0 ];
double _distanceFromPoint = Double.parseDouble( allStops[ i ][ 1 ] );
double _stopLat = Double.parseDouble( allStops[ i ][ 2 ] );
double _stopLon = Double.parseDouble( allStops[ i ][ 3 ] );
Best.log( " getAllNearByBustStops : stop at "+ i +" :: " + _stopID + " -- " + " -- " + _distanceFromPoint + " -- " + _stopLat + " -- " + _stopLon );
Vector _stopNearPointInfo = new Vector( 3 );
_stopNearPointInfo.insertElementAt( Double.toString( _distanceFromPoint ), M_STOP_NEAR_POINT_DISTANCE_INDEX );
_stopNearPointInfo.insertElementAt( Double.toString( _stopLat ), M_STOP_NEAR_POINT_LAT_INDEX );
_stopNearPointInfo.insertElementAt( Double.toString( _stopLon ), M_STOP_NEAR_POINT_LON_INDEX );
_allStopNearPointHash.put( _stopID, _stopNearPointInfo );
}
return( _allStopNearPointHash );
}
return( null );
}
public static String[][] getAllPassingRoutesFromStops(String[] stops,double lat,double lon,String srcDay)
{
if( stops.length > 0 )
{
String stopsList = "'" + android.text.TextUtils.join( "','", stops ) + "'";
String q = "select stops_on_trip_frequency._uniqtripID,stops_on_trip_frequency._stopid, stops_on_trip_frequency._stopseq, trips_sum._tripid, trips_sum._start, trips_sum._start_next_day, trips_sum._freq, st_distance( stop_geo._stopLoc , st_pointFromText( 'POINT( "+lat+" "+lon+")' ) )*111 as distd from stop_geo, stops_on_trip_frequency, schedule_rules, trips_sum where trips_sum._uniqtripID = stops_on_trip_frequency._uniqtripID and trips_sum._serviceid = schedule_rules._serviceid and stops_on_trip_frequency._stopid=stop_geo._stopid and schedule_rules._serviceday='"+srcDay+"' and schedule_rules._startperioddate<=date( 'now' ) and date( 'now' )<=schedule_rules._endperioddate and stops_on_trip_frequency._stopid in ("+stopsList+") order by distd;";
Best.log( " getAllPassingRoutesFromStops : query : " + q );
return( DBHandle.execQuery( q ) );
}
return( null );
}
public static Vector init_dec(String stopID,String stopLat,String stopLon,String stopSeq,String stop_arr_time,String stopDistanceFromDestination )
{
Vector v = new Vector();
v.insertElementAt( stopID, M_STOP_INFO_ID_INDEX );
v.insertElementAt( stopLat, M_STOP_INFO_LAT_INDEX );
v.insertElementAt( stopLon, M_STOP_INFO_LON_INDEX );
v.insertElementAt( stopSeq, M_STOP_INFO_SEQ_INDEX );
v.insertElementAt( stop_arr_time, M_STOP_INFO_ARR_TIME_INDEX );
v.insertElementAt( stopDistanceFromDestination, M_STOP_INFO_ARR_DISTANCE_INDEX );
return( v );
}
public static Vector insertWorkingTrips(Vector wtrips,Vector wt)
{
int wlen = wtrips.size();
Vector ret = new Vector();
if( wlen > 0 )
{
boolean b_done_insert = false;
Vector infoVector = ( Vector )wt.elementAt( 2 );
double suppliedDistance = Double.parseDouble( ( String )infoVector.elementAt( 2 ) );
for( int i=0; i < wlen; i++ )
{
Vector singleTrip = ( Vector )wtrips.elementAt( i );
Vector innerVector = ( Vector )singleTrip.elementAt( 2 );
if( suppliedDistance < Double.parseDouble( ( String )innerVector.elementAt( 2 ) ) )
{ ret.add( wt ); b_done_insert = true; }
ret.add( singleTrip );
}
if(!b_done_insert) { ret.add( wt ); }
}
else
ret.add( wt );
return( ret );
}
public static Vector calc_createWorkingRoute(String tripID,String uniqueTripID,String tripSign,String routeName,Vector start_stop_dec,Vector end_stop_dec,Vector next_trip_hops)
{
double s = Double.parseDouble( (String)start_stop_dec.elementAt( M_STOP_INFO_ARR_TIME_INDEX ) );
double e = Double.parseDouble( (String)end_stop_dec.elementAt( M_STOP_INFO_ARR_TIME_INDEX ) );
int strartBusStopNo = Integer.parseInt( (String)start_stop_dec.elementAt( M_STOP_INFO_SEQ_INDEX ) );
int lastBusStopNo = Integer.parseInt( (String)end_stop_dec.elementAt( M_STOP_INFO_SEQ_INDEX ) );
double trip_time = e - s;
double trip_dist = getTripDistance( uniqueTripID, strartBusStopNo+"", lastBusStopNo+"" );
Vector v = new Vector();
v.add( tripID );
v.add( uniqueTripID );
v.add( init_trip_dec( trip_time+"", "0", trip_dist+"", tripSign, routeName ) );
v.add( start_stop_dec );
v.add( end_stop_dec );
v.add( next_trip_hops );
return( v );
}
public static double getTripDistance(String tripID,String start_seq,String end_seq)
{
try{
String q = "select asText(stop_geo._stoploc) from stops_on_trip_frequency inner join stop_geo on (stop_geo._stopid=stops_on_trip_frequency._stopid) where _uniqtripID='"+tripID+"' and _stopseq>="+start_seq+" and _stopseq<="+end_seq;
String[][] resultSet = DBHandle.execQuery( q );
if( resultSet != null )
{
String lastPoint = "";
String distanceSelectClause = "";
for( int cnt = 0; cnt < resultSet.length; cnt++ )
{
if( cnt > 0 )
{
distanceSelectClause = ( ( distanceSelectClause.length() > 0 )?( "+" ):( "" ) )+"distance( GeomFromText( '"+lastPoint+"' ), GeomFromText( '"+resultSet[ cnt ][ 0 ]+"' ) )";
}
distanceSelectClause += "*111";
lastPoint = resultSet[ cnt ][ 0 ];
}
q = "select "+distanceSelectClause;
resultSet = DBHandle.execQuery( q );
Best.log( " getTripDistance q: " + q );
if( resultSet != null )
{
Best.log( " ANSWER : " + resultSet[ 0 ][ 0 ] );
return( Double.parseDouble( resultSet[ 0 ][ 0 ] ) );
}
}
}catch(Exception e){}
return( 0 );
}
public static Vector init_trip_dec(String tripTime,String tripFare,String tripDist,String tripSign,String routeName)
{
Vector v = new Vector();
v.add( tripTime );v.add( tripFare );v.add( tripDist );v.add( tripSign );v.add( routeName );
return( v );
}
//------------DIRECT ROUTING ---------
public static String[][] getDirectRoutes(String fromStopID, String toStopID)
{
String _currDay = Funcs.getCurrentDay();
String acceptable_trips = "";
String acceptable_trips_by_id = "";
String working_trips = "";
String q = "select stops_on_trip._tripID, stops_on_trip._stopSeq, trips_freq._start, trips_freq._end, trips_freq._end_next_day, trips_freq._headways, trips_freq._freq, routes._routeLongName , routes._routeName from stops_on_trip, trips_freq, trips, routes, schedule_rules where stops_on_trip._stopID='"+fromStopID +"' and stops_on_trip._tripID = trips_freq._tripID and stops_on_trip._tripID = trips._tripID and schedule_rules._serviceID = trips._serviceID and routes._routeID = trips._routeID and schedule_rules._serviceDay='"+ _currDay +"' order by stops_on_trip._tripID asc, _start asc;" ;
String[][] resultSet = DBHandle.execQuery( q );
Best.log( q );
if(resultSet != null )
{
Hashtable _passingFromStopsTrips = new Hashtable();
String _allTripId = "";
int _passedTrips = 0;
for( int cnt = 0; cnt < resultSet.length; cnt++ )
{
Best.log("====resultSet Count==="+ cnt);
String _tripId = resultSet[ cnt ][ 0 ];
int _seq = Integer.parseInt( resultSet[ cnt ][ 1 ] );
String _startTime = resultSet[ cnt ][ 2 ];
String _endTime = resultSet[ cnt ][ 3 ];
int _freq = Integer.parseInt( resultSet[ cnt ][ 6 ] );
String _routeLongName = resultSet[ cnt ][ 7 ];
String _routeName = resultSet[ cnt ][ 8 ];
String _currTime = Funcs.getCurrentTime( true );
Best.log("===_tripId=="+_tripId+"==_seq=="+_seq+"==_startTime=="+_startTime+"==_freq=="+_freq+"==_routeLongName=="+_routeLongName+"==_routeName=="+_routeName);
long _startTimeInSecs = Funcs.timeToSeconds( _startTime );
Best.log("===_startTime=="+_startTime);
long _endTimeInSecs = Funcs.timeToSeconds( _endTime );
Best.log("===_endTime=="+_endTime);
long _currTimeInSecs = Funcs.timeToSeconds( _currTime );
Best.log("===_currTime=="+_currTime);
Best.log("===_currTimeInSecs=="+_currTimeInSecs);
int _trip_travel_time = (_freq * _seq);
long _trip_start_esti_beg = (_currTimeInSecs - _trip_travel_time) - 900;
long _trip_start_esti_end = (_currTimeInSecs - _trip_travel_time) + 900;
Best.log("===_startTimeInSecs=="+_startTimeInSecs);
Best.log("_trip_start_esti_beg="+_trip_start_esti_beg);
Best.log("===_endTimeInSecs=="+_endTimeInSecs);
Best.log("_trip_start_esti_end="+_trip_start_esti_end);
if( ( (_startTimeInSecs <= _trip_start_esti_beg) && (_endTimeInSecs <= _trip_start_esti_beg) ) || ( (_startTimeInSecs <= _trip_start_esti_end) && (_endTimeInSecs <= _trip_start_esti_end) ) )
{
double _stopTime = ( _startTimeInSecs + ( _seq * _freq ) );
Best.log("===_stopTime=="+_stopTime);
//if( ( ( _stopTime - 900 ) < 57600 ) && ( ( _stopTime + 900 ) > 57600 ) )
//{
Vector _trip_info = new Vector( 6 );
_trip_info.add( _tripId );
_trip_info.add( Integer.toString( _seq ) );
_trip_info.add( Integer.toString( _freq ) );
_trip_info.add( _startTime );
_trip_info.add( _routeLongName );
_trip_info.add( _routeName );
Best.log( "STORRING : " + _tripId + " -> " + _seq + " -- " + _freq + " -- " + _startTime + " -- " + _tripId );
if(_passingFromStopsTrips.containsKey( _tripId ) )
{
<<<<<<< .mine
Vector _t = new Vector( 6 );
_t.add( Integer.toString( _seq ) );
_t.add( Integer.toString( _freq ) );
_t.add( _startTime );
_t.add( _headSign );
_t.add( _tripId );
_t.add( _routeName );
=======
Vector _tripVec = (Vector)_passingFromStopsTrips.get(_tripId);
_tripVec.add(_trip_info);
}
else
{
Vector _tripVec = new Vector();
_tripVec.add(_trip_info);
_passingFromStopsTrips.put( _tripId, _tripVec );
}
if(((Vector)(_passingFromStopsTrips.get(_tripId))).size() == 1)
_allTripId += ( ( _allTripId.length() > 0 )?( "," ):( "" ) ) + "'"+_tripId+"'";
>>>>>>> .r34
}
}
Best.log("=======_passingFromStopsTrips Size===="+_passingFromStopsTrips.size());
Best.log("=======_allTripId===="+_allTripId);
if( _passingFromStopsTrips.size() > 0 && _allTripId.length() > 0 )
{
String q2 = "select _tripID, _stopSeq from stops_on_trip where _tripID in ("+_allTripId+") and _stopID = '"+toStopID+"';";
Best.log( "2nd query======="+q2 );
resultSet = DBHandle.execQuery( q2 );
if( resultSet != null )
{
String _TripIds = "";
Hashtable _toStopSeqStore = new Hashtable();
for( int c = 0; c < resultSet.length; c++ )
{
String tripId = resultSet[ c ][ 0 ];
int _toStopSeq = Integer.parseInt( resultSet[ c ][ 1 ] );
Best.log( "Q2 : "+tripId+" :: "+_toStopSeq );
if( _passingFromStopsTrips.containsKey( tripId ) )
{
Vector _tripPassingFrom = ( Vector )_passingFromStopsTrips.get( tripId );
int _fromStopSeq = Integer.parseInt((String)( ( Vector )_tripPassingFrom.elementAt( 0 )).elementAt(1) );
Best.log( "SQS : "+ _fromStopSeq + " :: " + _toStopSeq );
if( _fromStopSeq < _toStopSeq )
{
_passedTrips++;
_TripIds += ( ( _TripIds.length() > 0 )?( "," ):( "" ) )+ tripId;
_toStopSeqStore.put( tripId, Integer.toString( _toStopSeq ) );
}
}
else
Best.log( "NOT STORED : "+tripId );
}
Best.log( "_TripIds : "+ _TripIds );
if( _TripIds.length() > 0 )
{
String[] _trips = _TripIds.split( "," );
String _tripIds = "";
int k = 0;
for( k = 0 ;k < _trips.length -1; k++)
{
_tripIds += "'"+_trips[k]+"'"+",";
}
_tripIds += "'"+_trips[k]+"'";
String[][] _ret = null;
if( _passedTrips > 0 )
_ret = new String[ _passedTrips ][ 6 ];
String query = "select ST_X(_stopLoc) , ST_Y(_stopLoc) , _tripID , _stopSeq ,stops_on_trip._stopID from stops_on_trip ,stop_geo where stops_on_trip._stopID = stop_geo._stopID and stops_on_trip._tripID in ("+_tripIds+") order by _tripID , _stopSeq ;";
Best.log("query="+query);
String[][] tripInfoResult = DBHandle.execQuery( query );
ArrayList<String> distanceList = new ArrayList<String>();
for(int i =0 ; i < tripInfoResult.length; i++)
{
ArrayList<String> stopGeoX = new ArrayList<String>();
ArrayList<String> stopGeoY = new ArrayList<String>();
if(tripInfoResult[i][4].equals(fromStopID))
{
for(int j = 0; j< tripInfoResult.length; j++,i++)
{
stopGeoX.add( tripInfoResult[i][0]);
stopGeoY.add( tripInfoResult[i][1]);
if(tripInfoResult[i][4].equals(toStopID))
break ;
}
int distanceBetweenStops = 0;
for(int index = 0; index <stopGeoX.size() - 1; index++ )
{
GeoPoint gp1 = new GeoPoint(Double.parseDouble(stopGeoX.get(index)) , Double.parseDouble(stopGeoY.get(index)) );
GeoPoint gp2 = new GeoPoint(Double.parseDouble(stopGeoX.get(index + 1)) , Double.parseDouble(stopGeoY.get(index + 1)) );
distanceBetweenStops += gp1.distanceTo( gp2 );
Best.log("distanceBetweenStops ="+ distanceBetweenStops);
}
distanceList.add(Integer.toString(distanceBetweenStops));
}
}
if( _ret != null )
{
for( int c = 0,_passeIndex=0; c < _trips.length; c++ )
{
String _trip_id = _trips[ c ];
Best.log( "_trip_id: "+_trip_id);
if( _passingFromStopsTrips.containsKey( _trip_id ) )
{
Vector _trip_vec = ( Vector ) _passingFromStopsTrips.get( _trip_id );
for(int i =0; i < _trip_vec.size() ; i++)
{
if( _passeIndex < _passedTrips )
{
Vector _t = (Vector)(_trip_vec.elementAt(i));
_ret[ _passeIndex ][ 0 ] = ( String )_t.elementAt( 0 ); //trip ID
_ret[ _passeIndex ][ 1 ] = ( String )_t.elementAt( 5 ); //routeName
_ret[ _passeIndex ][ 2 ] = ( String )_t.elementAt( 4 ); //head sign
_ret[ _passeIndex ][ 3 ] = Integer.toString( Integer.parseInt( ( String ) _toStopSeqStore.get( _trip_id ) ) - Integer.parseInt( ( String ) _t.elementAt( 1 ) ) ); // number of stops
//_ret[ c ][ 4 ] = ( String )_t.elementAt( 2 ); //departure time
_ret[ _passeIndex ][ 4 ] = distanceList.get(c);
_ret[ _passeIndex ][ 5 ] = ( String )_t.elementAt( 2 ); //freq
//String[][] tripInfoResultSet = getTripInfo( ( String )_t.elementAt( 0 ));
Best.log( "_x RET INFO : " + android.text.TextUtils.join( "','", _ret[ _passeIndex ] ) );
_passeIndex++;
}
}
}
else
Best.log( "_x else : " );
}
}
return( _ret );
}
}
}
}
else
Best.log("getDirectRoutes:=====Resultset null=====");
return( null );
}
//------------------------------------
}

View File

@ -0,0 +1,288 @@
////////////////////////////////////////////////
//
// A ChaloBEST (http://chalobest.in/) initiative
// Author: Nikita (Macgregor Techknowlogy)
// License: GPLv3
//
//
package com.best.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.Context;
import java.util.Vector;
import android.os.Bundle;
import android.os.Message;
import android.os.Handler;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import android.location.LocationManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationProvider;
import java.lang.CharSequence;
import android.content.DialogInterface;
import android.widget.LinearLayout;
import com.best.data.DBHandle;
import com.best.data.GTStore;
import com.best.util.TransitionEffect;
public class Best extends Activity
{
public static Activity me;
public static boolean result=false;
public static String[] stopNames=null;
public static ProgressDialog dialog;
public static boolean m_position_updation_on = false;
public static LocationManager m_locationManager = null;
public static Location _location;
public static int _activityRequestCode = 1;
public static String m_latitude = "";
public static String m_longitude = "";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.DONUT)
TransitionEffect.callOverridePendingTransition(this);
me = this;
DBHandle.init( me );
Intent intent = new Intent( ( Context )me,SplashScreen1.class );
me.startActivityForResult( intent,_activityRequestCode );
LoadThread loadThread = new LoadThread( loadHandler );
loadThread.start();
}
@Override
protected void onResume() {
super.onResume();
if( m_locationManager == null )
m_locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
getUpdatedPosition();
}
public Handler loadHandler = new Handler() {
public void handleMessage(Message msg) {
Bundle dataBundle = msg.getData();
boolean allOK = dataBundle.getBoolean( "allOK" );
if( allOK )
{
Intent intent = new Intent();
intent.setClass( me, Find.class);
startActivityForResult( intent, _activityRequestCode );
}
else
showErrorAndExit( "Sorry unable to start application." );
}
};
private class LoadThread extends Thread
{
Handler _handler;
LoadThread(Handler handler )
{
_handler = handler;
}
public void run()
{
//code to get all routes
Bundle dataBundle = new Bundle();
dataBundle.putBoolean( "allOK", DBHandle.dbFileReady() );
Message msg = _handler.obtainMessage();
msg.setData( dataBundle );
_handler.sendMessage( msg );
}
}
public static void finishAll()
{
try{ me.finishActivity(_activityRequestCode); }catch(Exception e){}
me.finish();
}
public static void exit(Context context)
{
AlertDialog.Builder builder = new AlertDialog.Builder( context );
builder.setMessage("Are you sure you want to exit?")
.setCancelable( false )
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finishAll();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
public static void showError(Context context, CharSequence msg)
{
showMessage( context, msg, "Error" );
}
public static void showError(Context context, int msg)
{
showMessage( context, msg, "Error" );
}
public static void showMessage(Context context, CharSequence msg,String title)
{
new AlertDialog.Builder( context )
.setMessage( msg )
.setTitle( title )
.setCancelable( true )
.setNeutralButton( "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){ }
})
.show();
}
public static void showMessage(Context context, int msg,String title)
{
new AlertDialog.Builder( context )
.setMessage( msg )
.setTitle( title )
.setCancelable( true )
.setNeutralButton( "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){ }
})
.show();
}
public static void showProcessing(Context context,String title, String msg)
{
dialog = ProgressDialog.show( context, title, msg, true );
}
public static void dissmissProcessing()
{
dialog.dismiss();
}
public static void log(String msg)
{
System.out.println( "USER DEBUG : " + msg );
}
/////////GPS
public static void getUpdatedPosition()
{
if( !m_position_updation_on )
{
m_latitude = "";
m_longitude = "";
m_position_updation_on = true;
//m_locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 5000, 0, m_networkLocationListener );
m_locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5000, 0, m_gpsLocationListener );
}
}
public static void cancelUpdatePosition()
{
m_position_updation_on = false;
cancelNetWorkUpdatePosition();
cancelGPSUpdatePosition();
}
public static void cancelNetWorkUpdatePosition()
{
m_locationManager.removeUpdates( m_networkLocationListener );
}
public static void cancelGPSUpdatePosition()
{
m_locationManager.removeUpdates( m_gpsLocationListener );
}
private static LocationListener m_gpsLocationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras){}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) { cancelGPSUpdatePosition(); }
@Override
public void onLocationChanged(Location location) {
try{ m_latitude = String.format("%9.6f", location.getLatitude()); }catch(Exception e){ m_latitude=""; }
try{ m_longitude = String.format("%9.6f", location.getLongitude()); }catch(Exception e){ m_longitude=""; }
cancelUpdatePosition();
}
};
private static LocationListener m_networkLocationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) { cancelNetWorkUpdatePosition(); }
@Override
public void onLocationChanged(Location location) {
try{ m_latitude = String.format("%9.6f", location.getLatitude()); }catch(Exception e){ m_latitude=""; }
try{ m_longitude = String.format("%9.6f", location.getLongitude()); }catch(Exception e){ m_longitude=""; }
cancelUpdatePosition();
}
};
public static boolean checkGPS(Context context)
{
if( !m_locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) )
{
showMessage( context, "GPS Service not working.Please check option for GPS in \"Location & Security settings\" is checked.", "Service" );
return( false );
}
return( true );
}
public static void showErrorAndExit(String msg)
{
new AlertDialog.Builder( me )
.setMessage( msg )
.setTitle( "Error" )
.setCancelable( true )
.setNeutralButton( "Exit" ,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){ Best.finishAll(); }
})
.show();
}
//////
}

View File

@ -0,0 +1,38 @@
////////////////////////////////////////////////
//
// A ChaloBEST (http://chalobest.in/) initiative
// Author: Vivek (Macgregor Techknowlogy)
// License: GPLv3
//
//
package com.best.ui;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.ListView;
public class ExpandedListView extends ListView {
private android.view.ViewGroup.LayoutParams params;
private int old_count = 0;
public ExpandedListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
if (getCount() != old_count) {
old_count = getCount();
params = getLayoutParams();
if( old_count > 0 )
params.height = ( getCount() * getChildAt(0).getHeight() ) + 20;
else
params.height = 0;
setLayoutParams(params);
}
super.onDraw(canvas);
}
}

View File

@ -0,0 +1,671 @@
////////////////////////////////////////////////
//
// A ChaloBEST (http://chalobest.in/) initiative
// Author: Nikita (Macgregor Techknowlogy)
// License: GPLv3
//
//
package com.best.ui;
import java.util.List;
import java.util.ArrayList;
import java.util.Vector;
import android.util.AttributeSet;
import android.app.Activity;
import android.app.ListActivity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageButton;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListView;
import android.widget.Filterable;
import android.widget.Filter;
import android.widget.AbsListView;
import android.content.Intent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.view.MotionEvent;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.KeyEvent;
import android.view.View.OnKeyListener;
import java.io.IOException;
import android.os.Message;
import android.os.Handler;
import android.os.Environment;
import java.lang.Double;
import android.graphics.Canvas;
import com.best.data.GTStore;
import com.best.util.Funcs;
import com.best.util.TransitionEffect;
import android.widget.RelativeLayout;
public class Find extends ListActivity {
public static ListActivity me;
public static Context m_context;
public static AttributeSet attr;
public static LayoutInflater mInflater;
public static int M_FROM_LIST_CAPTION = 1;
public static int M_TO_LIST_CAPTION = 2;
public static int M_FROM_NEAR_BY_LIST_CAPTION = 3;
public static int M_TO_NEAR_BY_LIST_CAPTION = 4;
public static int WIDGET_VISIBLE = 0;
public static int WIDGET_INVISIBLE = 4;
public static String[] stopsId ;
public static String[] stopName;
public static String[] distance;
public static String[] stopLatitude;
public static String[] stopLongitude;
public static String[][] resultTemp;
public static int selPosition = 0;
public static int flagSourceSel = -1;
public static int flagDestSel = -1;
public static int listDisplayed = -1;
public static boolean flagPanelVisible = true;
public static String _sourceStopId = null;
public static String _destStopId = null;
public static Double latDouble=0.0;
public static Double longDouble=0.0;
public static ProgressDialog dialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.DONUT)
TransitionEffect.callOverridePendingTransition(this);
//overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
me = this;
m_context = this;
me.setContentView( com.best.ui.R.layout.find );
flagSourceSel=-1;
flagDestSel=-1;
init();
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
outState.putInt("src",flagSourceSel);
outState.putInt("dest",flagDestSel);
outState.putInt("listDisplay",listDisplayed);
}
@Override
protected void onRestoreInstanceState(final Bundle outState) {
if(outState.getInt("listDisplay")!=-1)
{
EfficientAdapter adapter = new EfficientAdapter( m_context,resultTemp);
me.setListAdapter( adapter );
( (TextView) me.findViewById(com.best.ui.R.id.txthead) ).setVisibility( WIDGET_VISIBLE );
//((ImageButton) me.findViewById(com.best.ui.R.id.expandable)).setVisibility( WIDGET_VISIBLE );
}
flagSourceSel=outState.getInt("src");
flagDestSel=outState.getInt("dest");
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// do something or nothing when configuration change.
super.onConfigurationChanged(newConfig);
init();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(com.best.ui.R.menu.menustart, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case com.best.ui.R.id.mnuexitmain:
Best.exit( me );
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onPause() {
super.onPause();
// cancelUpdatePosition();
}
@Override
public void onBackPressed() {
Best.exit( me );
//return;
}
public void handleFromSearch(String fromTxt)
{
if( fromTxt.length() > 0 )
{
if( fromTxt.length() > 2 )
findBusStops( false, fromTxt, M_FROM_LIST_CAPTION );
else
Best.showError( m_context, com.best.ui.R.string.errMsgMoreChar );
}
else
Best.showError( m_context, com.best.ui.R.string.errMsgEnterSrcLoc );
}
public void handleToSearch(String toTxt)
{
if(toTxt.length()>0)
{
if(toTxt.length()>2)
findBusStops( false, toTxt, M_TO_LIST_CAPTION );
else
Best.showError( m_context, com.best.ui.R.string.errMsgMoreChar );
}
else
Best.showError( m_context, com.best.ui.R.string.errMsgEnterDestLoc );
}
public void handleEnter(KeyEvent e,EditText txt,boolean frmSearch)
{
if( e.getKeyCode() == KeyEvent.KEYCODE_ENTER && e.getAction() == KeyEvent.ACTION_DOWN) //enter
{
if( frmSearch )
handleFromSearch( txt.getText().toString().trim() );
else
handleToSearch( txt.getText().toString().trim() );
}
}
public void init()
{
final TextView txthead = (TextView) me.findViewById(com.best.ui.R.id.txthead);
//final LinearLayout expLayout = (LinearLayout) me.findViewById(com.best.ui.R.id.explinearlayout);
// final ImageButton btnexpand = (ImageButton) me.findViewById(com.best.ui.R.id.expandable);
// btnexpand.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v) {
// if(flagPanelVisible == true)
// {
// expLayout.setVisibility(LinearLayout.GONE);
// flagPanelVisible = false;
// btnexpand.setImageResource(R.drawable.ic_plus_trans);
// }
// else
// {
// expLayout.setVisibility(LinearLayout.VISIBLE);
// flagPanelVisible = true;
// btnexpand.setImageResource(R.drawable.ic_minus_trans);
// }
// }
// });
final EditText txtFrm = (EditText) me.findViewById(com.best.ui.R.id.fromtxt);
txtFrm.setOnKeyListener( new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
handleEnter( event, txtFrm, true );
return false;
}
});
final ImageButton btnsearchfrm = (ImageButton) me.findViewById(com.best.ui.R.id.findfrom);
btnsearchfrm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
handleFromSearch( txtFrm.getText().toString().trim() );
}
});
final EditText txtTo = (EditText) me.findViewById(com.best.ui.R.id.totxt);
txtTo.setOnKeyListener( new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
handleEnter( event, txtTo, false );
return false;
}
});
final ImageButton btnsearchto = (ImageButton) me.findViewById(com.best.ui.R.id.findto);
btnsearchto.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
handleToSearch( txtTo.getText().toString().trim() );
}
});
final Button btnnearfrom = (Button) me.findViewById(com.best.ui.R.id.nearFrom);
btnnearfrom.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
findNearByStops( true );
}
});
final Button btnnearto = (Button) me.findViewById(com.best.ui.R.id.nearTo);
btnnearto.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
findNearByStops( false );
}
});
final Button btnfindbus = ( Button ) me.findViewById( com.best.ui.R.id.findbus );
btnfindbus.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
String sourceText = txtFrm.getText().toString();
String destText = txtTo.getText().toString();
if( sourceText.length() > 0 )
{
if( flagSourceSel != -1 )
{
if( destText.length() > 0 )
{
if( flagDestSel != -1 )
{
Best.showProcessing( m_context, "Searching","Please wait while searching.." );
RouteSearchThread searchRoute = new RouteSearchThread( searchRoutesHandler );
searchRoute.start();
}
else
Best.showError( m_context, com.best.ui.R.string.errMsgEnterValidDest );
}
else
Best.showError( m_context, com.best.ui.R.string.errMsgEnterDestLoc );
}
else
Best.showError( m_context, com.best.ui.R.string.errMsgEnterValidSrc );
}
else
Best.showError( m_context, com.best.ui.R.string.errMsgEnterSrcLoc );
}
});
}
public Handler searchRoutesHandler = new Handler() {
public void handleMessage(Message msg) {
Bundle dataBundle = msg.getData();
Best.dissmissProcessing();
String[][] routesResult = ( String[][] )dataBundle.getSerializable( "rts" );
EfficientAdapter adapter = new EfficientAdapter( m_context, routesResult );
me.setListAdapter( adapter );
ListView listview = ( ListView )me.findViewById( android.R.id.list );
listview.requestLayout();
if( routesResult != null && routesResult.length >0 )
{
( (TextView) me.findViewById(com.best.ui.R.id.txthead) ).setVisibility( WIDGET_VISIBLE );
( ( ListView )me.findViewById( android.R.id.list ) ).setVisibility( WIDGET_VISIBLE );
//((ImageButton) me.findViewById(com.best.ui.R.id.expandable)).setVisibility( WIDGET_VISIBLE );
listDisplayed = 1;
}
else
{ ( (TextView) me.findViewById(com.best.ui.R.id.txthead) ).setVisibility( WIDGET_INVISIBLE );
( ( ListView )me.findViewById( android.R.id.list ) ).setVisibility( WIDGET_INVISIBLE );
//((ImageButton) me.findViewById(com.best.ui.R.id.expandable)).setVisibility( WIDGET_INVISIBLE );
Best.showMessage( m_context, "There are no routes to show.", "Processing" );
}
}
};
private class RouteSearchThread extends Thread
{
Handler _handler;
RouteSearchThread(Handler handler )
{
_handler = handler;
}
public void run()
{
//code to get all routes
Bundle dataBundle = new Bundle();
String currTime = Funcs.getCurrentTime( true );
// dataBundle.putSerializable( "rts", GTStore.getRoutes( _sourceStopId, _destStopId, Funcs.getCurrentDay(), currTime, Funcs.addTime( currTime, "00:25:00" ) ) );
//dataBundle.putSerializable( "rts", GTStore.findRoutes( 40.44938, -3.6912, 40.41876, -3.69263, Funcs.getCurrentDay() ) );
dataBundle.putSerializable( "rts", GTStore.getDirectRoutes( _sourceStopId, _destStopId ) );
//dataBundle.putSerializable( "rts", GTStore.getDirectRoutes( "714", "736" ) );
//dataBundle.putSerializable( "rts", GTStore.getDirectRoutes( "46", "73" ) );
Message msg = _handler.obtainMessage();
msg.setData( dataBundle );
_handler.sendMessage( msg );
}
}
public void findNearByStops(boolean fromButton)
{
if( Best.checkGPS( m_context ) )
{
if( fromButton )
findBusStops( true, "", M_FROM_NEAR_BY_LIST_CAPTION );
else
findBusStops( true, "", M_TO_NEAR_BY_LIST_CAPTION );
}
}
public static Handler searchStopsHandler = new Handler() {
public void handleMessage(Message msg) {
Bundle dataBundle = msg.getData();
String[][] resultSet = (String[][]) dataBundle.getSerializable( "resultSet" );
boolean byPosition = dataBundle.getBoolean( "byPosition" );
boolean allOK = dataBundle.getBoolean( "allOK" );
int editBox = dataBundle.getInt( "editBox" );
Best.dissmissProcessing();
if( allOK )
{
if( resultSet!=null && resultSet.length > 0 )
displayList( resultSet, editBox );
else
{
if( byPosition )
Best.showMessage( m_context, com.best.ui.R.string.errMsgNoNearbyStop, "Searching" );
else
Best.showMessage( m_context, com.best.ui.R.string.errMsgNoStopsMatch, "Searching" );
}
}
else
Best.showMessage( m_context, "Sorry something went wrong.", "Processing" );
}
};
private class StopSearchThread extends Thread
{
Handler _handler;
String _txtSearch = "";
boolean _byPosition = false;
int _editBox = -1;
StopSearchThread(Handler handler, String txtSearch, boolean byPosition, int editBox )
{
_handler = handler;
_txtSearch = txtSearch;
_byPosition = byPosition;
_editBox = editBox;
}
public void run()
{
boolean allOK = true;
String[][] resultSet = null;
if( Best.m_latitude.length() > 0 && Best.m_longitude.length() > 0 )
{
latDouble = Double.valueOf( Best.m_latitude );//Double.valueOf( "40.45939" );
longDouble = Double.valueOf( Best.m_longitude );//Double.valueOf( "-3.78429" );
}
if( _byPosition )
{
//near by stops
try{
resultSet = GTStore.getNearByStops( latDouble, longDouble );
}catch(Exception e){System.out.println("Excp2: " + e.toString() );allOK = false;}
}
else
{
//search by inputtext
try{
resultSet = GTStore.getAllStopsByText( _txtSearch, latDouble, longDouble );
}catch(Exception e){allOK = false; e.printStackTrace();}
}
Bundle dataBundle = new Bundle();
dataBundle.putSerializable( "resultSet", resultSet );
dataBundle.putBoolean( "byPosition", _byPosition );
dataBundle.putBoolean( "allOK", allOK );
dataBundle.putInt( "editBox", _editBox );
Message msg = _handler.obtainMessage();
msg.setData( dataBundle );
_handler.sendMessage( msg );
}
}
public void findBusStops(boolean byPosition, String enteredText, int editBoxNo)
{
Best.showProcessing( m_context, "Searching","Please wait while searching.." );
StopSearchThread thread = new StopSearchThread( searchStopsHandler, enteredText, byPosition, editBoxNo );
thread.start();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try{
Bundle bundle = data.getExtras();
int editBoxNo=bundle.getInt( "EditText" );
selPosition=bundle.getInt( "position" );
if( editBoxNo == 1 || editBoxNo == 3 )
{
String FrmLoc=bundle.getString( "frmLoc" );
EditText txtfrm1 = ( EditText ) findViewById(com.best.ui.R.id.fromtxt);
txtfrm1.setText(FrmLoc);
flagSourceSel = selPosition;
_sourceStopId = bundle.getString( "stopId" );
}
else if(editBoxNo==2||editBoxNo==4)
{
String ToLoc=bundle.getString("frmLoc");
EditText txtTo1 = (EditText) findViewById(com.best.ui.R.id.totxt);
txtTo1.setText(ToLoc);
flagDestSel = selPosition;
_destStopId = bundle.getString( "stopId" );
}
}
catch(Exception e)
{
System.out.println("Exception-"+e.toString());
}
}
public static void displayList(String[][] resultSet,int editBoxNo)
{
try{
String[] stopsId, stopName, distance;
stopsId = new String[resultSet.length ];
stopName = new String[resultSet.length ];
distance = new String[resultSet.length ];
for(int index=0; index<resultSet.length; index++)
{
if( resultSet[ index ] != null && resultSet[ index ].length > 0 )
{
String[] stopDesc = (String[])(resultSet[ index ]);
stopsId[ index ] = stopDesc[0];
stopName[ index ] = stopDesc[1];
distance[ index ] = stopDesc[2];
Best.log( "ID : "+stopsId[ index ].toString()+" -- "+stopName[ index ].toString()+" --- "+distance[ index ].toString() );
}
}
Intent intent = new Intent(m_context, ListLocation.class);
Bundle bundle = new Bundle();
bundle.putStringArray( "StopID", stopsId );
bundle.putStringArray( "Stops", stopName );
bundle.putStringArray( "Distance", distance );
bundle.putInt( "EditText", editBoxNo );
intent.putExtras( bundle );
me.startActivityForResult( intent, 5 );
}
catch(Exception e){}
}
public class EfficientAdapter extends BaseAdapter implements Filterable {
public String[][] result;
public EfficientAdapter(Context context, String[][] resultSet)
{
if(resultSet!= null)
{
mInflater = LayoutInflater.from( context );
result = new String[resultSet.length][];
result=resultSet;
}
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(result!= null)
{
if (convertView == null)
{
convertView = mInflater.inflate(com.best.ui.R.layout.list_button, null);
holder = new ViewHolder();
holder.routename= (TextView) convertView.findViewById(com.best.ui.R.id.routename);
holder.head = (TextView) convertView.findViewById(com.best.ui.R.id.bushead);
holder.total_dist = (TextView) convertView.findViewById(com.best.ui.R.id.totaldist);
holder.no_of_stops = (TextView) convertView.findViewById(com.best.ui.R.id.stopsno);
holder.blue_bus = (ImageView) convertView.findViewById(com.best.ui.R.id.busBlue);
convertView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putString( "tripID" , result[position][0] );
bundle.putString( "sourceID" ,_sourceStopId);
bundle.putString( "destID" ,_destStopId);
bundle.putBoolean( "showFullRoute" ,false);
Intent intent = new Intent(m_context, Routes.class);
intent.putExtras( bundle );
me.startActivityForResult(intent,6);
}
});
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
String _routeName = result[position][1];
String _headerName = result[position][2];
String _betweenStopsNum = result[position][3];
int _distance = 0;
try{ _distance = Integer.parseInt( result[position][4] ); }catch(Exception e){}
holder.routename.setText( _routeName );
holder.head.setText( _headerName );
if( _distance > 1000)
{
if( _distance == 0 )
{
holder.total_dist.setText( "NA");
}
else
{
String dist = Double.toString(Funcs.roundDouble((Double.parseDouble(_distance+"")/1000), 1));
holder.total_dist.setText( dist +" km");
}
}
else
holder.total_dist.setText( _distance +" m");
if( _betweenStopsNum == null )
{
holder.no_of_stops.setText( "NA" );
}
else
{
if(Integer.parseInt(_betweenStopsNum) == 1)
holder.no_of_stops.setText( _betweenStopsNum + " Bus stop" );
else
holder.no_of_stops.setText( _betweenStopsNum + " Bus stops" );
}
return convertView;
}
return (null);
}
public class ViewHolder {
TextView routename;
TextView head;
ImageView blue_bus;
TextView total_dist;
TextView no_of_stops;
}
@Override
public Filter getFilter() {
return null;
}
@Override
public int getCount() {
if(result != null)
return result.length;
else
return 0;
}
@Override
public Object getItem(int position) {
if(result != null)
return result[position];
else
return (null);
}
@Override
public long getItemId(int position) {
return 0;
}
}
}

View File

@ -0,0 +1,199 @@
////////////////////////////////////////////////
//
// A ChaloBEST (http://chalobest.in/) initiative
// Author: Nikita (Macgregor Techknowlogy)
// License: GPLv3
//
//
package com.best.ui;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.content.Intent;
import android.content.Context;
import android.widget.Button;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Filterable;
import android.widget.Filter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import com.best.data.GTStore;
import com.best.util.TransitionEffect;
import java.math.RoundingMode;
import java.math.BigDecimal;
import java.math.MathContext;
public class ListLocation extends ListActivity
{
public static ListActivity me = null;
public static Context m_context;
public EfficientAdapter adapter;
public static LayoutInflater mInflater;
public int EditTextNo;
public static String[] locations;
public static String[] distance;
public static String[] stopID;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate( savedInstanceState );
//overridePendingTransition( R.anim.fade_in, R.anim.fade_out );
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.DONUT) {
TransitionEffect.callOverridePendingTransition(this);
}
me = this;
m_context = this;
Bundle b = getIntent().getExtras();
stopID = b.getStringArray( "StopID" );
locations = b.getStringArray( "Stops" );
distance = b.getStringArray( "Distance" );
EditTextNo = b.getInt( "EditText" );
if( EditTextNo == Find.M_FROM_LIST_CAPTION )
setTitle(com.best.ui.R.string.fromListTitle);
else if( EditTextNo == Find.M_TO_LIST_CAPTION )
setTitle(com.best.ui.R.string.toListTitle);
else if( EditTextNo == Find.M_FROM_NEAR_BY_LIST_CAPTION || EditTextNo == Find.M_TO_NEAR_BY_LIST_CAPTION )
setTitle(com.best.ui.R.string.nearByListTitle);
try{
if(locations.length>0)
{
adapter = new EfficientAdapter(m_context,locations);
me.setListAdapter(adapter);
}
}catch(Exception e){}
}
public class EfficientAdapter extends BaseAdapter implements Filterable {
private Context context;
public EfficientAdapter(Context context , String[] locations)
{
mInflater = LayoutInflater.from(context);
this.context = context;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null)
{
convertView = mInflater.inflate(com.best.ui.R.layout.listtwotextnbtn, null);
holder = new ViewHolder();
holder.stopName = (TextView) convertView.findViewById(com.best.ui.R.id.stopname);
holder.stopDistance = (TextView) convertView.findViewById(com.best.ui.R.id.dist);
holder.btnMap = (Button) convertView.findViewById(com.best.ui.R.id.map);
holder.btnMap.setOnClickListener(new OnClickListener() {
private int pos = position;
@Override
public void onClick(View v) {
String[][] resultset = GTStore.getLatitudeLongitude( stopID[ position ] );
String latitude = resultset[0][1];
String longitude = resultset[0][2];
Intent intent = new Intent(m_context, Map.class);
Bundle bundle = new Bundle();
bundle.putBoolean( "showSingle", true );
bundle.putBoolean( "showMyPlace", ( EditTextNo == Find.M_FROM_NEAR_BY_LIST_CAPTION || EditTextNo == Find.M_TO_NEAR_BY_LIST_CAPTION ) );
bundle.putString( "lat", latitude );
bundle.putString( "long", longitude );
intent.putExtras( bundle );
me.startActivityForResult( intent, 5 );
}
});
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
String strDistance = "";
Double d = new Double( distance[ position ] );
if(d < 500)
{
strDistance = ( new BigDecimal( d.doubleValue() ).round(new MathContext( 2, RoundingMode.HALF_UP ) ).toString() )+" km";
if( d < 1 )
{
d = d * 1000;
strDistance = ( new BigDecimal( d.doubleValue() ).intValue() )+" m";
}
}
holder.stopName.setText( locations[position] );
holder.stopDistance.setText( strDistance );
holder.btnMap.setText( "Map" );
convertView.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View view)
{
Bundle bundle = new Bundle();
bundle.putString( "frmLoc" , locations[ position ] );
bundle.putInt( "position" , position );
bundle.putInt( "EditText" , EditTextNo );
bundle.putString( "stopId" , stopID[ position ] );
Intent mIntent = new Intent();
mIntent.putExtras( bundle );
int res = 0;
res = ( ( EditTextNo == Find.M_FROM_LIST_CAPTION || EditTextNo == Find.M_FROM_NEAR_BY_LIST_CAPTION )?( 1 ):( 2 ) );
setResult( res, mIntent );
finish();
}
});
return convertView;
}
public class ViewHolder {
TextView stopName;
TextView stopDistance;
Button btnMap;
}
@Override
public Filter getFilter() {
return null;
}
@Override
public int getCount() {
return locations.length;
}
@Override
public Object getItem(int position) {
return locations[position];
}
@Override
public long getItemId(int position) {
return 0;
}
}
}

View File

@ -0,0 +1,245 @@
////////////////////////////////////////////////
//
// A ChaloBEST (http://chalobest.in/) initiative
// Author: Nikita (Macgregor Techknowlogy)
// License: GPLv3
//
//
package com.best.ui;
import java.util.List;
import java.util.ArrayList;
//import org.osmdroid.constants.OpenStreetMapConstants;
import org.osmdroid.views.util.constants.MapViewConstants;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.MapController;
import org.osmdroid.views.overlay.MyLocationOverlay;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayItem;
import android.graphics.drawable.Drawable;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import org.osmdroid.api.IGeoPoint;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.MotionEvent;
import android.graphics.Rect;
import android.graphics.Paint;
import android.graphics.Path;
import org.osmdroid.util.BoundingBoxE6;
import android.content.Intent;
import android.content.Context;
import android.util.DisplayMetrics;
public class Map extends Activity implements MapViewConstants {
private MapView mapView;
private MyLocationOverlay mLocationOverlay;
private MapController mapController;
public static GeoPoint geoPoint1 = null;
public static GeoPoint geoPoint2 = null;
public static GeoPoint averagePoint = null;
public static boolean m_srcIsNew = true;
public static boolean m_markerShown = false;
public static Context m_context;
public static boolean m_showSingle = true;
public static boolean showMyPlace = false;
public boolean isFirstMapping = true;
public static String[] stopsGeoX = null;
public static String[] stopsGeoY = null;
public int minLatitude = 0;
public int maxLatitude = 0;
public int minLongitude= 0;
public int maxLongitude = 0;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
this.setContentView( com.best.ui.R.layout.mapstops );
m_context = this;
try{
mapView = ( MapView ) findViewById( com.best.ui.R.id.mapview );
mapView.setBuiltInZoomControls( true );
mapController = mapView.getController();
Bundle bundle = getIntent().getExtras();
if( ( m_showSingle = bundle.getBoolean( "showSingle" ) ) == true )
{
Double lat = Double.parseDouble( bundle.getString( "lat" ) );
Double lon = Double.parseDouble( bundle.getString( "long" ) );
geoPoint1 = new GeoPoint( lat, lon );
try{
showMyPlace = (boolean)bundle.getBoolean( "showMyPlace" );
if( showMyPlace && Best.m_latitude.length() > 0 && Best.m_longitude.length() > 0 )
{
Double latDouble = Double.valueOf( Best.m_latitude );//Double.valueOf( "40.45939" );
Double longDouble = Double.valueOf( Best.m_longitude );//Double.valueOf( "-3.78429" );
geoPoint2 = new GeoPoint( latDouble, longDouble );
}
}catch(Exception e){}
averagePoint = geoPoint1;
}
else
{
stopsGeoX = (String[])bundle.getSerializable("StopsGeoX");
stopsGeoY = (String[])bundle.getSerializable("StopsGeoY");
geoPoint1 = new GeoPoint( Double.parseDouble(stopsGeoX[0]), Double.parseDouble(stopsGeoY[0]) );
geoPoint2 = new GeoPoint( Double.parseDouble(stopsGeoX[stopsGeoX.length - 1]), Double.parseDouble(stopsGeoY[stopsGeoY.length - 1]) );
}
if( geoPoint1 != null && geoPoint2 != null )
{
int geoPointLat1 = geoPoint1.getLatitudeE6();
int geoPointLon1 = geoPoint1.getLongitudeE6();
int geoPointLat2 = geoPoint2.getLatitudeE6();
int geoPointLon2 = geoPoint2.getLongitudeE6();
minLatitude = ( geoPointLat1 > geoPointLat2 ) ? geoPointLat2 : geoPointLat1;
maxLatitude = ( geoPointLat1 < geoPointLat2 ) ? geoPointLat2 : geoPointLat1;
minLongitude = ( geoPointLon1 > geoPointLon2 ) ? geoPointLon2 : geoPointLon1;
maxLongitude = ( geoPointLon1 < geoPointLon2 ) ? geoPointLon2 : geoPointLon1;
int avgLat = ( maxLatitude + minLatitude )/2;
int avgLong = ( maxLongitude + minLongitude )/2 ;
averagePoint = GeoPoint.fromCenterBetween( geoPoint1, geoPoint2 );//= new GeoPoint( avgLat, avgLong );
// if( mapView.getBoundingBox().getDiagonalLengthInMeters() == 0 )
// {
// int latSpan = maxLatitude - minLatitude;
// int longSpan = maxLongitude - minLongitude;
// Integer maxSpan = Math.max( latSpan, longSpan );
// Double ln = Math.log( maxSpan.doubleValue() );
// zoomLevel = 20-ln.intValue();
// if ( zoomLevel < 5 )
// zoomLevel += 2;
// else if ( zoomLevel > 18 )
// zoomLevel = 18;
// }
// else
// mapController.zoomToSpan( ( maxLatitude - minLatitude ),( maxLongitude - minLongitude ) );
}
else
{
mapController.setZoom( 18 ); //always shud come befor setCenter and animate to
mapController.setCenter( averagePoint );
mapController.animateTo( averagePoint );
}
MapOverlay mapOverlay = new MapOverlay( m_context, mapView );
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add( mapOverlay );
mapView.invalidate();
}catch(Exception e){ e.printStackTrace(); Best.showError( m_context, com.best.ui.R.string.errNoMap );}
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
}
class MapOverlay extends org.osmdroid.views.overlay.MyLocationOverlay
{
public MapOverlay(Context context, MapView mapview)
{
super( context, mapview );
}
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow)
{
super.draw(canvas, mapView, shadow);
Point screenPts1, screenPts2;
Bitmap bmp = BitmapFactory.decodeResource( getResources(), com.best.ui.R.drawable.bus_small1 );
screenPts1 = new Point();
mapView.getProjection().toPixels( geoPoint1, screenPts1 );
canvas.drawBitmap( bmp, screenPts1.x - 6, screenPts1.y - 6, null );
screenPts2 = new Point();
if( !m_showSingle )
{
mapView.getProjection().toPixels(geoPoint2, screenPts2);
canvas.drawBitmap( bmp, screenPts2.x - 6, screenPts2.y - 6, null );
if(stopsGeoX != null && stopsGeoY != null)
{
Paint paint = new Paint();
paint.setColor(0xffff0000);
paint.setStrokeWidth(3);
Path path = new Path();
GeoPoint geopointStart = new GeoPoint(Double.parseDouble(stopsGeoX[0]) ,Double.parseDouble(stopsGeoY[0]));
mapView.getProjection().toPixels( geopointStart, screenPts1 );
path.moveTo(screenPts1.x, screenPts1.y);
for(int index = 1; index < stopsGeoX.length;index++)
{
GeoPoint nextGeoPoint= new GeoPoint(Double.parseDouble(stopsGeoX[index]) ,Double.parseDouble(stopsGeoY[index]));
mapView.getProjection().toPixels( nextGeoPoint, screenPts1 );
path.lineTo(screenPts1.x , screenPts1.y);
}
paint.setStyle(Paint.Style.STROKE);
canvas.drawPath (path, paint);
}
}
else
{
if( geoPoint2 != null && showMyPlace )
{
Bitmap bmpUser = BitmapFactory.decodeResource( getResources(), com.best.ui.R.drawable.user );
mapView.getProjection().toPixels( geoPoint2, screenPts2);
canvas.drawBitmap( bmpUser, screenPts2.x - 5, screenPts2.y - 5, null );
}
}
if( isFirstMapping == true && geoPoint1 != null && geoPoint2 != null)
{
setZoomAndCentre();
isFirstMapping = false;
}
mapView.invalidate();
}
public void setZoomAndCentre()
{
mapController.zoomToSpan( ( maxLatitude - minLatitude ),( maxLongitude - minLongitude )) ;
mapController.setCenter( averagePoint );
mapController.animateTo( averagePoint );
// BoundingBoxE6 bbox = mapView.getBoundingBox();
// System.out.println("==========Bounding box latitudeSpan = "+bbox.getLatitudeSpanE6() );
// System.out.println("==========Bounding box diameter = "+bbox.getDiagonalLengthInMeters() );
}
}
}

View File

@ -0,0 +1,309 @@
////////////////////////////////////////////////
//
// A ChaloBEST (http://chalobest.in/) initiative
// Author: Nikita (Macgregor Techknowlogy)
// License: GPLv3
//
//
package com.best.ui;
import android.app.Activity;
import android.app.ListActivity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Message;
import android.os.Handler;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.EditText;
import android.widget.Button;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Filterable;
import android.widget.Filter;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.View.OnClickListener;
import com.best.data.GTStore;
import com.best.util.TransitionEffect;
import java.util.List;
import java.util.ArrayList;
import android.graphics.Color;
import android.text.Html;
public class Routes extends ListActivity {
public static ListActivity me;
public static Context m_context;
public static LayoutInflater mInflater;
public static String sourceId="";
public static String destId="";
public static String _tripID;
public static String _startStopID = "";
public static String _endStopID = "";
public static String[] stopGeoPoints;
public static String[][]routeResult = null;
ArrayList<String> listStopsGeoX = new ArrayList<String>();
ArrayList<String> listStopsGeoY = new ArrayList<String>();
public static boolean showFullRoute = true;
public void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.DONUT)
TransitionEffect.callOverridePendingTransition(this);
//overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
me = this;
m_context = this;
me.setContentView( com.best.ui.R.layout.routes );
mInflater = LayoutInflater.from(m_context);
Bundle bundle = getIntent().getExtras();
_tripID = bundle.getString( "tripID" );
sourceId = bundle.getString("sourceID");
destId = bundle.getString("destID");
showFullRoute = bundle.getBoolean("showFullRoute");
init( _tripID );
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
if(showFullRoute == true)
inflater.inflate(com.best.ui.R.menu.onlymap, menu);
else
inflater.inflate(com.best.ui.R.menu.mapfullroute, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case com.best.ui.R.id.map:
Bundle bundle1 = new Bundle();
bundle1.putBoolean( "showSingle", false );
bundle1.putSerializable("StopsGeoX",listStopsGeoX.toArray( new String[ listStopsGeoX.size() ] ));
bundle1.putSerializable("StopsGeoY",listStopsGeoY.toArray( new String[ listStopsGeoY.size() ] ));
Intent intent = new Intent(m_context, Map.class);
intent.putExtras( bundle1 );
me.startActivityForResult(intent,5);
return true;
case com.best.ui.R.id.fullRoute:
Intent intent1 = new Intent(m_context, Routes.class);
Bundle bundle = new Bundle();
bundle.putString( "tripID",_tripID );
bundle.putString("sourceID", sourceId);
bundle.putString("destID", destId);
bundle.putBoolean("showFullRoute", true);
//bundle.putSerializable("routeResult", routeResult);
intent1.putExtras( bundle );
me.startActivityForResult(intent1,6);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void init(String tripID)
{
if(showFullRoute == false)
{
Best.showProcessing(m_context, "Processing","Please wait..." );
TripInfoThread tripInfoThread = new TripInfoThread( tripInfoHandler );
tripInfoThread.start();
}
else if( routeResult != null && routeResult.length > 0)
{
for(int index = 0; index < routeResult.length; index++)
{
listStopsGeoX.add( routeResult[index][3] );
listStopsGeoY.add( routeResult[index][4] );
}
EfficientAdapter adapter = new EfficientAdapter( m_context,routeResult);
me.setListAdapter( adapter );
}
else
Best.showMessage( m_context, "Sorry something went wrong.", "Processing" );
}
public Handler tripInfoHandler = new Handler() {
public void handleMessage(Message msg) {
Bundle dataBundle = msg.getData();
Best.dissmissProcessing();
routeResult = ( String[][] )dataBundle.getSerializable( "rts" );
if( showFullRoute == false && routeResult != null && routeResult.length > 0 )
{
List<String[]> listspecificRoute = new ArrayList<String[]>();
outer: for(int index = 0; index < routeResult.length; index++)
{
if((routeResult[index][1]).equals(sourceId))
{
for(int i = index; i< routeResult.length; i++)
{
if((routeResult[i][1]).equals(destId))
{
listStopsGeoX.add( routeResult[i][3] );
listStopsGeoY.add( routeResult[i][4] );
listspecificRoute.add(routeResult[ i ]);
Best.log( " DT :: " + android.text.TextUtils.join( ",", routeResult[ i ] ) );
break outer;
}
else
{
listStopsGeoX.add( routeResult[i][3] );
listStopsGeoY.add( routeResult[i][4] );
listspecificRoute.add(routeResult[ i ]);
}
}
}
}
if(listspecificRoute.toArray( new String[ listspecificRoute.size() ][] ) == null)
Best.showMessage( m_context, "Sorry something went wrong.", "Processing" );
EfficientAdapter adapter = new EfficientAdapter( m_context,listspecificRoute.toArray( new String[ listspecificRoute.size() ][] ) );
me.setListAdapter( adapter );
}
}
};
private class TripInfoThread extends Thread
{
Handler _handler;
TripInfoThread(Handler handler )
{
_handler = handler;
}
public void run()
{
//code to get all routes
Bundle dataBundle = new Bundle();
dataBundle.putSerializable( "rts", GTStore.getTripInfo(_tripID));
Message msg = _handler.obtainMessage();
msg.setData( dataBundle );
_handler.sendMessage( msg );
}
}
public class EfficientAdapter extends BaseAdapter implements Filterable {
public String[][] result;
public int resultSetLength;
public EfficientAdapter(Context context, String[][] resultSet)
{
mInflater = LayoutInflater.from( context );
result = new String[resultSet.length][];
result=resultSet;
resultSetLength = resultSet.length;
stopGeoPoints = new String[resultSet.length];
if(resultSet == null)
Best.showError(context ,"No route between Source and Destination");
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null)
{
convertView = mInflater.inflate(com.best.ui.R.layout.listthreetext, null);
holder = new ViewHolder();
holder.stop_name = (TextView) convertView.findViewById(com.best.ui.R.id.stopname);
holder.dep_time = (TextView) convertView.findViewById(com.best.ui.R.id.dep);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
if(position==0 && showFullRoute == true)
{
holder.stop_name.setText(Html.fromHtml("<font color = 'black'>"+"Bus starts at: "+"</font>"+"<font color = 'DarkSlateBlue'>"+result[position][0]+"</font>"));
_startStopID = result[position][1];
}
else if(position==(resultSetLength - 1) && showFullRoute == true )
{
holder.stop_name.setText(Html.fromHtml("<font color = 'black'>"+"Bus stops at: "+"</font>"+"<font color = 'DarkSlateBlue'>"+result[position][0]+"</font>"));
_endStopID = result[position][1];
}
else
holder.stop_name.setText(result[position][0]);
//String[] depParts = result[position][2].split('+');
//holder.dep_time.setText(result[position][2]);
stopGeoPoints[position] = result[position][3];
if((result[position][1]).equals(sourceId) || (result[position][1]).equals(destId))
convertView.setBackgroundColor(Color.parseColor("#d4b6d4")); //0xffcccccc
else
convertView.setBackgroundColor(0xffffffff);
return convertView;
}
public class ViewHolder {
TextView stop_name;
TextView dep_time;
}
@Override
public Filter getFilter() {
return null;
}
@Override
public int getCount() {
return result.length;
}
@Override
public Object getItem(int position) {
return result[position];
}
@Override
public long getItemId(int position) {
return 0;
}
}
}

View File

@ -0,0 +1,41 @@
////////////////////////////////////////////////
//
// A ChaloBEST (http://chalobest.in/) initiative
// Author: Nikita (Macgregor Techknowlogy)
// License: GPLv3
//
//
package com.best.ui;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.content.Context;
import android.view.MotionEvent;
import android.widget.LinearLayout;
import com.best.util.TransitionEffect;
public class SplashScreen1 extends Activity {
protected boolean _active = true;
protected int _splashTime = 1200; // time to display the splash screen in ms
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.DONUT)
TransitionEffect.callOverridePendingTransition(this);
//overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
// Splash screen view
setContentView(com.best.ui.R.layout.splash);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
_active = false;
}
return true;
}
}

View File

@ -0,0 +1,248 @@
////////////////////////////////////////////////
//
// A ChaloBEST (http://chalobest.in/) initiative
// Author: Vivek(Macgregor Techknowlogy)
// License: GPLv3
//
//
package com.best.util;
import java.util.Calendar;
import java.util.Formatter;
import com.best.ui.Best;
public class Funcs{
public static String addTime(String time, String addPeriod)
{
//expects both parameter in format "hh:mm:ss"
String[] timeSplit = time.split( ":" );
String[] periodSplit = addPeriod.split( ":" );
// "01:50:59" +
// "19:32:20"
// ---------
// "21:23:19"
if( timeSplit.length == 3 && periodSplit.length == 3 )
{
String newTime = "";
boolean useOver = false;
for( int cnt = 2; cnt >= 0; cnt-- )
{
int part1 = Integer.parseInt( timeSplit[ cnt ] );
int part2 = Integer.parseInt( periodSplit[ cnt ] );
int sum = part1 + part2 + ( ( useOver )?( 1 ):( 0 ) );
useOver = false;
if( cnt > 0 )
{
if( sum >= 60 )
{
sum = sum - 60;
useOver = true;
}
}
else
{
if( sum >= 24 )
{
sum = 0;
useOver = true;
}
}
newTime = ( ( (""+sum).length() == 2 )?( sum ):( "0"+sum ) ) + ( ( cnt < 2 )?( ":" ):( "" ) ) + newTime;
}
return( newTime );
}
return( null );
}
public static long timeToSeconds(String t)
{
t = t.trim();
if( t.indexOf( " " ) > 0 )
{
String[] _tmp = t.split( " " );
t = _tmp[ 0 ];
}
if( t.indexOf( "+" ) > 0 )
{
String[] _tmp = t.split( "\\+" );
t = _tmp[ 0 ];
}
String[] t_split = t.split( ":" );
int hr = 0; int min = 0; long sec = 0;
int len = t_split.length;
if( len >= 3 )
{
try{ hr = Integer.parseInt( t_split[ 0 ] ); }catch(Exception e){}
try{ min = Integer.parseInt( t_split[ 1 ] ); }catch(Exception e){}
try{ sec = Integer.parseInt( t_split[ 2 ] ); }catch(Exception e){}
sec += ( min * 60 ) + ( hr * 3600 );
}
else if( len == 2 )
{
try{min = Integer.parseInt( t_split[ 0 ] ); }catch(Exception e){}
try{sec = Integer.parseInt( t_split[ 1 ] ); }catch(Exception e){}
sec += ( min * 60 );
}
else
try{ sec = Integer.parseInt( t_split[ 0 ] ); }catch(Exception e){}
if(t.contains("PM") && hr != 12)
sec += 12 * 3600;
return( sec );
}
public static String secondsToTimeFormat( int seconds)
{
int hr = seconds/3600;
seconds = seconds%3600;
int min = seconds/60;
seconds = seconds%60;
return(hr+":"+min+":"+seconds);
}
public static String subtractTime(String timeStart, String timeEnd)
{
//expects both parameter in format "hh:mm:ss"
String[] timeStartSplit = timeStart.split( ":" );
String[] timeEndSplit = timeEnd.split( ":" );
if( timeStartSplit.length == 3 && timeEndSplit.length == 3 )
{
String newTime = "";
boolean useOver = false;
for( int cnt = 2; cnt >= 0; cnt-- )
{
int part1 = Integer.parseInt( timeStartSplit[ cnt ] );
int part2 = Integer.parseInt( timeEndSplit[ cnt ] );
boolean resetUO = true;
if( cnt > 0 && part2 == 0 )
{ part2 = 60; resetUO = false; }
int diff = part2 - part1 - ( ( useOver )?( 1 ):( 0 ) );
if( resetUO )
useOver = false;
else
useOver = true;
if( cnt > 0 )
{
if( diff < 0 )
{
diff = diff * -1;
useOver = true;
}
}
else
{
if( diff < 0 )
{
diff = 0;
useOver = true;
}
}
newTime = ( ( (""+diff).length() == 2 )?( diff ):( "0"+diff ) ) + ( ( cnt < 2 )?( ":" ):( "" ) ) + newTime;
}
return( newTime );
}
return( null );
}
public static String formatTimeSpan(String timeSpan)
{
String timeSpanFormatd = "";
String[] timeSpanSplit = timeSpan.split(":");
int timeSpanHr = 0;
int timeSpanMin = 0;
int timeSpanSec = 0;
try{ timeSpanHr = Integer.parseInt( timeSpanSplit[ 0 ] ); }catch( Exception e ){}
try{ timeSpanMin = Integer.parseInt( timeSpanSplit[ 1 ] ); }catch( Exception e ){}
try{ timeSpanSec = Integer.parseInt( timeSpanSplit[ 2 ] ); }catch( Exception e ){}
timeSpanFormatd = timeSpanHr+":";
if( timeSpanSec > 30 )
timeSpanMin++;
timeSpanFormatd += timeSpanMin;
return( timeSpanFormatd );
}
public static double roundDouble(double value, int places) {
if (places > 0)
{
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
return value;
}
public static String getCurrentDay(){
return( ( new Formatter() ).format( "%ta", Calendar.getInstance() ).toString() );
}
public static String getCurrentTime(boolean _24HrBased){
if( _24HrBased )
return( ( new Formatter() ).format( "%tT", Calendar.getInstance() ).toString() );
else
return( ( new Formatter() ).format( "%tr", Calendar.getInstance() ).toString() );
}
public static Calendar getNextDay(Calendar calendar){
calendar.add( Calendar.DAY_OF_MONTH, +1 );
return( calendar );
}
public static Calendar addTime(Calendar calendar, String time){
try{
String s[] = time.split( ":" );
calendar.add( Calendar.HOUR, Integer.parseInt( s[ 0 ] ) );
calendar.add( Calendar.MINUTE, Integer.parseInt( s[ 1 ] ) );
return( calendar );
}catch( Exception e ){}
return( null );
}
public static String[] getHashKeys( java.util.Hashtable h)
{
String[] starr = new String[ h.size() ];
java.util.Enumeration e = h.keys();
int c = 0;
while( e.hasMoreElements() )
{
starr[ c++ ] = (String)e.nextElement();
}
return( starr );
}
}

View File

@ -0,0 +1,12 @@
package com.best.util;
import android.app.Activity;
import android.content.Context;
public class TransitionEffect{
public static void callOverridePendingTransition(Activity m_context)
{
m_context.overridePendingTransition(com.best.ui.R.anim.fade_in_center, com.best.ui.R.anim.fade_out_center);
}
}

Binary file not shown.

View File

@ -0,0 +1,25 @@
package jsqlite;
/**
* Callback interface for SQLite's authorizer function.
*/
public interface Authorizer {
/**
* Callback to authorize access.
*
* @param what integer indicating type of access
* @param arg1 first argument (table, view, index, or trigger name)
* @param arg2 second argument (file, table, or column name)
* @param arg3 third argument (database name)
* @param arg4 third argument (trigger name)
* @return Constants.SQLITE_OK for success, Constants.SQLITE_IGNORE
* for don't allow access but don't raise an error, Constants.SQLITE_DENY
* for abort SQL statement with error.
*/
public int authorize(int what, String arg1, String arg2, String arg3,
String arg4);
}

Binary file not shown.

View File

@ -0,0 +1,99 @@
package jsqlite;
/**
* Class wrapping an SQLite backup object.
*/
public class Backup {
/**
* Internal handle for the native SQLite API.
*/
protected long handle = 0;
/**
* Finish a backup.
*/
protected void finish() throws jsqlite.Exception {
synchronized(this) {
_finalize();
}
}
/**
* Destructor for object.
*/
protected void finalize() {
synchronized(this) {
try {
_finalize();
} catch (jsqlite.Exception e) {
}
}
}
protected native void _finalize() throws jsqlite.Exception;
/**
* Perform a backup step.
*
* @param n number of pages to backup
* @return true when backup completed
*/
public boolean step(int n) throws jsqlite.Exception {
synchronized(this) {
return _step(n);
}
}
private native boolean _step(int n) throws jsqlite.Exception;
/**
* Perform the backup in one step.
*/
public void backup() throws jsqlite.Exception {
synchronized(this) {
_step(-1);
}
}
/**
* Return number of remaining pages to be backed up.
*/
public int remaining() throws jsqlite.Exception {
synchronized(this) {
return _remaining();
}
}
private native int _remaining() throws jsqlite.Exception;
/**
* Return the total number of pages in the backup source database.
*/
public int pagecount() throws jsqlite.Exception {
synchronized(this) {
return _pagecount();
}
}
private native int _pagecount() throws jsqlite.Exception;
/**
* Internal native initializer.
*/
private static native void internal_init();
static {
internal_init();
}
}

Binary file not shown.

View File

@ -0,0 +1,786 @@
/*
* This is a sample implementation of the
* Transaction Processing Performance Council
* Benchmark B coded in Java/JDBC and ANSI SQL2.
*
* This version is using one connection per
* thread to parallellize server operations.
*/
package jsqlite;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Vector;
public abstract class Benchmark {
/* the tps scaling factor: here it is 1 */
public static int tps = 1;
/* number of branches in 1 tps db */
public static int nbranches = 1;
/* number of tellers in 1 tps db */
public static int ntellers = 10;
/* number of accounts in 1 tps db */
public static int naccounts = 50000;
/* number of history recs in 1 tps db */
public static int nhistory = 864000;
public final static int TELLER = 0;
public final static int BRANCH = 1;
public final static int ACCOUNT = 2;
int failed_transactions = 0;
int transaction_count = 0;
static int n_clients = 10;
static int n_txn_per_client = 10;
long start_time = 0;
static boolean transactions = true;
static boolean prepared_stmt = false;
static boolean verbose = false;
/*
* main program
* creates a 1-tps database:
* i.e. 1 branch, 10 tellers,...
* runs one TPC BM B transaction
*/
public void run(String[] args) {
String DriverName = "";
String DBUrl = "";
String DBUser = "";
String DBPassword = "";
boolean initialize_dataset = false;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-clients")) {
if (i + 1 < args.length) {
i++;
n_clients = Integer.parseInt(args[i]);
}
} else if (args[i].equals("-driver")) {
if (i + 1 < args.length) {
i++;
DriverName = args[i];
}
} else if (args[i].equals("-url")) {
if (i + 1 < args.length) {
i++;
DBUrl = args[i];
}
} else if (args[i].equals("-user")) {
if (i + 1 < args.length) {
i++;
DBUser = args[i];
}
} else if (args[i].equals("-password")) {
if (i + 1 < args.length) {
i++;
DBPassword = args[i];
}
} else if (args[i].equals("-tpc")) {
if (i + 1 < args.length) {
i++;
n_txn_per_client = Integer.parseInt(args[i]);
}
} else if (args[i].equals("-init")) {
initialize_dataset = true;
} else if (args[i].equals("-tps")) {
if (i + 1 < args.length) {
i++;
tps = Integer.parseInt(args[i]);
}
} else if (args[i].equals("-v")) {
verbose = true;
}
}
if (DriverName.length() == 0 || DBUrl.length() == 0) {
System.out.println("JDBC based benchmark program\n\n" +
"JRE usage:\n\njava jsqlite.BenchmarkDriver " +
"-url [url_to_db] \\\n " +
"[-user [username]] " +
"[-password [password]] " +
"[-driver [driver_class_name]] \\\n " +
"[-v] [-init] [-tpc N] [-tps N] " +
"[-clients N]\n");
System.out.println("OJEC usage:\n\ncvm jsqlite.BenchmarkDataSource " +
"[-user [username]] " +
"[-password [password]] " +
"[-driver [driver_class_name]] \\\n " +
"[-v] [-init] [-tpc N] [-tps N] " +
"[-clients N]\n");
System.out.println();
System.out.println("-v verbose mode");
System.out.println("-init initialize the tables");
System.out.println("-tpc N transactions per client");
System.out.println("-tps N scale factor");
System.out.println("-clients N number of simultaneous clients/threads");
System.out.println();
System.out.println("Default driver class is jsqlite.JDBCDriver");
System.out.println("in this case use an -url parameter of the form");
System.out.println(" jdbc:sqlite:/[path]");
System.exit(1);
}
System.out.println("Driver: " + DriverName);
System.out.println("URL:" + DBUrl);
System.out.println();
System.out.println("Scale factor value: " + tps);
System.out.println("Number of clients: " + n_clients);
System.out.println("Number of transactions per client: " +
n_txn_per_client);
System.out.println();
try {
benchmark(DBUrl, DBUser, DBPassword, initialize_dataset);
} catch (java.lang.Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public void benchmark(String url, String user, String password, boolean init) {
Vector vClient = new Vector();
Thread Client = null;
Enumeration en = null;
try {
if (init) {
System.out.print("Initializing dataset...");
createDatabase(url, user, password);
System.out.println("done.\n");
}
System.out.println("* Starting Benchmark Run *");
transactions = false;
prepared_stmt = false;
start_time = System.currentTimeMillis();
for (int i = 0; i < n_clients; i++) {
Client = new BenchmarkThread(n_txn_per_client, url, user,
password, this);
Client.start();
vClient.addElement(Client);
}
/*
* Barrier to complete this test session
*/
en = vClient.elements();
while (en.hasMoreElements()) {
Client = (Thread) en.nextElement();
Client.join();
}
vClient.removeAllElements();
reportDone();
transactions = true;
prepared_stmt = false;
start_time = System.currentTimeMillis();
for (int i = 0; i < n_clients; i++) {
Client = new BenchmarkThread(n_txn_per_client, url,
user, password, this);
Client.start();
vClient.addElement(Client);
}
/*
* Barrier to complete this test session
*/
en = vClient.elements();
while (en.hasMoreElements()) {
Client = (Thread) en.nextElement();
Client.join();
}
vClient.removeAllElements();
reportDone();
transactions = false;
prepared_stmt = true;
start_time = System.currentTimeMillis();
for (int i = 0; i < n_clients; i++) {
Client = new BenchmarkThread(n_txn_per_client, url,
user, password, this);
Client.start();
vClient.addElement(Client);
}
/*
* Barrier to complete this test session
*/
en = vClient.elements();
while (en.hasMoreElements()) {
Client = (Thread) en.nextElement();
Client.join();
}
vClient.removeAllElements();
reportDone();
transactions = true;
prepared_stmt = true;
start_time = System.currentTimeMillis();
for (int i = 0; i < n_clients; i++) {
Client = new BenchmarkThread(n_txn_per_client, url,
user, password, this);
Client.start();
vClient.addElement(Client);
}
/*
* Barrier to complete this test session
*/
en = vClient.elements();
while (en.hasMoreElements()) {
Client = (Thread) en.nextElement();
Client.join();
}
vClient.removeAllElements();
reportDone();
} catch (java.lang.Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
System.exit(0);
}
}
public void reportDone() {
long end_time = System.currentTimeMillis();
double completion_time =
((double)end_time - (double)start_time) / 1000;
System.out.println("\n* Benchmark Report *" );
System.out.print("* Featuring ");
if (prepared_stmt) {
System.out.print("<prepared statements> ");
} else {
System.out.print("<direct queries> ");
}
if (transactions) {
System.out.print("<transactions> ");
} else {
System.out.print("<auto-commit> ");
}
System.out.println("\n--------------------");
System.out.println("Time to execute " +
transaction_count + " transactions: " +
completion_time + " seconds.");
System.out.println(failed_transactions + " / " +
transaction_count + " failed to complete.");
double rate = (transaction_count - failed_transactions)
/ completion_time;
System.out.println("Transaction rate: " + rate + " txn/sec.");
transaction_count = 0;
failed_transactions = 0;
System.gc();
}
public synchronized void incrementTransactionCount() {
transaction_count++;
}
public synchronized void incrementFailedTransactionCount() {
failed_transactions++;
}
void createDatabase(String url, String user, String password)
throws java.lang.Exception {
Connection Conn = connect(url, user, password);
String s = Conn.getMetaData().getDatabaseProductName();
System.out.println("DBMS: "+s);
transactions = true;
if (transactions) {
try {
Conn.setAutoCommit(false);
System.out.println("In transaction mode");
} catch (SQLException etxn) {
transactions = false;
}
}
try {
int accountsnb = 0;
Statement Stmt = Conn.createStatement();
String Query;
Query = "SELECT count(*) FROM accounts";
ResultSet RS = Stmt.executeQuery(Query);
Stmt.clearWarnings();
while (RS.next()) {
accountsnb = RS.getInt(1);
}
if (transactions) {
Conn.commit();
}
Stmt.close();
if (accountsnb == (naccounts*tps)) {
System.out.println("Already initialized");
connectClose(Conn);
return;
}
} catch (java.lang.Exception e) {
}
System.out.println("Drop old tables if they exist");
try {
Statement Stmt = Conn.createStatement();
String Query;
Query = "DROP TABLE history";
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "DROP TABLE accounts";
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "DROP TABLE tellers";
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "DROP TABLE branches";
Stmt.execute(Query);
Stmt.clearWarnings();
if (transactions) {
Conn.commit();
}
Stmt.close();
} catch (java.lang.Exception e) {
}
System.out.println("Creates tables");
try {
Statement Stmt = Conn.createStatement();
String Query;
Query = "CREATE TABLE branches (";
Query += "Bid INTEGER NOT NULL PRIMARY KEY,";
Query += "Bbalance INTEGER,";
Query += "filler CHAR(88))"; /* pad to 100 bytes */
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "CREATE TABLE tellers (";
Query += "Tid INTEGER NOT NULL PRIMARY KEY,";
Query += "Bid INTEGER,";
Query += "Tbalance INTEGER,";
Query += "filler CHAR(84))"; /* pad to 100 bytes */
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "CREATE TABLE accounts (";
Query += "Aid INTEGER NOT NULL PRIMARY KEY,";
Query += "Bid INTEGER,";
Query += "Abalance INTEGER,";
Query += "filler CHAR(84))"; /* pad to 100 bytes */
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "CREATE TABLE history (";
Query += "Tid INTEGER,";
Query += "Bid INTEGER,";
Query += "Aid INTEGER,";
Query += "delta INTEGER,";
Query += "tstime TIMESTAMP,";
Query += "filler CHAR(22))"; /* pad to 50 bytes */
Stmt.execute(Query);
Stmt.clearWarnings();
if (transactions) {
Conn.commit();
}
Stmt.close();
} catch (java.lang.Exception e) {
}
System.out.println("Delete elements in table in case DROP didn't work");
try {
Statement Stmt = Conn.createStatement();
String Query;
Query = "DELETE FROM history";
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "DELETE FROM accounts";
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "DELETE FROM tellers";
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "DELETE FROM branches";
Stmt.execute(Query);
Stmt.clearWarnings();
if (transactions) {
Conn.commit();
}
/*
* prime database using TPC BM B scaling rules.
* Note that for each branch and teller:
* branch_id = teller_id / ntellers
* branch_id = account_id / naccounts
*/
PreparedStatement pstmt = null;
prepared_stmt = true;
if (prepared_stmt) {
try {
Query = "INSERT INTO branches(Bid,Bbalance) VALUES (?,0)";
pstmt = Conn.prepareStatement(Query);
System.out.println("Using prepared statements");
} catch (SQLException estmt) {
pstmt = null;
prepared_stmt = false;
}
}
System.out.println("Insert data in branches table");
for (int i = 0; i < nbranches * tps; i++) {
if (prepared_stmt) {
pstmt.setInt(1,i);
pstmt.executeUpdate();
pstmt.clearWarnings();
} else {
Query = "INSERT INTO branches(Bid,Bbalance) VALUES (" +
i + ",0)";
Stmt.executeUpdate(Query);
}
if ((i%100==0) && (transactions)) {
Conn.commit();
}
}
if (prepared_stmt) {
pstmt.close();
}
if (transactions) {
Conn.commit();
}
if (prepared_stmt) {
Query = "INSERT INTO tellers(Tid,Bid,Tbalance) VALUES (?,?,0)";
pstmt = Conn.prepareStatement(Query);
}
System.out.println("Insert data in tellers table");
for (int i = 0; i < ntellers * tps; i++) {
if (prepared_stmt) {
pstmt.setInt(1,i);
pstmt.setInt(2,i/ntellers);
pstmt.executeUpdate();
pstmt.clearWarnings();
} else {
Query = "INSERT INTO tellers(Tid,Bid,Tbalance) VALUES (" +
i + "," + i / ntellers + ",0)";
Stmt.executeUpdate(Query);
}
if ((i%100==0) && (transactions)) {
Conn.commit();
}
}
if (prepared_stmt) {
pstmt.close();
}
if (transactions) {
Conn.commit();
}
if (prepared_stmt) {
Query = "INSERT INTO accounts(Aid,Bid,Abalance) VALUES (?,?,0)";
pstmt = Conn.prepareStatement(Query);
}
System.out.println("Insert data in accounts table");
for (int i = 0; i < naccounts*tps; i++) {
if (prepared_stmt) {
pstmt.setInt(1,i);
pstmt.setInt(2,i/naccounts);
pstmt.executeUpdate();
pstmt.clearWarnings();
} else {
Query = "INSERT INTO accounts(Aid,Bid,Abalance) VALUES (" +
i + "," + i / naccounts + ",0)";
Stmt.executeUpdate(Query);
}
if ((i%10000==0) && (transactions)) {
Conn.commit();
}
if ((i>0) && ((i%10000)==0)) {
System.out.println("\t" + i + "\t records inserted");
}
}
if (prepared_stmt) {
pstmt.close();
}
if (transactions) {
Conn.commit();
}
System.out.println("\t" + (naccounts*tps) + "\t records inserted");
Stmt.close();
} catch (java.lang.Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
connectClose(Conn);
}
public static int getRandomInt(int lo, int hi) {
int ret = 0;
ret = (int)(Math.random() * (hi - lo + 1));
ret += lo;
return ret;
}
public static int getRandomID(int type) {
int min, max, num;
max = min = 0;
num = naccounts;
switch(type) {
case TELLER:
min += nbranches;
num = ntellers;
/* FALLTHROUGH */
case BRANCH:
if (type == BRANCH) {
num = nbranches;
}
min += naccounts;
/* FALLTHROUGH */
case ACCOUNT:
max = min + num - 1;
}
return (getRandomInt(min, max));
}
public abstract Connection connect(String DBUrl, String DBUser,
String DBPassword);
public static void connectClose(Connection c) {
if (c == null) {
return;
}
try {
c.close();
} catch (java.lang.Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
class BenchmarkThread extends Thread {
int ntrans = 0;
Connection Conn;
Benchmark bench;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
PreparedStatement pstmt3 = null;
PreparedStatement pstmt4 = null;
PreparedStatement pstmt5 = null;
public BenchmarkThread(int number_of_txns,String url,
String user, String password,
Benchmark b) {
bench = b;
ntrans = number_of_txns;
Conn = b.connect(url, user, password);
if (Conn == null) {
return;
}
try {
if (Benchmark.transactions) {
Conn.setAutoCommit(false);
}
if (Benchmark.prepared_stmt) {
String Query;
Query = "UPDATE accounts";
Query += " SET Abalance = Abalance + ?";
Query += " WHERE Aid = ?";
pstmt1 = Conn.prepareStatement(Query);
Query = "SELECT Abalance";
Query += " FROM accounts";
Query += " WHERE Aid = ?";
pstmt2 = Conn.prepareStatement(Query);
Query = "UPDATE tellers";
Query += " SET Tbalance = Tbalance + ?";
Query += " WHERE Tid = ?";
pstmt3 = Conn.prepareStatement(Query);
Query = "UPDATE branches";
Query += " SET Bbalance = Bbalance + ?";
Query += " WHERE Bid = ?";
pstmt4 = Conn.prepareStatement(Query);
Query = "INSERT INTO history(Tid, Bid, Aid, delta)";
Query += " VALUES (?,?,?,?)";
pstmt5 = Conn.prepareStatement(Query);
}
} catch (java.lang.Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public void run() {
while (ntrans-- > 0) {
int account = Benchmark.getRandomID(Benchmark.ACCOUNT);
int branch = Benchmark.getRandomID(Benchmark.BRANCH);
int teller = Benchmark.getRandomID(Benchmark.TELLER);
int delta = Benchmark.getRandomInt(0, 1000);
doOne(branch, teller, account, delta);
bench.incrementTransactionCount();
}
if (Benchmark.prepared_stmt) {
try {
if (pstmt1 != null) {
pstmt1.close();
}
if (pstmt2 != null) {
pstmt2.close();
}
if (pstmt3 != null) {
pstmt3.close();
}
if (pstmt4 != null) {
pstmt4.close();
}
if (pstmt5 != null) {
pstmt5.close();
}
} catch (java.lang.Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
Benchmark.connectClose(Conn);
Conn = null;
}
/*
* Executes a single TPC BM B transaction.
*/
int doOne(int bid, int tid, int aid, int delta) {
int aBalance = 0;
if (Conn == null) {
bench.incrementFailedTransactionCount();
return 0;
}
try {
if (Benchmark.prepared_stmt) {
pstmt1.setInt(1,delta);
pstmt1.setInt(2,aid);
pstmt1.executeUpdate();
pstmt1.clearWarnings();
pstmt2.setInt(1,aid);
ResultSet RS = pstmt2.executeQuery();
pstmt2.clearWarnings();
while (RS.next()) {
aBalance = RS.getInt(1);
}
pstmt3.setInt(1,delta);
pstmt3.setInt(2,tid);
pstmt3.executeUpdate();
pstmt3.clearWarnings();
pstmt4.setInt(1,delta);
pstmt4.setInt(2,bid);
pstmt4.executeUpdate();
pstmt4.clearWarnings();
pstmt5.setInt(1,tid);
pstmt5.setInt(2,bid);
pstmt5.setInt(3,aid);
pstmt5.setInt(4,delta);
pstmt5.executeUpdate();
pstmt5.clearWarnings();
} else {
Statement Stmt = Conn.createStatement();
String Query = "UPDATE accounts";
Query += " SET Abalance = Abalance + " + delta;
Query += " WHERE Aid = " + aid;
Stmt.executeUpdate(Query);
Stmt.clearWarnings();
Query = "SELECT Abalance";
Query += " FROM accounts";
Query += " WHERE Aid = " + aid;
ResultSet RS = Stmt.executeQuery(Query);
Stmt.clearWarnings();
while (RS.next()) {
aBalance = RS.getInt(1);
}
Query = "UPDATE tellers";
Query += " SET Tbalance = Tbalance + " + delta;
Query += " WHERE Tid = " + tid;
Stmt.executeUpdate(Query);
Stmt.clearWarnings();
Query = "UPDATE branches";
Query += " SET Bbalance = Bbalance + " + delta;
Query += " WHERE Bid = " + bid;
Stmt.executeUpdate(Query);
Stmt.clearWarnings();
Query = "INSERT INTO history(Tid, Bid, Aid, delta)";
Query += " VALUES (";
Query += tid + ",";
Query += bid + ",";
Query += aid + ",";
Query += delta + ")";
Stmt.executeUpdate(Query);
Stmt.clearWarnings();
Stmt.close();
}
if (Benchmark.transactions) {
Conn.commit();
}
return aBalance;
} catch (java.lang.Exception e) {
if (Benchmark.verbose) {
System.out.println("Transaction failed: "
+ e.getMessage());
e.printStackTrace();
}
bench.incrementFailedTransactionCount();
if (Benchmark.transactions) {
try {
Conn.rollback();
} catch (SQLException e1) {
}
}
}
return 0;
}
}

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,325 @@
package jsqlite;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Internal class implementing java.io.InputStream on
* SQLite 3.4.0 incremental blob I/O interface.
*/
class BlobR extends InputStream {
/**
* Blob instance
*/
private Blob blob;
/**
* Read position, file pointer.
*/
private int pos;
/**
* Contruct InputStream from blob instance.
*/
BlobR(Blob blob) {
this.blob = blob;
this.pos = 0;
}
/**
* Return number of available bytes for reading.
* @return available input bytes
*/
public int available() throws IOException {
int ret = blob.size - pos;
return (ret < 0) ? 0 : ret;
}
/**
* Mark method; dummy to satisfy InputStream class.
*/
public void mark(int limit) {
}
/**
* Reset method; dummy to satisfy InputStream class.
*/
public void reset() throws IOException {
}
/**
* Mark support; not for this class.
* @return always false
*/
public boolean markSupported() {
return false;
}
/**
* Close this blob InputStream.
*/
public void close() throws IOException {
blob.close();
blob = null;
pos = 0;
}
/**
* Skip over blob data.
*/
public long skip(long n) throws IOException {
long ret = pos + n;
if (ret < 0) {
ret = 0;
pos = 0;
} else if (ret > blob.size) {
ret = blob.size;
pos = blob.size;
} else {
pos = (int) ret;
}
return ret;
}
/**
* Read single byte from blob.
* @return byte read
*/
public int read() throws IOException {
byte b[] = new byte[1];
int n = blob.read(b, 0, pos, b.length);
if (n > 0) {
pos += n;
return b[0];
}
return -1;
}
/**
* Read byte array from blob.
* @param b byte array to be filled
* @return number of bytes read
*/
public int read(byte b[]) throws IOException {
int n = blob.read(b, 0, pos, b.length);
if (n > 0) {
pos += n;
return n;
}
return -1;
}
/**
* Read slice of byte array from blob.
* @param b byte array to be filled
* @param off offset into byte array
* @param len length to be read
* @return number of bytes read
*/
public int read(byte b[], int off, int len) throws IOException {
if (off + len > b.length) {
len = b.length - off;
}
if (len < 0) {
return -1;
}
if (len == 0) {
return 0;
}
int n = blob.read(b, off, pos, len);
if (n > 0) {
pos += n;
return n;
}
return -1;
}
}
/**
* Internal class implementing java.io.OutputStream on
* SQLite 3.4.0 incremental blob I/O interface.
*/
class BlobW extends OutputStream {
/**
* Blob instance
*/
private Blob blob;
/**
* Read position, file pointer.
*/
private int pos;
/**
* Contruct OutputStream from blob instance.
*/
BlobW(Blob blob) {
this.blob = blob;
this.pos = 0;
}
/**
* Flush blob; dummy to satisfy OutputStream class.
*/
public void flush() throws IOException {
}
/**
* Close this blob OutputStream.
*/
public void close() throws IOException {
blob.close();
blob = null;
pos = 0;
}
/**
* Write blob data.
* @param v byte to be written at current position.
*/
public void write(int v) throws IOException {
byte b[] = new byte[1];
b[0] = (byte) v;
pos += blob.write(b, 0, pos, 1);
}
/**
* Write blob data.
* @param b byte array to be written at current position.
*/
public void write(byte[] b) throws IOException {
if (b != null && b.length > 0) {
pos += blob.write(b, 0, pos, b.length);
}
}
/**
* Write blob data.
* @param b byte array to be written.
* @param off offset within byte array
* @param len length of data to be written
*/
public void write(byte[] b, int off, int len) throws IOException {
if (b != null) {
if (off + len > b.length) {
len = b.length - off;
}
if (len <= 0) {
return;
}
pos += blob.write(b, off, pos, len);
}
}
}
/**
* Class to represent SQLite3 3.4.0 incremental blob I/O interface.
*
* Note, that all native methods of this class are
* not synchronized, i.e. it is up to the caller
* to ensure that only one thread is in these
* methods at any one time.
*/
public class Blob {
/**
* Internal handle for the SQLite3 blob.
*/
private long handle = 0;
/**
* Cached size of blob, setup right after blob
* has been opened.
*/
protected int size = 0;
/**
* Return InputStream for this blob
* @return InputStream
*/
public InputStream getInputStream() {
return new BlobR(this);
}
/**
* Return OutputStream for this blob
* @return OutputStream
*/
public OutputStream getOutputStream() {
return new BlobW(this);
}
/**
* Close blob.
*/
public native void close();
/**
* Internal blob write method.
* @param b byte array to be written
* @param off offset into byte array
* @param pos offset into blob
* @param len length to be written
* @return number of bytes written to blob
*/
native int write(byte[] b, int off, int pos, int len) throws IOException;
/**
* Internal blob read method.
* @param b byte array to be written
* @param off offset into byte array
* @param pos offset into blob
* @param len length to be written
* @return number of bytes written to blob
*/
native int read(byte[] b, int off, int pos, int len) throws IOException;
/**
* Destructor for object.
*/
protected native void finalize();
/**
* Internal native initializer.
*/
private static native void internal_init();
static {
internal_init();
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,20 @@
package jsqlite;
/**
* Callback interface for SQLite's user defined busy handler.
*/
public interface BusyHandler {
/**
* Invoked when a table is locked by another process
* or thread. The method should return true for waiting
* until the table becomes unlocked, or false in order
* to abandon the action.<BR><BR>
*
* @param table the name of the locked table
* @param count number of times the table was locked
*/
public boolean busy(String table, int count);
}

Binary file not shown.

View File

@ -0,0 +1,68 @@
package jsqlite;
/**
* Callback interface for SQLite's query results.
* <BR><BR>
* Example:<BR>
*
* <PRE>
* class TableFmt implements SQLite.Callback {
* public void columns(String cols[]) {
* System.out.println("&lt;TH&gt;&lt;TR&gt;");
* for (int i = 0; i &lt; cols.length; i++) {
* System.out.println("&lt;TD&gt;" + cols[i] + "&lt;/TD&gt;");
* }
* System.out.println("&lt;/TR&gt;&lt;/TH&gt;");
* }
* public boolean newrow(String cols[]) {
* System.out.println("&lt;TR&gt;");
* for (int i = 0; i &lt; cols.length; i++) {
* System.out.println("&lt;TD&gt;" + cols[i] + "&lt;/TD&gt;");
* }
* System.out.println("&lt;/TR&gt;");
* return false;
* }
* }
* ...
* SQLite.Database db = new SQLite.Database();
* db.open("db", 0);
* System.out.println("&lt;TABLE&gt;");
* db.exec("select * from TEST", new TableFmt());
* System.out.println("&lt;/TABLE&gt;");
* ...
* </PRE>
*/
public interface Callback {
/**
* Reports column names of the query result.
* This method is invoked first (and once) when
* the SQLite engine returns the result set.<BR><BR>
*
* @param coldata string array holding the column names
*/
public void columns(String coldata[]);
/**
* Reports type names of the columns of the query result.
* This is available from SQLite 2.6.0 on and needs
* the PRAGMA show_datatypes to be turned on.<BR><BR>
*
* @param types string array holding column types
*/
public void types(String types[]);
/**
* Reports row data of the query result.
* This method is invoked for each row of the
* result set. If true is returned the running
* SQLite query is aborted.<BR><BR>
*
* @param rowdata string array holding the column values of the row
*/
public boolean newrow(String rowdata[]);
}

View File

@ -0,0 +1,145 @@
/* DO NOT EDIT */
package jsqlite;
/**
* Container for SQLite constants.
*/
public final class Constants {
/* Error code: 0 */
public static final int SQLITE_OK = 0;
/* Error code: 1 */
public static final int SQLITE_ERROR = 1;
/* Error code: 2 */
public static final int SQLITE_INTERNAL = 2;
/* Error code: 3 */
public static final int SQLITE_PERM = 3;
/* Error code: 4 */
public static final int SQLITE_ABORT = 4;
/* Error code: 5 */
public static final int SQLITE_BUSY = 5;
/* Error code: 6 */
public static final int SQLITE_LOCKED = 6;
/* Error code: 7 */
public static final int SQLITE_NOMEM = 7;
/* Error code: 8 */
public static final int SQLITE_READONLY = 8;
/* Error code: 9 */
public static final int SQLITE_INTERRUPT = 9;
/* Error code: 10 */
public static final int SQLITE_IOERR = 10;
/* Error code: 11 */
public static final int SQLITE_CORRUPT = 11;
/* Error code: 12 */
public static final int SQLITE_NOTFOUND = 12;
/* Error code: 13 */
public static final int SQLITE_FULL = 13;
/* Error code: 14 */
public static final int SQLITE_CANTOPEN = 14;
/* Error code: 15 */
public static final int SQLITE_PROTOCOL = 15;
/* Error code: 16 */
public static final int SQLITE_EMPTY = 16;
/* Error code: 17 */
public static final int SQLITE_SCHEMA = 17;
/* Error code: 18 */
public static final int SQLITE_TOOBIG = 18;
/* Error code: 19 */
public static final int SQLITE_CONSTRAINT = 19;
/* Error code: 20 */
public static final int SQLITE_MISMATCH = 20;
/* Error code: 21 */
public static final int SQLITE_MISUSE = 21;
/* Error code: 22 */
public static final int SQLITE_NOLFS = 22;
/* Error code: 23 */
public static final int SQLITE_AUTH = 23;
/* Error code: 24 */
public static final int SQLITE_FORMAT = 24;
/* Error code: 25 */
public static final int SQLITE_RANGE = 25;
/* Error code: 26 */
public static final int SQLITE_NOTADB = 26;
public static final int SQLITE_ROW = 100;
public static final int SQLITE_DONE = 101;
public static final int SQLITE_INTEGER = 1;
public static final int SQLITE_FLOAT = 2;
public static final int SQLITE_BLOB = 4;
public static final int SQLITE_NULL = 5;
public static final int SQLITE3_TEXT = 3;
public static final int SQLITE_NUMERIC = -1;
public static final int SQLITE_TEXT = 3;
public static final int SQLITE2_TEXT = -2;
public static final int SQLITE_ARGS = -3;
public static final int SQLITE_COPY = 0;
public static final int SQLITE_CREATE_INDEX = 1;
public static final int SQLITE_CREATE_TABLE = 2;
public static final int SQLITE_CREATE_TEMP_INDEX = 3;
public static final int SQLITE_CREATE_TEMP_TABLE = 4;
public static final int SQLITE_CREATE_TEMP_TRIGGER = 5;
public static final int SQLITE_CREATE_TEMP_VIEW = 6;
public static final int SQLITE_CREATE_TRIGGER = 7;
public static final int SQLITE_CREATE_VIEW = 8;
public static final int SQLITE_DELETE = 9;
public static final int SQLITE_DROP_INDEX = 10;
public static final int SQLITE_DROP_TABLE = 11;
public static final int SQLITE_DROP_TEMP_INDEX = 12;
public static final int SQLITE_DROP_TEMP_TABLE = 13;
public static final int SQLITE_DROP_TEMP_TRIGGER = 14;
public static final int SQLITE_DROP_TEMP_VIEW = 15;
public static final int SQLITE_DROP_TRIGGER = 16;
public static final int SQLITE_DROP_VIEW = 17;
public static final int SQLITE_INSERT = 18;
public static final int SQLITE_PRAGMA = 19;
public static final int SQLITE_READ = 20;
public static final int SQLITE_SELECT = 21;
public static final int SQLITE_TRANSACTION = 22;
public static final int SQLITE_UPDATE = 23;
public static final int SQLITE_ATTACH = 24;
public static final int SQLITE_DETACH = 25;
public static final int SQLITE_DENY = 1;
public static final int SQLITE_IGNORE = 2;
public static final int SQLITE_OPEN_AUTOPROXY = 0;
public static final int SQLITE_OPEN_CREATE = 4;
public static final int SQLITE_OPEN_DELETEONCLOSE = 8;
public static final int SQLITE_OPEN_EXCLUSIVE = 16;
public static final int SQLITE_OPEN_FULLMUTEX = 65536;
public static final int SQLITE_OPEN_MAIN_DB = 256;
public static final int SQLITE_OPEN_MAIN_JOURNAL = 2048;
public static final int SQLITE_OPEN_MASTER_JOURNAL = 16384;
public static final int SQLITE_OPEN_NOMUTEX = 32768;
public static final int SQLITE_OPEN_PRIVATECACHE = 262144;
public static final int SQLITE_OPEN_READONLY = 1;
public static final int SQLITE_OPEN_READWRITE = 2;
public static final int SQLITE_OPEN_SHAREDCACHE = 131072;
public static final int SQLITE_OPEN_SUBJOURNAL = 8192;
public static final int SQLITE_OPEN_TEMP_DB = 512;
public static final int SQLITE_OPEN_TEMP_JOURNAL = 4096;
public static final int SQLITE_OPEN_TRANSIENT_DB = 1024;
public static final int SQLITE_OPEN_URI = 0;
public static final int SQLITE_OPEN_WAL = 0;
public static final int SQLITE_STATUS_MALLOC_COUNT = 0;
public static final int SQLITE_STATUS_MALLOC_SIZE = 5;
public static final int SQLITE_STATUS_MEMORY_USED = 0;
public static final int SQLITE_STATUS_PAGECACHE_OVERFLOW = 2;
public static final int SQLITE_STATUS_PAGECACHE_SIZE = 7;
public static final int SQLITE_STATUS_PAGECACHE_USED = 1;
public static final int SQLITE_STATUS_PARSER_STACK = 6;
public static final int SQLITE_STATUS_SCRATCH_OVERFLOW = 4;
public static final int SQLITE_STATUS_SCRATCH_SIZE = 8;
public static final int SQLITE_STATUS_SCRATCH_USED = 3;
public static final int SQLITE_DBSTATUS_CACHE_HIT = 0;
public static final int SQLITE_DBSTATUS_CACHE_MISS = 0;
public static final int SQLITE_DBSTATUS_CACHE_USED = 0;
public static final int SQLITE_DBSTATUS_LOOKASIDE_HIT = 0;
public static final int SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE = 0;
public static final int SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL = 0;
public static final int SQLITE_DBSTATUS_LOOKASIDE_USED = 0;
public static final int SQLITE_DBSTATUS_SCHEMA_USED = 0;
public static final int SQLITE_DBSTATUS_STMT_USED = 0;
public static final int SQLITE_STMTSTATUS_FULLSCAN_STEP = 1;
public static final int SQLITE_STMTSTATUS_SORT = 2;
public static final int SQLITE_STMTSTATUS_AUTOINDEX = 0;
public static final int drv_minor = 20120209;
}

View File

@ -0,0 +1,960 @@
package jsqlite;
/**
* Main class wrapping an SQLite database.
*/
public class Database {
/**
* Internal handle for the native SQLite API.
*/
protected long handle = 0;
/**
* Internal last error code for exec() methods.
*/
protected int error_code = 0;
/**
* Open an SQLite database file.
*
* @param filename the name of the database file
* @param mode open mode (e.g. SQLITE_OPEN_READONLY)
*/
public void open(String filename, int mode) throws jsqlite.Exception {
if ((mode & 0200) != 0) {
mode = jsqlite.Constants.SQLITE_OPEN_READWRITE |
jsqlite.Constants.SQLITE_OPEN_CREATE;
} else if ((mode & 0400) != 0) {
mode = jsqlite.Constants.SQLITE_OPEN_READONLY;
}
synchronized(this) {
try {
_open4(filename, mode, null, false);
} catch (jsqlite.Exception se) {
throw se;
} catch (java.lang.OutOfMemoryError me) {
throw me;
} catch (Throwable t) {
_open(filename, mode);
}
}
}
/**
* Open an SQLite database file.
*
* @param filename the name of the database file
* @param mode open mode (e.g. SQLITE_OPEN_READONLY)
* @param vfs VFS name (for SQLite >= 3.5)
*/
public void open(String filename, int mode, String vfs)
throws jsqlite.Exception {
if ((mode & 0200) != 0) {
mode = jsqlite.Constants.SQLITE_OPEN_READWRITE |
jsqlite.Constants.SQLITE_OPEN_CREATE;
} else if ((mode & 0400) != 0) {
mode = jsqlite.Constants.SQLITE_OPEN_READONLY;
}
synchronized(this) {
try {
_open4(filename, mode, vfs, false);
} catch (jsqlite.Exception se) {
throw se;
} catch (java.lang.OutOfMemoryError me) {
throw me;
} catch (Throwable t) {
_open(filename, mode);
}
}
}
/**
* Open an SQLite database file.
*
* @param filename the name of the database file
* @param mode open mode (e.g. SQLITE_OPEN_READONLY)
* @param vfs VFS name (for SQLite >= 3.5)
* @param ver2 flag to force version on create (false = SQLite3, true = SQLite2)
*/
public void open(String filename, int mode, String vfs, boolean ver2)
throws jsqlite.Exception {
if ((mode & 0200) != 0) {
mode = jsqlite.Constants.SQLITE_OPEN_READWRITE |
jsqlite.Constants.SQLITE_OPEN_CREATE;
} else if ((mode & 0400) != 0) {
mode = jsqlite.Constants.SQLITE_OPEN_READONLY;
}
synchronized(this) {
try {
_open4(filename, mode, vfs, ver2);
} catch (jsqlite.Exception se) {
throw se;
} catch (java.lang.OutOfMemoryError me) {
throw me;
} catch (Throwable t) {
_open(filename, mode);
}
}
}
/*
* For backward compatibility to older sqlite.jar, sqlite_jni
*/
private native void _open(String filename, int mode)
throws jsqlite.Exception;
/*
* Newer full interface
*/
private native void _open4(String filename, int mode, String vfs,
boolean ver2)
throws jsqlite.Exception;
/**
* Open SQLite auxiliary database file for temporary
* tables.
*
* @param filename the name of the auxiliary file or null
*/
public void open_aux_file(String filename) throws jsqlite.Exception {
synchronized(this) {
_open_aux_file(filename);
}
}
private native void _open_aux_file(String filename)
throws jsqlite.Exception;
/**
* Destructor for object.
*/
protected void finalize() {
synchronized(this) {
_finalize();
}
}
private native void _finalize();
/**
* Close the underlying SQLite database file.
*/
public void close() throws jsqlite.Exception {
synchronized(this) {
_close();
}
}
private native void _close()
throws jsqlite.Exception;
/**
* Execute an SQL statement and invoke callback methods
* for each row of the result set.<P>
*
* It the method fails, an SQLite.Exception is thrown and
* an error code is set, which later can be retrieved by
* the last_error() method.
*
* @param sql the SQL statement to be executed
* @param cb the object implementing the callback methods
*/
public void exec(String sql, jsqlite.Callback cb) throws jsqlite.Exception {
synchronized(this) {
_exec(sql, cb);
}
}
private native void _exec(String sql, jsqlite.Callback cb)
throws jsqlite.Exception;
/**
* Execute an SQL statement and invoke callback methods
* for each row of the result set. Each '%q' or %Q in the
* statement string is substituted by its corresponding
* element in the argument vector.
* <BR><BR>
* Example:<BR>
* <PRE>
* String args[] = new String[1];
* args[0] = "tab%";
* db.exec("select * from sqlite_master where type like '%q'",
* null, args);
* </PRE>
*
* It the method fails, an SQLite.Exception is thrown and
* an error code is set, which later can be retrieved by
* the last_error() method.
*
* @param sql the SQL statement to be executed
* @param cb the object implementing the callback methods
* @param args arguments for the SQL statement, '%q' substitution
*/
public void exec(String sql, jsqlite.Callback cb,
String args[]) throws jsqlite.Exception {
synchronized(this) {
_exec(sql, cb, args);
}
}
private native void _exec(String sql, jsqlite.Callback cb, String args[])
throws jsqlite.Exception;
/**
* Return the row identifier of the last inserted
* row.
*/
public long last_insert_rowid() {
synchronized(this) {
return _last_insert_rowid();
}
}
private native long _last_insert_rowid();
/**
* Abort the current SQLite operation.
*/
public void interrupt() {
synchronized(this) {
_interrupt();
}
}
private native void _interrupt();
/**
* Return the number of changed rows for the last statement.
*/
public long changes() {
synchronized(this) {
return _changes();
}
}
private native long _changes();
/**
* Establish a busy callback method which gets called when
* an SQLite table is locked.
*
* @param bh the object implementing the busy callback method
*/
public void busy_handler(jsqlite.BusyHandler bh) {
synchronized(this) {
_busy_handler(bh);
}
}
private native void _busy_handler(jsqlite.BusyHandler bh);
/**
* Set the timeout for waiting for an SQLite table to become
* unlocked.
*
* @param ms number of millisecond to wait
*/
public void busy_timeout(int ms) {
synchronized(this) {
_busy_timeout(ms);
}
}
private native void _busy_timeout(int ms);
/**
* Convenience method to retrieve an entire result
* set into memory.
*
* @param sql the SQL statement to be executed
* @param maxrows the max. number of rows to retrieve
* @return result set
*/
public TableResult get_table(String sql, int maxrows)
throws jsqlite.Exception {
TableResult ret = new TableResult(maxrows);
if (!is3()) {
try {
exec(sql, ret);
} catch (jsqlite.Exception e) {
if (maxrows <= 0 || !ret.atmaxrows) {
throw e;
}
}
} else {
synchronized(this) {
/* only one statement !!! */
Vm vm = compile(sql);
set_last_error(vm.error_code);
if (ret.maxrows > 0) {
while (ret.nrows < ret.maxrows && vm.step(ret)) {
set_last_error(vm.error_code);
}
} else {
while (vm.step(ret)) {
set_last_error(vm.error_code);
}
}
vm.finalize();
}
}
return ret;
}
/**
* Convenience method to retrieve an entire result
* set into memory.
*
* @param sql the SQL statement to be executed
* @return result set
*/
public TableResult get_table(String sql) throws jsqlite.Exception {
return get_table(sql, 0);
}
/**
* Convenience method to retrieve an entire result
* set into memory.
*
* @param sql the SQL statement to be executed
* @param maxrows the max. number of rows to retrieve
* @param args arguments for the SQL statement, '%q' substitution
* @return result set
*/
public TableResult get_table(String sql, int maxrows, String args[])
throws jsqlite.Exception {
TableResult ret = new TableResult(maxrows);
if (!is3()) {
try {
exec(sql, ret, args);
} catch (jsqlite.Exception e) {
if (maxrows <= 0 || !ret.atmaxrows) {
throw e;
}
}
} else {
synchronized(this) {
/* only one statement !!! */
Vm vm = compile(sql, args);
set_last_error(vm.error_code);
if (ret.maxrows > 0) {
while (ret.nrows < ret.maxrows && vm.step(ret)) {
set_last_error(vm.error_code);
}
} else {
while (vm.step(ret)) {
set_last_error(vm.error_code);
}
}
vm.finalize();
}
}
return ret;
}
/**
* Convenience method to retrieve an entire result
* set into memory.
*
* @param sql the SQL statement to be executed
* @param args arguments for the SQL statement, '%q' substitution
* @return result set
*/
public TableResult get_table(String sql, String args[])
throws jsqlite.Exception {
return get_table(sql, 0, args);
}
/**
* Convenience method to retrieve an entire result
* set into memory.
*
* @param sql the SQL statement to be executed
* @param args arguments for the SQL statement, '%q' substitution
* @param tbl TableResult to receive result set
*/
public void get_table(String sql, String args[], TableResult tbl)
throws jsqlite.Exception {
tbl.clear();
if (!is3()) {
try {
exec(sql, tbl, args);
} catch (jsqlite.Exception e) {
if (tbl.maxrows <= 0 || !tbl.atmaxrows) {
throw e;
}
}
} else {
synchronized(this) {
/* only one statement !!! */
Vm vm = compile(sql, args);
if (tbl.maxrows > 0) {
while (tbl.nrows < tbl.maxrows && vm.step(tbl)) {
set_last_error(vm.error_code);
}
} else {
while (vm.step(tbl)) {
set_last_error(vm.error_code);
}
}
vm.finalize();
}
}
}
/**
* See if an SQL statement is complete.
* Returns true if the input string comprises
* one or more complete SQL statements.
*
* @param sql the SQL statement to be checked
*/
public synchronized static boolean complete(String sql) {
return _complete(sql);
}
private native static boolean _complete(String sql);
/**
* Return SQLite version number as string.
* Don't rely on this when both SQLite 2 and 3 are compiled
* into the native part. Use the class method in this case.
*/
public native static String version();
/**
* Return SQLite version number as string.
* If the database is not open, <tt>unknown</tt> is returned.
*/
public native String dbversion();
/**
* Create regular function.
*
* @param name the name of the new function
* @param nargs number of arguments to function
* @param f interface of function
*/
public void create_function(String name, int nargs, Function f) {
synchronized(this) {
_create_function(name, nargs, f);
}
}
private native void _create_function(String name, int nargs, Function f);
/**
* Create aggregate function.
*
* @param name the name of the new function
* @param nargs number of arguments to function
* @param f interface of function
*/
public void create_aggregate(String name, int nargs, Function f) {
synchronized(this) {
_create_aggregate(name, nargs, f);
}
}
private native void _create_aggregate(String name, int nargs, Function f);
/**
* Set function return type. Only available in SQLite 2.6.0 and
* above, otherwise a no-op.
*
* @param name the name of the function whose return type is to be set
* @param type return type code, e.g. jsqlite.Constants.SQLITE_NUMERIC
*/
public void function_type(String name, int type) {
synchronized(this) {
_function_type(name, type);
}
}
private native void _function_type(String name, int type);
/**
* Return the code of the last error occured in
* any of the exec() methods. The value is valid
* after an Exception has been reported by one of
* these methods. See the <A HREF="Constants.html">Constants</A>
* class for possible values.
*
* @return SQLite error code
*/
public int last_error() {
return error_code;
}
/**
* Internal: set error code.
* @param error_code new error code
*/
protected void set_last_error(int error_code) {
this.error_code = error_code;
}
/**
* Return last error message of SQLite3 engine.
*
* @return error string or null
*/
public String error_message() {
synchronized(this) {
return _errmsg();
}
}
private native String _errmsg();
/**
* Return error string given SQLite error code (SQLite2).
*
* @param error_code the error code
* @return error string
*/
public static native String error_string(int error_code);
/**
* Set character encoding.
* @param enc name of encoding
*/
public void set_encoding(String enc) throws jsqlite.Exception {
synchronized(this) {
_set_encoding(enc);
}
}
private native void _set_encoding(String enc)
throws jsqlite.Exception;
/**
* Set authorizer function. Only available in SQLite 2.7.6 and
* above, otherwise a no-op.
*
* @param auth the authorizer function
*/
public void set_authorizer(Authorizer auth) {
synchronized(this) {
_set_authorizer(auth);
}
}
private native void _set_authorizer(Authorizer auth);
/**
* Set trace function. Only available in SQLite 2.7.6 and above,
* otherwise a no-op.
*
* @param tr the trace function
*/
public void trace(Trace tr) {
synchronized(this) {
_trace(tr);
}
}
private native void _trace(Trace tr);
/**
* Initiate a database backup, SQLite 3.x only.
*
* @param dest destination database
* @param destName schema of destination database to be backed up
* @param srcName schema of source database
* @return Backup object to perform the backup operation
*/
public Backup backup(Database dest, String destName, String srcName)
throws jsqlite.Exception {
synchronized(this) {
Backup b = new Backup();
_backup(b, dest, destName, this, srcName);
return b;
}
}
private static native void _backup(Backup b, Database dest,
String destName, Database src,
String srcName)
throws jsqlite.Exception;
/**
* Set profile function. Only available in SQLite 3.6 and above,
* otherwise a no-op.
*
* @param pr the trace function
*/
public void profile(Profile pr) {
synchronized(this) {
_profile(pr);
}
}
private native void _profile(Profile pr);
/**
* Return information on SQLite runtime status.
* Only available in SQLite 3.6 and above,
* otherwise a no-op.
*
* @param op operation code
* @param info output buffer, must be able to hold two
* values (current/highwater)
* @param flag reset flag
* @return SQLite error code
*/
public synchronized static int status(int op, int info[], boolean flag) {
return _status(op, info, flag);
}
private native static int _status(int op, int info[], boolean flag);
/**
* Return information on SQLite connection status.
* Only available in SQLite 3.6 and above,
* otherwise a no-op.
*
* @param op operation code
* @param info output buffer, must be able to hold two
* values (current/highwater)
* @param flag reset flag
* @return SQLite error code
*/
public int db_status(int op, int info[], boolean flag) {
synchronized(this) {
return _db_status(op, info, flag);
}
}
private native int _db_status(int op, int info[], boolean flag);
/**
* Compile and return SQLite VM for SQL statement. Only available
* in SQLite 2.8.0 and above, otherwise a no-op.
*
* @param sql SQL statement to be compiled
* @return a Vm object
*/
public Vm compile(String sql) throws jsqlite.Exception {
synchronized(this) {
Vm vm = new Vm();
vm_compile(sql, vm);
return vm;
}
}
/**
* Compile and return SQLite VM for SQL statement. Only available
* in SQLite 3.0 and above, otherwise a no-op.
*
* @param sql SQL statement to be compiled
* @param args arguments for the SQL statement, '%q' substitution
* @return a Vm object
*/
public Vm compile(String sql, String args[]) throws jsqlite.Exception {
synchronized(this) {
Vm vm = new Vm();
vm_compile_args(sql, vm, args);
return vm;
}
}
/**
* Prepare and return SQLite3 statement for SQL. Only available
* in SQLite 3.0 and above, otherwise a no-op.
*
* @param sql SQL statement to be prepared
* @return a Stmt object
*/
public Stmt prepare(String sql) throws jsqlite.Exception {
synchronized(this) {
Stmt stmt = new Stmt();
stmt_prepare(sql, stmt);
return stmt;
}
}
/**
* Open an SQLite3 blob. Only available in SQLite 3.4.0 and above.
* @param db database name
* @param table table name
* @param column column name
* @param row row identifier
* @param rw if true, open for read-write, else read-only
* @return a Blob object
*/
public Blob open_blob(String db, String table, String column,
long row, boolean rw) throws jsqlite.Exception {
synchronized(this) {
Blob blob = new Blob();
_open_blob(db, table, column, row, rw, blob);
return blob;
}
}
/**
* Check type of open database.
* @return true if SQLite3 database
*/
public native boolean is3();
/**
* Internal compile method.
* @param sql SQL statement
* @param vm Vm object
*/
private native void vm_compile(String sql, Vm vm)
throws jsqlite.Exception;
/**
* Internal compile method, SQLite 3.0 only.
* @param sql SQL statement
* @param args arguments for the SQL statement, '%q' substitution
* @param vm Vm object
*/
private native void vm_compile_args(String sql, Vm vm, String args[])
throws jsqlite.Exception;
/**
* Internal SQLite3 prepare method.
* @param sql SQL statement
* @param stmt Stmt object
*/
private native void stmt_prepare(String sql, Stmt stmt)
throws jsqlite.Exception;
/**
* Internal SQLite open blob method.
* @param db database name
* @param table table name
* @param column column name
* @param row row identifier
* @param rw if true, open for read-write, else read-only
* @param blob Blob object
*/
private native void _open_blob(String db, String table, String column,
long row, boolean rw, Blob blob)
throws jsqlite.Exception;
/**
* Establish a progress callback method which gets called after
* N SQLite VM opcodes.
*
* @param n number of SQLite VM opcodes until callback is invoked
* @param p the object implementing the progress callback method
*/
public void progress_handler(int n, jsqlite.ProgressHandler p) {
synchronized(this) {
_progress_handler(n, p);
}
}
private native void _progress_handler(int n, jsqlite.ProgressHandler p);
/**
* Specify key for encrypted database. To be called
* right after open() on SQLite3 databases.
* Not available in public releases of SQLite.
*
* @param ekey the key as byte array
*/
public void key(byte[] ekey) throws jsqlite.Exception {
synchronized(this) {
_key(ekey);
}
}
/**
* Specify key for encrypted database. To be called
* right after open() on SQLite3 databases.
* Not available in public releases of SQLite.
*
* @param skey the key as String
*/
public void key(String skey) throws jsqlite.Exception {
synchronized(this) {
byte ekey[] = null;
if (skey != null && skey.length() > 0) {
ekey = new byte[skey.length()];
for (int i = 0; i< skey.length(); i++) {
char c = skey.charAt(i);
ekey[i] = (byte) ((c & 0xff) ^ (c >> 8));
}
}
_key(ekey);
}
}
private native void _key(byte[] ekey);
/**
* Change the key of a encrypted database. The
* SQLite3 database must have been open()ed.
* Not available in public releases of SQLite.
*
* @param ekey the key as byte array
*/
public void rekey(byte[] ekey) throws jsqlite.Exception {
synchronized(this) {
_rekey(ekey);
}
}
/**
* Change the key of a encrypted database. The
* SQLite3 database must have been open()ed.
* Not available in public releases of SQLite.
*
* @param skey the key as String
*/
public void rekey(String skey) throws jsqlite.Exception {
synchronized(this) {
byte ekey[] = null;
if (skey != null && skey.length() > 0) {
ekey = new byte[skey.length()];
for (int i = 0; i< skey.length(); i++) {
char c = skey.charAt(i);
ekey[i] = (byte) ((c & 0xff) ^ (c >> 8));
}
}
_rekey(ekey);
}
}
private native void _rekey(byte[] ekey);
/**
* Enable/disable shared cache mode (SQLite 3.x only).
*
* @param onoff boolean to enable or disable shared cache
* @return boolean when true, function supported/succeeded
*/
protected static native boolean _enable_shared_cache(boolean onoff);
/**
* Internal native initializer.
*/
private static native void internal_init();
/**
* Make long value from julian date for java.lang.Date
*
* @param d double value (julian date in SQLite3 format)
* @return long
*/
public static long long_from_julian(double d) {
d -= 2440587.5;
d *= 86400000.0;
return (long) d;
}
/**
* Make long value from julian date for java.lang.Date
*
* @param s string (double value) (julian date in SQLite3 format)
* @return long
*/
public static long long_from_julian(String s) throws jsqlite.Exception {
try {
double d = Double.valueOf(s).doubleValue();
return long_from_julian(d);
} catch (java.lang.Exception ee) {
throw new jsqlite.Exception("not a julian date: " + s + ": " + ee);
}
}
/**
* Make julian date value from java.lang.Date
*
* @param ms millisecond value of java.lang.Date
* @return double
*/
public static double julian_from_long(long ms) {
double adj = (ms < 0) ? 0 : 0.5;
double d = (ms + adj) / 86400000.0 + 2440587.5;
return d;
}
/**
* Static initializer to load the native part.
*/
static {
try {
System.loadLibrary("jsqlite");
} catch (Throwable t) {
System.err.println("Unable to load sqlite_jni: " + t);
}
/*
* Call native initializer functions now, since the
* native part could have been linked statically, i.e.
* the try/catch above would have failed in that case.
*/
try {
internal_init();
new FunctionContext();
} catch (java.lang.Exception e) {
}
}
}

Binary file not shown.

View File

@ -0,0 +1,18 @@
package jsqlite;
/**
* Class for SQLite related exceptions.
*/
public class Exception extends java.lang.Exception {
/**
* Construct a new SQLite exception.
*
* @param string error message
*/
public Exception(String string) {
super(string);
}
}

View File

@ -0,0 +1,59 @@
package jsqlite;
/**
* Callback interface for SQLite's user defined functions.
* Each callback method receives a
* <A HREF="FunctionContext.html">FunctionContext</A> object
* which is used to set the function result or error code.
* <BR><BR>
* Example:<BR>
*
* <PRE>
* class SinFunc implements SQLite.Function {
* public void function(SQLite.FunctionContext fc, String args[]) {
* try {
* Double d = new Double(args[0]);
* fc.set_result(Math.sin(d.doubleValue()));
* } catch (Exception e) {
* fc.set_error("sin(" + args[0] + "):" + e);
* }
* }
* ...
* }
* SQLite.Database db = new SQLite.Database();
* db.open("db", 0);
* db.create_function("sin", 1, SinFunc);
* ...
* db.exec("select sin(1.0) from test", null);
* </PRE>
*/
public interface Function {
/**
* Callback for regular function.
*
* @param fc function's context for reporting result
* @param args String array of arguments
*/
public void function(FunctionContext fc, String args[]);
/**
* Callback for one step in aggregate function.
*
* @param fc function's context for reporting result
* @param args String array of arguments
*/
public void step(FunctionContext fc, String args[]);
/**
* Callback for final step in aggregate function.
*
* @param fc function's context for reporting result
*/
public void last_step(FunctionContext fc);
}

View File

@ -0,0 +1,82 @@
package jsqlite;
/**
* Context for execution of SQLite's user defined functions.
* A reference to an instance of this class is passed to
* user defined functions.
*/
public class FunctionContext {
/**
* Internal handle for the native SQLite API.
*/
private long handle = 0;
/**
* Set function result from string.
*
* @param r result string
*/
public native void set_result(String r);
/**
* Set function result from integer.
*
* @param r result integer
*/
public native void set_result(int r);
/**
* Set function result from double.
*
* @param r result double
*/
public native void set_result(double r);
/**
* Set function result from error message.
*
* @param r result string (error message)
*/
public native void set_error(String r);
/**
* Set function result from byte array.
* Only provided by SQLite3 databases.
*
* @param r result byte array
*/
public native void set_result(byte[] r);
/**
* Set function result as empty blob given size.
* Only provided by SQLite3 databases.
*
* @param n size for empty blob
*/
public native void set_result_zeroblob(int n);
/**
* Retrieve number of rows for aggregate function.
*/
public native int count();
/**
* Internal native initializer.
*/
private static native void internal_init();
static {
internal_init();
}
}

View File

@ -0,0 +1,19 @@
package jsqlite;
/**
* Callback interface for SQLite's profile function.
*/
public interface Profile {
/**
* Callback to profile (ie log) one SQL statement
* with its estimated execution time.
*
* @param stmt SQL statement string
* @param est estimated execution time in milliseconds.
*/
public void profile(String stmt, long est);
}

View File

@ -0,0 +1,17 @@
package jsqlite;
/**
* Callback interface for SQLite's user defined progress handler.
*/
public interface ProgressHandler {
/**
* Invoked for N SQLite VM opcodes.
* The method should return true to continue the
* current query, or false in order
* to abandon the action.<BR><BR>
*/
public boolean progress();
}

View File

@ -0,0 +1,96 @@
package jsqlite;
import java.io.PrintStream;
import java.io.PrintWriter;
/**
* SQLite SQL dump utility.
*/
public class SQLDump implements Callback {
PrintWriter pw;
PrintWriter err;
Database db;
Shell s;
public SQLDump(PrintWriter pw, Database db) {
this.pw = pw;
this.err = this.pw;
this.db = db;
s = new Shell(this.pw, this.err);
s.mode = Shell.MODE_Insert;
s.db = db;
}
public SQLDump(PrintStream ps, Database db) {
this.pw = new PrintWriter(ps);
this.err = this.pw;
this.db = db;
s = new Shell(this.pw, this.err);
s.mode = Shell.MODE_Insert;
s.db = db;
}
public void dump() throws jsqlite.Exception {
pw.println("BEGIN TRANSACTION;");
db.exec("SELECT name, type, sql FROM sqlite_master " +
"WHERE type!='meta' AND sql NOT NULL " +
"ORDER BY substr(type,2,1), name", this);
pw.println("COMMIT;");
pw.flush();
}
public void columns(String col[]) {
/* Empty body to satisfy jsqlite.Callback interface. */
}
public void types(String args[]) {
/* Empty body to satisfy jsqlite.Callback interface. */
}
public boolean newrow(String args[]) {
if (args.length != 3) {
return true;
}
pw.println(args[2] + ";");
if (args[1].compareTo("table") == 0) {
s.mode = Shell.MODE_Insert;
s.set_table_name(args[0]);
String qargs[] = new String[1];
qargs[0] = args[0];
try {
if (s.db.is3()) {
TableResult t = null;
t = s.db.get_table("PRAGMA table_info('%q')", qargs);
String query;
if (t != null) {
StringBuffer sb = new StringBuffer();
String sep = "";
sb.append("SELECT ");
for (int i = 0; i < t.nrows; i++) {
String col = ((String[]) t.rows.elementAt(i))[1];
sb.append(sep + "quote(" +
Shell.sql_quote_dbl(col) + ")");
sep = ",";
}
sb.append(" from '%q'");
query = sb.toString();
s.mode = Shell.MODE_Insert2;
} else {
query = "SELECT * from '%q'";
}
s.db.exec(query, s, qargs);
pw.flush();
} else {
s.db.exec("SELECT * from '%q'", s, qargs);
pw.flush();
}
} catch (Exception e) {
return true;
}
}
s.mode = Shell.MODE_Line;
return false;
}
}

View File

@ -0,0 +1,49 @@
package jsqlite;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* SQLite SQL restore utility.
*/
public class SQLRestore {
BufferedReader is;
Database db;
public SQLRestore(InputStream is, Database db) {
this.is = new BufferedReader(new InputStreamReader(is));
this.db = db;
}
public void restore() throws jsqlite.Exception {
String line = null, sql = null;
while (true) {
try {
line = is.readLine();
} catch (EOFException e) {
line = null;
} catch (IOException e) {
throw new jsqlite.Exception("I/O error: " + e);
}
if (line == null) {
break;
}
if (sql == null) {
sql = line;
} else {
sql = sql + " " + line;
}
if (Database.complete(sql)) {
db.exec(sql, null);
sql = null;
}
}
if (sql != null) {
throw new jsqlite.Exception("Incomplete SQL: " + sql);
}
}
}

View File

@ -0,0 +1,698 @@
package jsqlite;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* SQLite command line shell. This is a partial reimplementation
* of sqlite/src/shell.c and can be invoked by:<P>
*
* <verb>
* java jsqlite.Shell [OPTIONS] database [SHELLCMD]
* or
* java -jar sqlite.jar [OPTIONS] database [SHELLCMD]
* </verb>
*/
public class Shell implements Callback {
Database db;
boolean echo;
int count;
int mode;
boolean showHeader;
String tableName;
String sep;
String cols[];
int colwidth[];
String destTable;
PrintWriter pw;
PrintWriter err;
static final int MODE_Line = 0;
static final int MODE_Column = 1;
static final int MODE_List = 2;
static final int MODE_Semi = 3;
static final int MODE_Html = 4;
static final int MODE_Insert = 5;
static final int MODE_Insert2 = 6;
public Shell(PrintWriter pw, PrintWriter err) {
this.pw = pw;
this.err = err;
}
public Shell(PrintStream ps, PrintStream errs) {
pw = new PrintWriter(ps);
err = new PrintWriter(errs);
}
protected Object clone() {
Shell s = new Shell(this.pw, this.err);
s.db = db;
s.echo = echo;
s.mode = mode;
s.count = 0;
s.showHeader = showHeader;
s.tableName = tableName;
s.sep = sep;
s.colwidth = colwidth;
return s;
}
static public String sql_quote_dbl(String str) {
if (str == null) {
return "NULL";
}
int i, single = 0, dbl = 0;
for (i = 0; i < str.length(); i++) {
if (str.charAt(i) == '\'') {
single++;
} else if (str.charAt(i) == '"') {
dbl++;
}
}
if (dbl == 0) {
return "\"" + str + "\"";
}
StringBuffer sb = new StringBuffer("\"");
for (i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '"') {
sb.append("\"\"");
} else {
sb.append(c);
}
}
return sb.toString();
}
static public String sql_quote(String str) {
if (str == null) {
return "NULL";
}
int i, single = 0, dbl = 0;
for (i = 0; i < str.length(); i++) {
if (str.charAt(i) == '\'') {
single++;
} else if (str.charAt(i) == '"') {
dbl++;
}
}
if (single == 0) {
return "'" + str + "'";
}
if (dbl == 0) {
return "\"" + str + "\"";
}
StringBuffer sb = new StringBuffer("'");
for (i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '\'') {
sb.append("''");
} else {
sb.append(c);
}
}
return sb.toString();
}
static String html_quote(String str) {
if (str == null) {
return "NULL";
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '<') {
sb.append("&lt;");
} else if (c == '>') {
sb.append("&gt;");
} else if (c == '&') {
sb.append("&amp;");
} else {
int x = c;
if (x < 32 || x > 127) {
sb.append("&#" + x + ";");
} else {
sb.append(c);
}
}
}
return sb.toString();
}
static boolean is_numeric(String str) {
try {
Double d = Double.valueOf(str);
} catch (java.lang.Exception e) {
return false;
}
return true;
}
void set_table_name(String str) {
if (str == null) {
tableName = "";
return;
}
if (db.is3()) {
tableName = Shell.sql_quote_dbl(str);
} else {
tableName = Shell.sql_quote(str);
}
}
public void columns(String args[]) {
cols = args;
}
public void types(String args[]) {
/* Empty body to satisfy jsqlite.Callback interface. */
}
public boolean newrow(String args[]) {
int i;
String tname;
switch (mode) {
case Shell.MODE_Line:
if (args.length == 0) {
break;
}
if (count++ > 0) {
pw.println("");
}
for (i = 0; i < args.length; i++) {
pw.println(cols[i] + " = " +
args[i] == null ? "NULL" : args[i]);
}
break;
case Shell.MODE_Column:
String csep = "";
if (count++ == 0) {
colwidth = new int[args.length];
for (i = 0; i < args.length; i++) {
int w;
w = cols[i].length();
if (w < 10) {
w = 10;
}
colwidth[i] = w;
if (showHeader) {
pw.print(csep + cols[i]);
csep = " ";
}
}
if (showHeader) {
pw.println("");
}
}
if (args.length == 0) {
break;
}
csep = "";
for (i = 0; i < args.length; i++) {
pw.print(csep + (args[i] == null ? "NULL" : args[i]));
csep = " ";
}
pw.println("");
break;
case Shell.MODE_Semi:
case Shell.MODE_List:
if (count++ == 0 && showHeader) {
for (i = 0; i < args.length; i++) {
pw.print(cols[i] +
(i == args.length - 1 ? "\n" : sep));
}
}
if (args.length == 0) {
break;
}
for (i = 0; i < args.length; i++) {
pw.print(args[i] == null ? "NULL" : args[i]);
if (mode == Shell.MODE_Semi) {
pw.print(";");
} else if (i < args.length - 1) {
pw.print(sep);
}
}
pw.println("");
break;
case MODE_Html:
if (count++ == 0 && showHeader) {
pw.print("<TR>");
for (i = 0; i < args.length; i++) {
pw.print("<TH>" + html_quote(cols[i]) + "</TH>");
}
pw.println("</TR>");
}
if (args.length == 0) {
break;
}
pw.print("<TR>");
for (i = 0; i < args.length; i++) {
pw.print("<TD>" + html_quote(args[i]) + "</TD>");
}
pw.println("</TR>");
break;
case MODE_Insert:
if (args.length == 0) {
break;
}
tname = tableName;
if (destTable != null) {
tname = destTable;
}
pw.print("INSERT INTO " + tname + " VALUES(");
for (i = 0; i < args.length; i++) {
String tsep = i > 0 ? "," : "";
if (args[i] == null) {
pw.print(tsep + "NULL");
} else if (is_numeric(args[i])) {
pw.print(tsep + args[i]);
} else {
pw.print(tsep + sql_quote(args[i]));
}
}
pw.println(");");
break;
case MODE_Insert2:
if (args.length == 0) {
break;
}
tname = tableName;
if (destTable != null) {
tname = destTable;
}
pw.print("INSERT INTO " + tname + " VALUES(");
for (i = 0; i < args.length; i++) {
String tsep = i > 0 ? "," : "";
pw.print(tsep + args[i]);
}
pw.println(");");
break;
}
return false;
}
void do_meta(String line) {
StringTokenizer st = new StringTokenizer(line.toLowerCase());
int n = st.countTokens();
if (n <= 0) {
return;
}
String cmd = st.nextToken();
String args[] = new String[n - 1];
int i = 0;
while (st.hasMoreTokens()) {
args[i] = st.nextToken();
++i;
}
if (cmd.compareTo(".dump") == 0) {
new DBDump(this, args);
return;
}
if (cmd.compareTo(".echo") == 0) {
if (args.length > 0 &&
(args[0].startsWith("y") || args[0].startsWith("on"))) {
echo = true;
}
return;
}
if (cmd.compareTo(".exit") == 0) {
try {
db.close();
} catch (Exception e) {
}
System.exit(0);
}
if (cmd.compareTo(".header") == 0) {
if (args.length > 0 &&
(args[0].startsWith("y") || args[0].startsWith("on"))) {
showHeader = true;
}
return;
}
if (cmd.compareTo(".help") == 0) {
pw.println(".dump ?TABLE? ... Dump database in text fmt");
pw.println(".echo ON|OFF Command echo on or off");
pw.println(".enc ?NAME? Change encoding");
pw.println(".exit Exit program");
pw.println(".header ON|OFF Display headers on or off");
pw.println(".help This message");
pw.println(".mode MODE Set output mode to\n" +
" line, column, insert\n" +
" list, or html");
pw.println(".mode insert TABLE Generate SQL insert stmts");
pw.println(".schema ?PATTERN? List table schema");
pw.println(".separator STRING Set separator string");
pw.println(".tables ?PATTERN? List table names");
return;
}
if (cmd.compareTo(".mode") == 0) {
if (args.length > 0) {
if (args[0].compareTo("line") == 0) {
mode = Shell.MODE_Line;
} else if (args[0].compareTo("column") == 0) {
mode = Shell.MODE_Column;
} else if (args[0].compareTo("list") == 0) {
mode = Shell.MODE_List;
} else if (args[0].compareTo("html") == 0) {
mode = Shell.MODE_Html;
} else if (args[0].compareTo("insert") == 0) {
mode = Shell.MODE_Insert;
if (args.length > 1) {
destTable = args[1];
}
}
}
return;
}
if (cmd.compareTo(".separator") == 0) {
if (args.length > 0) {
sep = args[0];
}
return;
}
if (cmd.compareTo(".tables") == 0) {
TableResult t = null;
if (args.length > 0) {
try {
String qarg[] = new String[1];
qarg[0] = args[0];
t = db.get_table("SELECT name FROM sqlite_master " +
"WHERE type='table' AND " +
"name LIKE '%%%q%%' " +
"ORDER BY name", qarg);
} catch (Exception e) {
err.println("SQL Error: " + e);
err.flush();
}
} else {
try {
t = db.get_table("SELECT name FROM sqlite_master " +
"WHERE type='table' ORDER BY name");
} catch (Exception e) {
err.println("SQL Error: " + e);
err.flush();
}
}
if (t != null) {
for (i = 0; i < t.nrows; i++) {
String tab = ((String[]) t.rows.elementAt(i))[0];
if (tab != null) {
pw.println(tab);
}
}
}
return;
}
if (cmd.compareTo(".schema") == 0) {
if (args.length > 0) {
try {
String qarg[] = new String[1];
qarg[0] = args[0];
db.exec("SELECT sql FROM sqlite_master " +
"WHERE type!='meta' AND " +
"name LIKE '%%%q%%' AND " +
"sql NOTNULL " +
"ORDER BY type DESC, name",
this, qarg);
} catch (Exception e) {
err.println("SQL Error: " + e);
err.flush();
}
} else {
try {
db.exec("SELECT sql FROM sqlite_master " +
"WHERE type!='meta' AND " +
"sql NOTNULL " +
"ORDER BY tbl_name, type DESC, name",
this);
} catch (Exception e) {
err.println("SQL Error: " + e);
err.flush();
}
}
return;
}
if (cmd.compareTo(".enc") == 0) {
try {
db.set_encoding(args.length > 0 ? args[0] : null);
} catch (Exception e) {
err.println("" + e);
err.flush();
}
return;
}
if (cmd.compareTo(".rekey") == 0) {
try {
db.rekey(args.length > 0 ? args[0] : null);
} catch (Exception e) {
err.println("" + e);
err.flush();
}
return;
}
err.println("Unknown command '" + cmd + "'");
err.flush();
}
String read_line(BufferedReader is, String prompt) {
try {
if (prompt != null) {
pw.print(prompt);
pw.flush();
}
String line = is.readLine();
return line;
} catch (IOException e) {
return null;
}
}
void do_input(BufferedReader is) {
String line, sql = null;
String prompt = "SQLITE> ";
while ((line = read_line(is, prompt)) != null) {
if (echo) {
pw.println(line);
}
if (line.length() > 0 && line.charAt(0) == '.') {
do_meta(line);
} else {
if (sql == null) {
sql = line;
} else {
sql = sql + " " + line;
}
if (Database.complete(sql)) {
try {
db.exec(sql, this);
} catch (Exception e) {
if (!echo) {
err.println(sql);
}
err.println("SQL Error: " + e);
err.flush();
}
sql = null;
prompt = "SQLITE> ";
} else {
prompt = "SQLITE? ";
}
}
pw.flush();
}
if (sql != null) {
err.println("Incomplete SQL: " + sql);
err.flush();
}
}
void do_cmd(String sql) {
if (db == null) {
return;
}
if (sql.length() > 0 && sql.charAt(0) == '.') {
do_meta(sql);
} else {
try {
db.exec(sql, this);
} catch (Exception e) {
err.println("SQL Error: " + e);
err.flush();
}
}
}
public static void main(String args[]) {
String key = null;
Shell s = new Shell(System.out, System.err);
s.mode = Shell.MODE_List;
s.sep = "|";
s.showHeader = false;
s.db = new Database();
String dbname = null, sql = null;
for (int i = 0; i < args.length; i++) {
if(args[i].compareTo("-html") ==0) {
s.mode = Shell.MODE_Html;
} else if (args[i].compareTo("-list") == 0) {
s.mode = Shell.MODE_List;
} else if (args[i].compareTo("-line") == 0) {
s.mode = Shell.MODE_Line;
} else if (i < args.length - 1 &&
args[i].compareTo("-separator") == 0) {
++i;
s.sep = args[i];
} else if (args[i].compareTo("-header") == 0) {
s.showHeader = true;
} else if (args[i].compareTo("-noheader") == 0) {
s.showHeader = false;
} else if (args[i].compareTo("-echo") == 0) {
s.echo = true;
} else if (args[i].compareTo("-key") == 0) {
++i;
key = args[i];
} else if (dbname == null) {
dbname = args[i];
} else if (sql == null) {
sql = args[i];
} else {
System.err.println("Arguments: ?OPTIONS? FILENAME ?SQL?");
System.exit(1);
}
}
if (dbname == null) {
System.err.println("No database file given");
System.exit(1);
}
try {
s.db.open(dbname, jsqlite.Constants.SQLITE_OPEN_READWRITE |
jsqlite.Constants.SQLITE_OPEN_CREATE);
} catch (Exception e) {
System.err.println("Unable to open database: " + e);
System.exit(1);
}
if (key != null) {
try {
s.db.key(key);
} catch (Exception e) {
System.err.println("Unable to set key: " + e);
System.exit(1);
}
}
if (sql != null) {
s.do_cmd(sql);
s.pw.flush();
} else {
BufferedReader is =
new BufferedReader(new InputStreamReader(System.in));
s.do_input(is);
s.pw.flush();
}
try {
s.db.close();
} catch (Exception ee) {
}
}
}
/**
* Internal class for dumping an entire database.
* It contains a special callback interface to traverse the
* tables of the current database and output create SQL statements
* and for the data insert SQL statements.
*/
class DBDump implements Callback {
Shell s;
DBDump(Shell s, String tables[]) {
this.s = s;
s.pw.println("BEGIN TRANSACTION;");
if (tables == null || tables.length == 0) {
try {
s.db.exec("SELECT name, type, sql FROM sqlite_master " +
"WHERE type!='meta' AND sql NOT NULL " +
"ORDER BY substr(type,2,1), name", this);
} catch (Exception e) {
s.err.println("SQL Error: " + e);
s.err.flush();
}
} else {
String arg[] = new String[1];
for (int i = 0; i < tables.length; i++) {
arg[0] = tables[i];
try {
s.db.exec("SELECT name, type, sql FROM sqlite_master " +
"WHERE tbl_name LIKE '%q' AND type!='meta' " +
" AND sql NOT NULL " +
" ORDER BY substr(type,2,1), name",
this, arg);
} catch (Exception e) {
s.err.println("SQL Error: " + e);
s.err.flush();
}
}
}
s.pw.println("COMMIT;");
}
public void columns(String col[]) {
/* Empty body to satisfy jsqlite.Callback interface. */
}
public void types(String args[]) {
/* Empty body to satisfy jsqlite.Callback interface. */
}
public boolean newrow(String args[]) {
if (args.length != 3) {
return true;
}
s.pw.println(args[2] + ";");
if (args[1].compareTo("table") == 0) {
Shell s2 = (Shell) s.clone();
s2.mode = Shell.MODE_Insert;
s2.set_table_name(args[0]);
String qargs[] = new String[1];
qargs[0] = args[0];
try {
if (s2.db.is3()) {
TableResult t = null;
t = s2.db.get_table("PRAGMA table_info('%q')", qargs);
String query;
if (t != null) {
StringBuffer sb = new StringBuffer();
String sep = "";
sb.append("SELECT ");
for (int i = 0; i < t.nrows; i++) {
String col = ((String[]) t.rows.elementAt(i))[1];
sb.append(sep + "quote(" +
Shell.sql_quote_dbl(col) + ")");
sep = ",";
}
sb.append(" from '%q'");
query = sb.toString();
s2.mode = Shell.MODE_Insert2;
} else {
query = "SELECT * from '%q'";
}
s2.db.exec(query, s2, qargs);
} else {
s2.db.exec("SELECT * from '%q'", s2, qargs);
}
} catch (Exception e) {
s.err.println("SQL Error: " + e);
s.err.flush();
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,305 @@
package jsqlite;
/**
* Class to represent compiled SQLite3 statement.
*
* Note, that all native methods of this class are
* not synchronized, i.e. it is up to the caller
* to ensure that only one thread is in these
* methods at any one time.
*/
public class Stmt {
/**
* Internal handle for the SQLite3 statement.
*/
private long handle = 0;
/**
* Internal last error code for prepare()/step() methods.
*/
protected int error_code = 0;
/**
* Prepare the next SQL statement for the Stmt instance.
* @return true when the next piece of the SQL statement sequence
* has been prepared, false on end of statement sequence.
*/
public native boolean prepare() throws jsqlite.Exception;
/**
* Perform one step of compiled SQLite3 statement.
*
* Example:<BR>
* <PRE>
* ...
* try {
* Stmt s = db.prepare("select * from x; select * from y;");
* s.bind(...);
* ...
* s.bind(...);
* while (s.step(cb)) {
* Object o = s.value(...);
* ...
* }
* // s.reset() for re-execution or
* // s.prepare() for the next piece of SQL
* while (s.prepare()) {
* s.bind(...);
* ...
* s.bind(...);
* while (s.step(cb)) {
* Object o = s.value(...);
* ...
* }
* }
* } catch (jsqlite.Exception e) {
* s.close();
* }
* </PRE>
*
* @return true when row data is available, false on end
* of result set.
*/
public native boolean step() throws jsqlite.Exception;
/**
* Close the compiled SQLite3 statement.
*/
public native void close() throws jsqlite.Exception;
/**
* Reset the compiled SQLite3 statement without
* clearing parameter bindings.
*/
public native void reset() throws jsqlite.Exception;
/**
* Clear all bound parameters of the compiled SQLite3 statement.
*/
public native void clear_bindings() throws jsqlite.Exception;
/**
* Bind positional integer value to compiled SQLite3 statement.
* @param pos parameter index, 1-based
* @param value value of parameter
*/
public native void bind(int pos, int value) throws jsqlite.Exception;
/**
* Bind positional long value to compiled SQLite3 statement.
* @param pos parameter index, 1-based
* @param value value of parameter
*/
public native void bind(int pos, long value) throws jsqlite.Exception;
/**
* Bind positional double value to compiled SQLite3 statement.
* @param pos parameter index, 1-based
* @param value value of parameter
*/
public native void bind(int pos, double value) throws jsqlite.Exception;
/**
* Bind positional byte array to compiled SQLite3 statement.
* @param pos parameter index, 1-based
* @param value value of parameter, may be null
*/
public native void bind(int pos, byte[] value) throws jsqlite.Exception;
/**
* Bind positional String to compiled SQLite3 statement.
* @param pos parameter index, 1-based
* @param value value of parameter, may be null
*/
public native void bind(int pos, String value) throws jsqlite.Exception;
/**
* Bind positional SQL null to compiled SQLite3 statement.
* @param pos parameter index, 1-based
*/
public native void bind(int pos) throws jsqlite.Exception;
/**
* Bind positional zero'ed blob to compiled SQLite3 statement.
* @param pos parameter index, 1-based
* @param length byte size of zero blob
*/
public native void bind_zeroblob(int pos, int length)
throws jsqlite.Exception;
/**
* Return number of parameters in compiled SQLite3 statement.
* @return int number of parameters
*/
public native int bind_parameter_count() throws jsqlite.Exception;
/**
* Return name of parameter in compiled SQLite3 statement.
* @param pos parameter index, 1-based
* @return String parameter name
*/
public native String bind_parameter_name(int pos) throws jsqlite.Exception;
/**
* Return index of named parameter in compiled SQLite3 statement.
* @param name of parameter
* @return int index of parameter, 1-based
*/
public native int bind_parameter_index(String name)
throws jsqlite.Exception;
/**
* Retrieve integer column from exec'ed SQLite3 statement.
* @param col column number, 0-based
* @return int column value
*/
public native int column_int(int col) throws jsqlite.Exception;
/**
* Retrieve long column from exec'ed SQLite3 statement.
* @param col column number, 0-based
* @return long column value
*/
public native long column_long(int col) throws jsqlite.Exception;
/**
* Retrieve double column from exec'ed SQLite3 statement.
* @param col column number, 0-based
* @return double column value
*/
public native double column_double(int col) throws jsqlite.Exception;
/**
* Retrieve blob column from exec'ed SQLite3 statement.
* @param col column number, 0-based
* @return byte[] column value
*/
public native byte[] column_bytes(int col) throws jsqlite.Exception;
/**
* Retrieve string column from exec'ed SQLite3 statement.
* @param col column number, 0-based
* @return String column value
*/
public native String column_string(int col) throws jsqlite.Exception;
/**
* Retrieve column type from exec'ed SQLite3 statement.
* @param col column number, 0-based
* @return column type code, e.g. jsqlite.Constants.SQLITE_INTEGER
*/
public native int column_type(int col) throws jsqlite.Exception;
/**
* Retrieve number of columns of exec'ed SQLite3 statement.
* @return int number of columns
*/
public native int column_count() throws jsqlite.Exception;
/**
* Retrieve column data as object from exec'ed SQLite3 statement.
* @param col column number, 0-based
* @return Object or null
*/
public Object column(int col) throws jsqlite.Exception {
switch (column_type(col)) {
case Constants.SQLITE_INTEGER:
return new Long(column_long(col));
case Constants.SQLITE_FLOAT:
return new Double(column_double(col));
case Constants.SQLITE_BLOB:
return column_bytes(col);
case Constants.SQLITE3_TEXT:
return column_string(col);
}
return null;
}
/**
* Return table name of column of SQLite3 statement.
* @param col column number, 0-based
* @return String or null
*/
public native String column_table_name(int col) throws jsqlite.Exception;
/**
* Return database name of column of SQLite3 statement.
* @param col column number, 0-based
* @return String or null
*/
public native String column_database_name(int col) throws jsqlite.Exception;
/**
* Return declared column type of SQLite3 statement.
* @param col column number, 0-based
* @return String or null
*/
public native String column_decltype(int col) throws jsqlite.Exception;
/**
* Return column name of column of SQLite3 statement.
* @param col column number, 0-based
* @return String or null
*/
public native String column_name(int col) throws jsqlite.Exception;
/**
* Return origin column name of column of SQLite3 statement.
* @param col column number, 0-based
* @return String or null
*/
public native String column_origin_name(int col) throws jsqlite.Exception;
/**
* Return statement status information.
* @param op which counter to report
* @param flg reset flag
* @return counter
*/
public native int status(int op, boolean flg);
/**
* Destructor for object.
*/
protected native void finalize();
/**
* Internal native initializer.
*/
private static native void internal_init();
static {
internal_init();
}
}

View File

@ -0,0 +1,244 @@
package jsqlite;
/**
* String encoder/decoder for SQLite.
*
* This module was kindly donated by Eric van der Maarel of Nedap N.V.
*
* This encoder was implemented based on an original idea from an anonymous
* author in the source code of the SQLite distribution.
* I feel obliged to provide a quote from the original C-source code:
*
* "The author disclaims copyright to this source code. In place of
* a legal notice, here is a blessing:
*
* May you do good and not evil.
* May you find forgiveness for yourself and forgive others.
* May you share freely, never taking more than you give."
*
*/
public class StringEncoder {
/**
* Encodes the given byte array into a string that can be used by
* the SQLite database. The database cannot handle null (0x00) and
* the character '\'' (0x27). The encoding consists of escaping
* these characters with a reserved character (0x01). The escaping
* is applied after determining and applying a shift that minimizes
* the number of escapes required.
* With this encoding the data of original size n is increased to a
* maximum of 1+(n*257)/254.
* For sufficiently large n the overhead is thus less than 1.2%.
* @param a the byte array to be encoded. A null reference is handled as
* an empty array.
* @return the encoded bytes as a string. When an empty array is
* provided a string of length 1 is returned, the value of
* which is bogus.
* When decoded with this class' <code>decode</code> method
* a string of size 1 will return an empty byte array.
*/
public static String encode(byte[] a) {
// check input
if (a == null || a.length == 0) {
// bogus shift, no data
return "x";
}
// determine count
int[] cnt = new int[256];
for (int i = 0 ; i < a.length; i++) {
cnt[a[i] & 0xff]++;
}
// determine shift for minimum number of escapes
int shift = 1;
int nEscapes = a.length;
for (int i = 1; i < 256; i++) {
if (i == '\'') {
continue;
}
int sum = cnt[i] + cnt[(i + 1) & 0xff] + cnt[(i + '\'') & 0xff];
if (sum < nEscapes) {
nEscapes = sum;
shift = i;
if (nEscapes == 0) {
// cannot become smaller
break;
}
}
}
// construct encoded output
int outLen = a.length + nEscapes + 1;
StringBuffer out = new StringBuffer(outLen);
out.append((char)shift);
for (int i = 0; i < a.length; i++) {
// apply shift
char c = (char)((a[i] - shift)&0xff);
// insert escapes
if (c == 0) { // forbidden
out.append((char)1);
out.append((char)1);
} else if (c == 1) { // escape character
out.append((char)1);
out.append((char)2);
} else if (c == '\'') { // forbidden
out.append((char)1);
out.append((char)3);
} else {
out.append(c);
}
}
return out.toString();
}
/**
* Decodes the given string that is assumed to be a valid encoding
* of a byte array. Typically the given string is generated by
* this class' <code>encode</code> method.
* @param s the given string encoding.
* @return the byte array obtained from the decoding.
* @throws IllegalArgumentException when the string given is not
* a valid encoded string for this encoder.
*/
public static byte[] decode(String s) {
char[] a = s.toCharArray();
if (a.length > 2 && a[0] == 'X' &&
a[1] == '\'' && a[a.length-1] == '\'') {
// SQLite3 BLOB syntax
byte[] result = new byte[(a.length-3)/2];
for (int i = 2, k = 0; i < a.length - 1; i += 2, k++) {
byte tmp;
switch (a[i]) {
case '0': tmp = 0; break;
case '1': tmp = 1; break;
case '2': tmp = 2; break;
case '3': tmp = 3; break;
case '4': tmp = 4; break;
case '5': tmp = 5; break;
case '6': tmp = 6; break;
case '7': tmp = 7; break;
case '8': tmp = 8; break;
case '9': tmp = 9; break;
case 'A':
case 'a': tmp = 10; break;
case 'B':
case 'b': tmp = 11; break;
case 'C':
case 'c': tmp = 12; break;
case 'D':
case 'd': tmp = 13; break;
case 'E':
case 'e': tmp = 14; break;
case 'F':
case 'f': tmp = 15; break;
default: tmp = 0; break;
}
result[k] = (byte) (tmp << 4);
switch (a[i+1]) {
case '0': tmp = 0; break;
case '1': tmp = 1; break;
case '2': tmp = 2; break;
case '3': tmp = 3; break;
case '4': tmp = 4; break;
case '5': tmp = 5; break;
case '6': tmp = 6; break;
case '7': tmp = 7; break;
case '8': tmp = 8; break;
case '9': tmp = 9; break;
case 'A':
case 'a': tmp = 10; break;
case 'B':
case 'b': tmp = 11; break;
case 'C':
case 'c': tmp = 12; break;
case 'D':
case 'd': tmp = 13; break;
case 'E':
case 'e': tmp = 14; break;
case 'F':
case 'f': tmp = 15; break;
default: tmp = 0; break;
}
result[k] |= tmp;
}
return result;
}
// first element is the shift
byte[] result = new byte[a.length-1];
int i = 0;
int shift = s.charAt(i++);
int j = 0;
while (i < s.length()) {
int c;
if ((c = s.charAt(i++)) == 1) { // escape character found
if ((c = s.charAt(i++)) == 1) {
c = 0;
} else if (c == 2) {
c = 1;
} else if (c == 3) {
c = '\'';
} else {
throw new IllegalArgumentException(
"invalid string passed to decoder: " + j);
}
}
// do shift
result[j++] = (byte)((c + shift) & 0xff);
}
int outLen = j;
// provide array of correct length
if (result.length != outLen) {
result = byteCopy(result, 0, outLen, new byte[outLen]);
}
return result;
}
/**
* Copies count elements from source, starting at element with
* index offset, to the given target.
* @param source the source.
* @param offset the offset.
* @param count the number of elements to be copied.
* @param target the target to be returned.
* @return the target being copied to.
*/
private static byte[] byteCopy(byte[] source, int offset,
int count, byte[] target) {
for (int i = offset, j = 0; i < offset + count; i++, j++) {
target[j] = source[i];
}
return target;
}
static final char[] xdigits = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
/**
* Encodes the given byte array into SQLite3 blob notation, ie X'..'
* @param a the byte array to be encoded. A null reference is handled as
* an empty array.
* @return the encoded bytes as a string.
*/
public static String encodeX(byte[] a) {
// check input
if (a == null || a.length == 0) {
return "X''";
}
char[] out = new char[a.length * 2 + 3];
int i = 2;
for (int j = 0; j < a.length; j++) {
out[i++] = xdigits[(a[j] >> 4) & 0x0F];
out[i++] = xdigits[a[j] & 0x0F];
}
out[0] = 'X';
out[1] = '\'';
out[i] = '\'';
return new String(out);
}
}

View File

@ -0,0 +1,159 @@
package jsqlite;
import java.util.Vector;
/**
* Class representing an SQLite result set as
* returned by the
* <A HREF="Database.html#get_table(java.lang.String)">Database.get_table</A>
* convenience method.
* <BR><BR>
* Example:<BR>
*
* <PRE>
* ...
* SQLite.Database db = new SQLite.Database();
* db.open("db", 0);
* System.out.print(db.get_table("select * from TEST"));
* ...
* </PRE>
* Example output:<BR>
*
* <PRE>
* id|firstname|lastname|
* 0|John|Doe|
* 1|Speedy|Gonzales|
* ...
* </PRE>
*/
public class TableResult implements Callback {
/**
* Number of columns in the result set.
*/
public int ncolumns;
/**
* Number of rows in the result set.
*/
public int nrows;
/**
* Column names of the result set.
*/
public String column[];
/**
* Types of columns of the result set or null.
*/
public String types[];
/**
* Rows of the result set. Each row is stored as a String array.
*/
public Vector rows;
/**
* Maximum number of rows to hold in the table.
*/
public int maxrows = 0;
/**
* Flag to indicate Maximum number of rows condition.
*/
public boolean atmaxrows;
/**
* Create an empty result set.
*/
public TableResult() {
clear();
}
/**
* Create an empty result set with maximum number of rows.
*/
public TableResult(int maxrows) {
this.maxrows = maxrows;
clear();
}
/**
* Clear result set.
*/
public void clear() {
column = new String[0];
types = null;
rows = new Vector();
ncolumns = nrows = 0;
atmaxrows = false;
}
/**
* Callback method used while the query is executed.
*/
public void columns(String coldata[]) {
column = coldata;
ncolumns = column.length;
}
/**
* Callback method used while the query is executed.
*/
public void types(String types[]) {
this.types = types;
}
/**
* Callback method used while the query is executed.
*/
public boolean newrow(String rowdata[]) {
if (rowdata != null) {
if (maxrows > 0 && nrows >= maxrows) {
atmaxrows = true;
return true;
}
rows.addElement(rowdata);
nrows++;
}
return false;
}
/**
* Make String representation of result set.
*/
public String toString() {
StringBuffer sb = new StringBuffer();
int i;
for (i = 0; i < ncolumns; i++) {
sb.append(column[i] == null ? "NULL" : column[i]);
sb.append('|');
}
sb.append('\n');
for (i = 0; i < nrows; i++) {
int k;
String row[] = (String[]) rows.elementAt(i);
for (k = 0; k < ncolumns; k++) {
sb.append(row[k] == null ? "NULL" : row[k]);
sb.append('|');
}
sb.append('\n');
}
return sb.toString();
}
}

View File

@ -0,0 +1,17 @@
package jsqlite;
/**
* Callback interface for SQLite's trace function.
*/
public interface Trace {
/**
* Callback to trace (ie log) one SQL statement.
*
* @param stmt SQL statement string
*/
public void trace(String stmt);
}

View File

@ -0,0 +1,78 @@
package jsqlite;
/**
* Class to represent compiled SQLite VM.
*/
public class Vm {
/**
* Internal handle for the compiled SQLite VM.
*/
private long handle = 0;
/**
* Internal last error code for compile()/step() methods.
*/
protected int error_code = 0;
/**
* Perform one step on compiled SQLite VM.
* The result row is passed to the given callback interface.<BR><BR>
*
* Example:<BR>
* <PRE>
* ...
* try {
* Vm vm = db.compile("select * from x; select * from y;");
* while (vm.step(cb)) {
* ...
* }
* while (vm.compile()) {
* while (vm.step(cb)) {
* ...
* }
* }
* } catch (SQLite.Exception e) {
* }
* </PRE>
*
* @param cb the object implementing the callback methods.
* @return true as long as more row data can be retrieved,
* false, otherwise.
*/
public native boolean step(Callback cb) throws jsqlite.Exception;
/**
* Compile the next SQL statement for the SQLite VM instance.
* @return true when SQL statement has been compiled, false
* on end of statement sequence.
*/
public native boolean compile() throws jsqlite.Exception;
/**
* Abort the compiled SQLite VM.
*/
public native void stop() throws jsqlite.Exception;
/**
* Destructor for object.
*/
protected native void finalize();
/**
* Internal native initializer.
*/
private static native void internal_init();
static {
internal_init();
}
}

32
android/spatialite/README Normal file
View File

@ -0,0 +1,32 @@
#do all these in linux box
#"spatialite-android is checked out from..."
svn checkout http://spatialite-android.googlecode.com/svn/trunk/ spatialite-android-read-only
#then follow instaructions...
cd jni
#wget http://download.osgeo.org/geos/geos-3.2.2.tar.bz2 #( already added to svn )
tar xvjf geos-3.2.2.tar.bz2
cd geos-3.2.2
./configure --build=x86_64-pc-linux-gnu --host=arm-linux-eabi
cd ..
#wget ftp://ftp.remotesensing.org/proj/proj-4.7.0.tar.gz #( already added to svn )
tar xvzf proj-4.7.0.tar.gz
cd proj-4.7.0
./configure --build=x86_64-pc-linux-gnu --host=arm-linux-eabi
touch src/empty.cpp
cd ..
#now in jni execute.. ( download ndk tar from "http://developer.android.com/sdk/ndk/index.html" )
ndk-build
#this will create "libs\armeabi\libjsqlite.so" , which is already added in SVN
#now add your database in res/raw/ ("test-2.3.sqlite is test database, which is no added in svn..")
#and do
ant clean
ant debug
#apk created... push it to phone and starts running...