Saturday, June 4, 2016

Store your Location in DataBase (SQLite) using Google Map API V2

"Jai Saraswati  Maa"

Dear All This example will helps you to capture your Location and store in DataBase (SQLite).

Please be sure you know how add Google Map API Key in your App.
Suggestion Please read my previous post Google Map PArt I & II Carefully.
I am using Android Studio 1.5.1 with API23(Marshmallow).
Thanks ..
 
A. Output will be like this
 ******* When you click on a particular location it will show you a default marker and store this location to DataBase like this .... It will show you a Toast Also....


B. Java Codes

1. DataBase Handler class    LocationsDB.java is as 

package com.exam.ravi.googlemapex1;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class LocationsDB extends SQLiteOpenHelper {

       private static String DBNAME = "locationDB";

      private static int VERSION = 1;


    public static final String ROW_ID = "_id";


    public static final String LAT = "lat";
      public static final String LNG = "lng";
    public static final String ZOOM = "zom";

    private static final String DB_TABLE = "loc";

    private SQLiteDatabase mDB;
    public LocationsDB(Context context) {
        super(context, DBNAME, null, VERSION);
        this.mDB = getWritableDatabase();
    }
    @Override    public void onCreate(SQLiteDatabase db) {
        String sql =     "create table " + DB_TABLE + " ( " +
                ROW_ID + " integer primary key autoincrement , " +
                LNG + " double , " +
                LAT + " double , " +
                ZOOM + " text " +
                " ) ";
        db.execSQL(sql);
    }

   
    public long insert(ContentValues contentValues){
        long rowID = mDB.insert(DB_TABLE, null, contentValues);
        return rowID;
    }

    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

}

2.  MainActivity is as   named as AddLoc.java

package com.exam.ravi.googlemapex1;

import android.content.ContentValues;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;


public class AddLoc extends AppCompatActivity  implements OnMapReadyCallback  {

        GoogleMap gMap;
        Context cob = this;
        @Override        protected void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
            SupportMapFragment mapFragment = (SupportMapFragment) 
                     getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);

    }
    @Override    public void onMapReady(GoogleMap googleMap)
    {
        gMap = googleMap;
        LatLng jaipur = new LatLng(26.923952,75.826743);
        CameraPosition cameraPosition = CameraPosition.builder()
         .zoom(17).tilt(20).bearing(90).target(jaipur).build();
         gMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            gMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override            public void onMapClick(LatLng point) {

                drawMarker(point);   // Draw marker

                 ContentValues contentValues = new ContentValues();
                // get  & set with contentvalues

                 contentValues.put(LocationsDB.LAT, point.latitude);
                contentValues.put(LocationsDB.LNG, point.longitude);
                contentValues.put(LocationsDB.ZOOM, gMap.getCameraPosition().zoom);
                LocationsDB lb = new LocationsDB(cob);
                // Storing the latitude, longitude and zoom level to SQLite database

                long row = lb.insert(contentValues);
                if(row>0)
                Toast.makeText(cob, "Your Location Inserted Successfully...." , 
                                               Toast.LENGTH_SHORT).show();
                else

             Toast.makeText(cob, "Something Wrong...", Toast.LENGTH_SHORT).show();

            }
        });
    }
    private void drawMarker(LatLng point){
               MarkerOptions markerOptions = new MarkerOptions();
                 markerOptions.position(point);
                gMap.addMarker(markerOptions);
    }

}

C. XML files

1. MainLayout file is as

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:map="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context="com.exam.ravi.googlemapex1.MapsActivity" >
    <fragment        android:id="@+id/map"

        android:name="com.google.android.gms.maps.SupportMapFragment"

        android:layout_width="match_parent"

        android:layout_height="match_parent"></fragment>
    </LinearLayout>

2. Manifest File is as

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.exam.ravi.googlemapex1">

    <!--         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use

         Google Maps Android API v2, but you must specify either coarse or fine

         location permissions for the 'MyLocation' functionality.     -->

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:supportsRtl="true"

        android:theme="@style/AppTheme">

        <!--             The API key for Google Maps-based APIs is defined as a string resource.

             (See the file "res/values/google_maps_api.xml").

             Note that the API key is linked to the encryption key used to sign the APK.

             You need a different API key for each encryption key, including the release
             key that is used to sign the APK for publishing.

             You can define the keys for the debug and release targets in src/debug/ 
              and src/release/.         -->

        <meta-data            android:name="com.google.android.geo.API_KEY"

            android:value="@string/google_maps_key" />

        <activity            android:name=".AddLoc"

            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

2 comments:

  1. How to view the stored location?

    ReplyDelete
  2. How to show marker from sqlite when search for a location ??

    ReplyDelete