· 9 years ago · Jan 22, 2017, 09:34 AM
1public class LocationsContentProvider extends ContentProvider{
2
3 public static final String PROVIDER_NAME = "pioneers.locationcontentprovider.LocationsContentProvider";
4
5 public static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME + "/locations" );
6
7 private static final int LOCATIONS = 1;
8
9 private static final UriMatcher uriMatcher ;
10
11 static {
12 uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
13 uriMatcher.addURI(PROVIDER_NAME, "locations", LOCATIONS);
14 }
15
16
17 LocationsDB mLocationsDB;
18
19
20 @Override
21 public boolean onCreate() {
22 mLocationsDB = new LocationsDB(getContext());
23 return true;
24 }
25
26
27 @Override
28 public Uri insert(Uri uri, ContentValues values) {
29 long rowID = mLocationsDB.insert(values);
30 Uri _uri=null;
31 if(rowID>0){
32 _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
33 }else {
34 try {
35 throw new SQLException("Failed to insert : " + uri);
36 } catch (SQLException e) {
37 e.printStackTrace();
38 }
39 }
40 return _uri;
41 }
42
43 @Override
44 public int update(Uri uri, ContentValues values, String selection,
45 String[] selectionArgs) {
46 // TODO Auto-generated method stub
47 return 0;
48 }
49
50
51
52
53 @Override
54 public int delete(Uri uri, String selection, String[] selectionArgs) {
55 int cnt = 0;
56 cnt = mLocationsDB.del();
57 return cnt;
58 }
59
60
61 @Override
62 public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
63
64 if(uriMatcher.match(uri)==LOCATIONS){
65 return mLocationsDB.getAllLocations();
66 }
67 return null;
68 }
69 @Override
70 public String getType(Uri uri) {
71 return null;
72 }
73}
74
75import android.content.ContentValues;
76import android.content.Context;
77import android.database.Cursor;
78import android.database.sqlite.SQLiteDatabase;
79import android.database.sqlite.SQLiteOpenHelper;
80
81
82public class LocationsDB extends SQLiteOpenHelper{
83
84
85 private static String DBNAME = "locationmarkersqlite";
86
87 /** Version number of the database */
88 private static int VERSION = 1;
89
90 /** Field 1 of the table locations, which is the primary key */
91 public static final String FIELD_ROW_ID = "_id";
92
93 /** Field 2 of the table locations, stores the latitude */
94 public static final String FIELD_LAT = "lat";
95
96 /** Field 3 of the table locations, stores the longitude*/
97 public static final String FIELD_LNG = "lng";
98
99 /** Field 4 of the table locations, stores the zoom level of map*/
100 public static final String FIELD_ZOOM = "zom";
101
102 /** A constant, stores the the table name */
103 private static final String DATABASE_TABLE = "locations";
104
105 /** An instance variable for SQLiteDatabase */
106 private SQLiteDatabase mDB;
107
108
109 /** Constructor */
110 public LocationsDB(Context context) {
111 super(context, DBNAME, null, VERSION);
112 this.mDB = getWritableDatabase();
113 }
114
115
116 /** This is a callback method, invoked when the method getReadableDatabase() / getWritableDatabase() is called
117 * provided the database does not exists
118 * */
119 @Override
120 public void onCreate(SQLiteDatabase db) {
121 String sql = "create table " + DATABASE_TABLE + " ( " +
122 FIELD_ROW_ID + " integer primary key autoincrement , " +
123 FIELD_LNG + " double , " +
124 FIELD_LAT + " double , " +
125 FIELD_ZOOM + " text " +
126 " ) ";
127
128 db.execSQL(sql);
129 }
130
131 /** Inserts a new location to the table locations */
132 public long insert(ContentValues contentValues){
133 long rowID = mDB.insert(DATABASE_TABLE, null, contentValues);
134 return rowID;
135
136 }
137
138
139 /** Deletes all locations from the table */
140 public int del(){
141 int cnt = mDB.delete(DATABASE_TABLE, null , null);
142 return cnt;
143 }
144
145 /** Returns all the locations from the table */
146 public Cursor getAllLocations(){
147 return mDB.query(DATABASE_TABLE, new String[] { FIELD_ROW_ID, FIELD_LAT , FIELD_LNG, FIELD_ZOOM } , null, null, null, null, null);
148 }
149
150 @Override
151 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
152
153 }
154
155}
156
157import android.app.Dialog;
158import android.content.ContentValues;
159import android.content.pm.PackageManager;
160import android.database.Cursor;
161import android.net.Uri;
162import android.os.AsyncTask;
163import android.os.Build;
164import android.os.Bundle;
165import android.support.v4.app.ActivityCompat;
166import android.support.v4.app.FragmentActivity;
167import android.support.v4.app.LoaderManager.LoaderCallbacks;
168import android.support.v4.content.ContextCompat;
169import android.support.v4.content.CursorLoader;
170import android.support.v4.content.Loader;
171import android.support.v7.app.AppCompatActivity;
172import android.view.Menu;
173import android.widget.Toast;
174
175import com.google.android.gms.common.ConnectionResult;
176import com.google.android.gms.common.GooglePlayServicesUtil;
177import com.google.android.gms.maps.CameraUpdateFactory;
178import com.google.android.gms.maps.GoogleMap;
179import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
180import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
181import com.google.android.gms.maps.OnMapReadyCallback;
182import com.google.android.gms.maps.SupportMapFragment;
183import com.google.android.gms.maps.model.LatLng;
184import com.google.android.gms.maps.model.MarkerOptions;
185
186public class MainActivity extends FragmentActivity implements LoaderCallbacks<Cursor>, OnMapReadyCallback {
187
188 GoogleMap googleMap;
189
190 @Override
191 protected void onCreate(Bundle savedInstanceState) {
192 super.onCreate(savedInstanceState);
193 setContentView(R.layout.activity_main);
194
195
196 int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
197
198 // Showing status
199 if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available
200
201 int requestCode = 10;
202 Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
203 dialog.show();
204
205 } else { // Google Play Services are available
206
207 // Getting reference to the SupportMapFragment of activity_main.xml
208 SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
209
210
211 fm.getMapAsync(this);
212
213 if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
214 // TODO: Consider calling
215 // ActivityCompat#requestPermissions
216 // here to request the missing permissions, and then overriding
217 // public void onRequestPermissionsResult(int requestCode, String[] permissions,
218 // int[] grantResults)
219 // to handle the case where the user grants the permission. See the documentation
220 // for ActivityCompat#requestPermissions for more details.
221 return;
222 }
223
224
225 googleMap.setMyLocationEnabled(true);
226
227 // Invoke LoaderCallbacks to retrieve and draw already saved locations in map
228 getSupportLoaderManager().initLoader(0, null, this);
229 }
230
231 googleMap.setOnMapClickListener(new OnMapClickListener() {
232
233 @Override
234 public void onMapClick(LatLng point) {
235
236
237 // Drawing marker on the map
238 drawMarker(point);
239
240 // Creating an instance of ContentValues
241 ContentValues contentValues = new ContentValues();
242
243 // Setting latitude in ContentValues
244 contentValues.put(LocationsDB.FIELD_LAT, point.latitude );
245
246 // Setting longitude in ContentValues
247 contentValues.put(LocationsDB.FIELD_LNG, point.longitude);
248
249 // Setting zoom in ContentValues
250 contentValues.put(LocationsDB.FIELD_ZOOM, googleMap.getCameraPosition().zoom);
251
252 // Creating an instance of LocationInsertTask
253 LocationInsertTask insertTask = new LocationInsertTask();
254
255 // Storing the latitude, longitude and zoom level to SQLite database
256 insertTask.execute(contentValues);
257
258 Toast.makeText(getBaseContext(), "Marker is added to the Map", Toast.LENGTH_SHORT).show();
259
260 }
261 });
262
263
264 googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {
265 @Override
266 public void onMapLongClick(LatLng point) {
267
268 // Removing all markers from the Google Map
269 googleMap.clear();
270
271 // Creating an instance of LocationDeleteTask
272 LocationDeleteTask deleteTask = new LocationDeleteTask();
273
274 // Deleting all the rows from SQLite database table
275 deleteTask.execute();
276
277 Toast.makeText(getBaseContext(), "All markers are removed", Toast.LENGTH_LONG).show();
278
279 }
280 });
281 }
282
283
284 private void drawMarker(LatLng point){
285 // Creating an instance of MarkerOptions
286 MarkerOptions markerOptions = new MarkerOptions();
287
288 // Setting latitude and longitude for the marker
289 markerOptions.position(point);
290
291 // Adding marker on the Google Map
292 googleMap.addMarker(markerOptions);
293 }
294
295 @Override
296 public void onMapReady(GoogleMap googleMap) {
297
298 googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
299 googleMap.getUiSettings().setZoomControlsEnabled(true);
300 googleMap.getUiSettings().setCompassEnabled(true);
301 googleMap.getUiSettings().setMyLocationButtonEnabled(true);
302 googleMap.getUiSettings().setRotateGesturesEnabled(true);
303 googleMap.getUiSettings().setScrollGesturesEnabled(true);
304 googleMap.getUiSettings().setTiltGesturesEnabled(true);
305 googleMap.getUiSettings().setZoomGesturesEnabled(true);
306 //or myMap.getUiSettings().setAllGesturesEnabled(true);
307 googleMap.setTrafficEnabled(true);
308 }
309
310
311
312
313 private class LocationInsertTask extends AsyncTask<ContentValues, Void, Void>{
314 @Override
315 protected Void doInBackground(ContentValues... contentValues) {
316
317 /** Setting up values to insert the clicked location into SQLite database */
318 getContentResolver().insert(LocationsContentProvider.CONTENT_URI, contentValues[0]);
319 return null;
320 }
321 }
322
323 private class LocationDeleteTask extends AsyncTask<Void, Void, Void>{
324 @Override
325 protected Void doInBackground(Void... params) {
326
327 /** Deleting all the locations stored in SQLite database */
328 getContentResolver().delete(LocationsContentProvider.CONTENT_URI, null, null);
329 return null;
330 }
331 }
332
333
334 @Override
335 public boolean onCreateOptionsMenu(Menu menu) {
336 // Inflate the menu; this adds items to the action bar if it is present.
337 getMenuInflater().inflate(R.menu.main, menu);
338 return true;
339 }
340
341
342 @Override
343 public Loader<Cursor> onCreateLoader(int arg0,
344 Bundle arg1) {
345
346 // Uri to the content provider LocationsContentProvider
347 Uri uri = LocationsContentProvider.CONTENT_URI;
348
349 // Fetches all the rows from locations table
350 return new CursorLoader(this, uri, null, null, null, null);
351
352 }
353
354
355 @Override
356 public void onLoadFinished(Loader<Cursor> arg0,
357 Cursor arg1) {
358 int locationCount = 0;
359 double lat=0;
360 double lng=0;
361 float zoom=0;
362
363 // Number of locations available in the SQLite database table
364 locationCount = arg1.getCount();
365
366 // Move the current record pointer to the first row of the table
367 arg1.moveToFirst();
368
369 for(int i=0;i<locationCount;i++){
370
371 // Get the latitude
372 lat = arg1.getDouble(arg1.getColumnIndex(LocationsDB.FIELD_LAT));
373
374 // Get the longitude
375 lng = arg1.getDouble(arg1.getColumnIndex(LocationsDB.FIELD_LNG));
376
377 // Get the zoom level
378 zoom = arg1.getFloat(arg1.getColumnIndex(LocationsDB.FIELD_ZOOM));
379
380 // Creating an instance of LatLng to plot the location in Google Maps
381 LatLng location = new LatLng(lat, lng);
382
383 // Drawing the marker in the Google Maps
384 drawMarker(location);
385
386 // Traverse the pointer to the next row
387 arg1.moveToNext();
388 }
389
390 if(locationCount>0){
391 // Moving CameraPosition to last clicked position
392 googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(lat,lng)));
393
394 // Setting the zoom level in the map on last position is clicked
395 googleMap.animateCamera(CameraUpdateFactory.zoomTo(zoom));
396
397 }
398 }
399
400 @Override
401 public void onLoaderReset(Loader<Cursor> arg0) {
402 // TODO Auto-generated method stub
403 }
404}
405
406<?xml version="1.0" encoding="utf-8"?>
407 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
408 package="pioneers.locationcontentprovider">
409 <permission
410 android:name="pioneers.locationcontentprovider.permission.MAPS_RECEIVE"
411 android:protectionLevel="signature"/>
412
413 <uses-permission android:name="pioneers.locationcontentprovider.permission.MAPS_RECEIVE"/>
414
415 <uses-permission android:name="android.permission.INTERNET"/>
416 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
417 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
418 <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
419 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
420 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
421 <application
422 android:allowBackup="true"
423 android:icon="@mipmap/ic_launcher"
424 android:label="@string/app_name"
425 android:supportsRtl="true"
426 android:theme="@style/AppTheme">
427 <activity android:name=".MainActivity">
428 <intent-filter>
429 <action android:name="android.intent.action.MAIN" />
430
431 <category android:name="android.intent.category.LAUNCHER" />
432 </intent-filter>
433 </activity>
434 <provider
435 android:name=".LocationsContentProvider"
436 android:authorities="pioneers.locationcontentprovider.LocationsContentProvider"
437 android:exported="false" />
438
439 <meta-data
440 android:name="com.google.android.maps.v2.API_KEY"
441 android:value="YOUR_ANDROID_API_KEY" />
442 </application>
443
444 </manifest>
445
446<?xml version="1.0" encoding="utf-8"?>
447<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
448 xmlns:tools="http://schemas.android.com/tools"
449 android:id="@+id/activity_main"
450 android:layout_width="match_parent"
451 android:layout_height="match_parent"
452 android:paddingBottom="@dimen/activity_vertical_margin"
453 android:paddingLeft="@dimen/activity_horizontal_margin"
454 android:paddingRight="@dimen/activity_horizontal_margin"
455 android:paddingTop="@dimen/activity_vertical_margin"
456 tools:context="pioneers.locationcontentprovider.MainActivity">
457
458 <fragment
459 android:id="@+id/map"
460 android:layout_width="match_parent"
461 android:layout_height="match_parent"
462 android:name="com.google.android.gms.maps.SupportMapFragment" />
463</RelativeLayout>
464
465import android.content.ContentValues;
466import android.content.Context;
467import android.database.Cursor;
468import android.database.sqlite.SQLiteDatabase;
469import android.database.sqlite.SQLiteOpenHelper;
470
471
472public class LocationsDB extends SQLiteOpenHelper{
473
474 /** Database name */
475 private static String DBNAME = "locationmarkersqlite";
476
477 /** Version number of the database */
478 private static int VERSION = 1;
479
480 /** Field 1 of the table locations, which is the primary key */
481 public static final String FIELD_ROW_ID = "_id";
482
483 /** Field 2 of the table locations, stores the latitude */
484 public static final String FIELD_LAT = "lat";
485
486 /** Field 3 of the table locations, stores the longitude*/
487 public static final String FIELD_LNG = "lng";
488
489 /** Field 4 of the table locations, stores the zoom level of map*/
490 public static final String FIELD_ZOOM = "zom";
491
492 /** A constant, stores the the table name */
493 private static final String DATABASE_TABLE = "locations";
494
495 /** An instance variable for SQLiteDatabase */
496 private SQLiteDatabase mDB;
497
498
499 /** Constructor */
500 public LocationsDB(Context context) {
501 super(context, DBNAME, null, VERSION);
502 this.mDB = getWritableDatabase();
503 }
504
505
506 /** This is a callback method, invoked when the method getReadableDatabase() / getWritableDatabase() is called
507 * provided the database does not exists
508 * */
509 @Override
510 public void onCreate(SQLiteDatabase db) {
511 String sql = "create table " + DATABASE_TABLE + " ( " +
512 FIELD_ROW_ID + " integer primary key autoincrement , " +
513 FIELD_LNG + " double , " +
514 FIELD_LAT + " double , " +
515 FIELD_ZOOM + " text " +
516 " ) ";
517
518 db.execSQL(sql);
519 }
520
521 /** Inserts a new location to the table locations */
522 public long insert(ContentValues contentValues){
523 long rowID = mDB.insert(DATABASE_TABLE, null, contentValues);
524 return rowID;
525
526 }
527
528
529 /** Deletes all locations from the table */
530 public int del(){
531 int cnt = mDB.delete(DATABASE_TABLE, null , null);
532 return cnt;
533 }
534
535 /** Returns all the locations from the table */
536 public Cursor getAllLocations(){
537 return mDB.query(DATABASE_TABLE, new String[] { FIELD_ROW_ID, FIELD_LAT , FIELD_LNG, FIELD_ZOOM } , null, null, null, null, null);
538 }
539
540 @Override
541 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
542
543 }
544
545}