0% found this document useful (0 votes)
13 views27 pages

Unit 4 - MAD

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views27 pages

Unit 4 - MAD

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Unit 4

Creating Your Own Content


CONTENT PROVIDERS
 A content provider component supplies data from one application to others on request. Such requests are
handled by the methods of the ContentResolver class.
 A content provider can use different ways to store its data and the data can be stored in a database, in
files, or even over a network.
 Content providers let you centralize content in one place and have many different applications access
it as needed.
 A content provider behaves very much like a database where you can query it, edit its content, as well
as add or delete content using insert(), update(), delete(), and query() methods. In most cases this data
is stored in an SQlite database.
 A content provider is implemented as a subclass of ContentProvider class and must implement a
standard set of APIs that enable other applications to perform transactions.

public class My Application extends ContentProvider {


}

Content URIs

 To query a content provider, you specify the query string in the form of a URI which has following
format

<prefix>://<authority>/<data_type>/<id>
Create Content Provider
This involves number of simple steps to create your own content provider.
 First of all you need to create a Content Provider class that extends the ContentProviderbaseclass.
 Second, you need to define your content provider URI address which will be used to access the
content.
 Next you will need to create your own database to keep the content. Usually, Android uses SQLite
database and framework needs to override onCreate() method which will use SQLite Open Helper
method to create or open the provider's database. When your application is launched,
the onCreate() handler of each of its Content Providers is called on the main application thread.
 Next you will have to implement Content Provider queries to perform different database specific
operations.
 Finally register your Content Provider in your activity file using <provider> tag.

Here is the list of methods which you need to override in Content Provider class to have your Content Provider
working –
Example
This example will explain you how to create your own ContentProvider. So let's follow the following steps to
similar to what we followed while creating Hello World Example−

Creating a Content Provider

Step 1:Create a new project

Step 2: Creating activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Content Provider!"
android:layout_gravity="center"
android:textSize="20dp"
android:textStyle="bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="VIM"
android:layout_gravity="center"
android:textSize="20dp"
android:textStyle="bold"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/img"
android:layout_gravity="center"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter first Name:"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/edit1"
android:hint="first name here"
/>
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Grade"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/edit2"
android:hint="grade here"
/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="submit"
android:id="@+id/button1"
android:layout_gravity="center"
android:onClick="onClickAddName"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="retrive"
android:id="@+id/button2"
android:layout_gravity="center"
android:onClick="onClickRetrieveStudents"/>
</LinearLayout>

Step 3: Creating Main_Activity.java

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickAddName(View view) {
// Add a new student record
ContentValues values = new ContentValues();
values.put(StudentsProvider.NAME,
((EditText)findViewById(R.id.edit1)).getText().toString());

values.put(StudentsProvider.GRADE,
((EditText)findViewById(R.id.edit2)).getText().toString());

Uri uri = getContentResolver().insert(


StudentsProvider.CONTENT_URI, values);

Toast.makeText(getBaseContext(),
uri.toString(), Toast.LENGTH_LONG).show();
}
public void onClickRetrieveStudents(View view) {
// Retrieve student records
String URL = "content://com.example.PG8.StudentsProvider";

Uri students = Uri.parse(URL);


Cursor c = managedQuery(students, null, null, null, "name");

if (c.moveToFirst()) {
do{
Toast.makeText(this,c.getString(c.getColumnIndex(StudentsProvider._ID)) +
", " + c.getString(c.getColumnIndex( StudentsProvider.NAME)) +
", " + c.getString(c.getColumnIndex( StudentsProvider.GRADE)),
Toast.LENGTH_SHORT).show();
} while (c.moveToNext());
}
}
}

Step 4: Create ContentHandler a java class to define various database handler activities and add the following
code.
package com.example.pg8;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;

import android.database.Cursor;
import android.database.SQLException;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;

import android.net.Uri;
import android.text.TextUtils;

public class StudentsProvider extends ContentProvider {


static final String PROVIDER_NAME = "com.example.PG8.StudentsProvider";
static final String URL = "content://" + PROVIDER_NAME + "/students";
static final Uri CONTENT_URI = Uri.parse(URL);

static final String _ID = "_id";


static final String NAME = "name";
static final String GRADE = "grade";

private static HashMap<String, String> STUDENTS_PROJECTION_MAP;

static final int STUDENTS = 1;


static final int STUDENT_ID = 2;

static final UriMatcher uriMatcher;


static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "students", STUDENTS);
uriMatcher.addURI(PROVIDER_NAME, "students/#", STUDENT_ID);
}

/**
* Database specific constant declarations
*/

private SQLiteDatabase db;


static final String DATABASE_NAME = "College";
static final String STUDENTS_TABLE_NAME = "students";
static final int DATABASE_VERSION = 1;
static final String CREATE_DB_TABLE =
" CREATE TABLE " + STUDENTS_TABLE_NAME +
" (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
" name TEXT NOT NULL, " +
" grade TEXT NOT NULL);";

/**
* Helper class that actually creates and manages
* the provider's underlying data repository.
*/

private static class DatabaseHelper extends SQLiteOpenHelper {


DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_DB_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + STUDENTS_TABLE_NAME);
onCreate(db);
}
}

@Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);

/**
* Create a write able database which will trigger its
* creation if it doesn't already exist.
*/

db = dbHelper.getWritableDatabase();
return (db == null)? false:true;
}

@Override
public Uri insert(Uri uri, ContentValues values) {
/**
* Add a new student record
*/
long rowID = db.insert( STUDENTS_TABLE_NAME, "", values);

/**
* If record is added successfully
*/
if (rowID > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}

throw new SQLException("Failed to add a record into " + uri);


}

@Override
public Cursor query(Uri uri, String[] projection,
String selection,String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(STUDENTS_TABLE_NAME);

switch (uriMatcher.match(uri)) {
case STUDENTS:
qb.setProjectionMap(STUDENTS_PROJECTION_MAP);
break;

case STUDENT_ID:
qb.appendWhere( _ID + "=" + uri.getPathSegments().get(1));
break;

default:
}

if (sortOrder == null || sortOrder == ""){


/**
* By default sort on student names
*/
sortOrder = NAME;
}

Cursor c = qb.query(db, projection, selection,


selectionArgs,null, null, sortOrder);
/**
* register to watch a content URI for changes
*/
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}

Step 5: Add provider tag in manifest.xml file

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


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

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.PG8"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


</intent-filter>
</activity>
<provider android:name="StudentsProvider"
android:authorities="com.example.PG8.StudentsProvider"/>
</application>

</manifest>

Output:

Sending SMS Messages Programmatically

 A text SMS over the phone can be done by using the SMSManager class in an Android application.
 SMSManager class manages operations like sending a text message, data message, and multimedia
messages (MMS).
 For sending a text message method sendTextMessage() is used likewise for multimedia message
sendMultimediaMessage() and for data message sendDataMessage() method is used.
 The details of each function are:
Function Description

sendTextMessage(String destinationAddress,
sendTextMessage() String scAddress, String text, PendingIntent sentIntent,
PendingIntent deliveryIntent, long messageId)
Function Description

sendDataMessage(String destinationAddress,
sendDataMessage() String scAddress, short destinationPort, byte[] data,
PendingIntent sentIntent, PendingIntent deliveryIntent)

sendMultimediaMessage(Context context,
sendMultimediaMessage() Uri contentUri, String locationUrl,
Bundle configOverrides, PendingIntent sentIntent

Below is an example of a basic application that sends a text message.

Activity_Main.xml

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<EditText
android:id="@+id/phonenumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:hint="Phone Number"
/>

<EditText
android:id="@+id/messagebox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Message"
/>

<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
/>
</LinearLayout>

Manifest.XML

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dist="http://schemas.android.com/apk/distribution"
package="com.example.smspgm">

<uses-feature
android:name="android.hardware.telephony"
android:required="false" />
<uses-permission android:name="android.permission.SEND_SMS"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Smspgm">
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


</intent-filter>
</activity>
</application>

</manifest>

MainActivity.java

package com.example.smspgm;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this,new
String[]{Manifest.permission.SEND_SMS},
PackageManager.PERMISSION_GRANTED);
EditText ph=(EditText) findViewById(R.id.phonenumber);
EditText msg=(EditText) findViewById(R.id.messagebox);
Button btnsend=(Button) findViewById(R.id.send);
btnsend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SmsManager s=SmsManager.getDefault();
s.sendTextMessage(ph.getText().toString(),null,msg.getText().toString(),null,null);
Toast.makeText(MainActivity.this, "Message Sent",
Toast.LENGTH_SHORT).show();
}
});
}
}

Sending E-mail

 Sending Email is like SMS messaging, Android also supports e-mail. The Gmail/Email application on
Android enables you to configure an email account using POP3 or IMAP. Besides sending and receiving
e-mails using the Gmail/Email application.
 POP3 (Post Office Protocol 3) and IMAP (Internet Message Access Protocol) both are MAA (Message
accessing agent), and both of these protocols are used to retrieve messages from the mail server to the
receiver system.
 You can do so with the help of Intent with action as ACTION_SEND with extra fields:

 email id to which you want to send mail,


 the subject of the email and
 body of the email.

 Basically Intent is a simple message object that is used to communicate between android components
such as activities, content providers, broadcast receivers, and services, here use to send the email. This
application basically contains one activity with EditText to take input of email address, subject, and
body of the email from the user and button to send that email.

Following is the program to demonstrate Email


Step 1: Create a New Project in Android Studio

Step 2: Working with the XML Files


<?xml version="1.0" encoding="utf-8"?>
<!-- Relative Layout -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<!-- Edit text for email id -->


<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_marginTop="18dp"
android:layout_marginRight="22dp" />

<!-- Edit text for email subject -->


<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_alignLeft="@+id/editText1"
android:layout_marginTop="20dp" />

<!-- Edit text for email body -->


<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_alignLeft="@+id/editText2"
android:layout_marginTop="30dp" />

<!-- text Views for label -->


<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText1"
android:layout_alignBottom="@+id/editText1"
android:layout_alignParentLeft="true"
android:text="Send To:"
android:textColor="#0F9D58" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText2"
android:layout_alignBottom="@+id/editText2"
android:layout_alignParentLeft="true"
android:text="Email Subject:"
android:textColor="#0F9D58" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText3"
android:layout_alignBottom="@+id/editText3"
android:text="Email Body:"
android:textColor="#0F9D58" />

<!-- Button to send email -->


<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText3"
android:layout_alignLeft="@+id/editText3"
android:layout_marginLeft="76dp"
android:layout_marginTop="20dp"
android:text="Send email!!" />
</RelativeLayout>
Step 3: Working with the JAVA File
package com.example.mailpgm;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

// define objects for edit text and button


Button button;
EditText sendto, subject, body;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Getting instance of edittext and button


sendto = findViewById(R.id.editText1);
subject = findViewById(R.id.editText2);
body = findViewById(R.id.editText3);
button = findViewById(R.id.button);

// attach setOnClickListener to button with Intent object define in it


button.setOnClickListener(view -> {
String emailsend = sendto.getText().toString();
String emailsubject = subject.getText().toString();
String emailbody = body.getText().toString();

// define Intent object with action attribute as ACTION_SEND


Intent intent = new Intent(Intent.ACTION_SEND);

// add three fields to intent using putExtra function


intent.putExtra(Intent.EXTRA_EMAIL, new String[]{emailsend});
intent.putExtra(Intent.EXTRA_SUBJECT, emailsubject);
intent.putExtra(Intent.EXTRA_TEXT, emailbody);

// set type of intent


intent.setType("message/rfc822");

// startActivity with intent with chooser as Email client using createChooser function
startActivity(Intent.createChooser(intent, "Choose an Email client :"));
});
}
}
SQLite DATABASE

 SQLite is a Structure query base database, open source, light weight, no network access and standalone
database. It support embedded relational database features.

Whenever an application needs to store large amount of data then using sqlite is more preferable than
other repository system like SharedPreferences or saving data in files.

Android has built in SQLite database implementation. It is available locally over the device(mobile &
tablet) and contain data in text format. It carry light weight data and suitable with many languages. So, it
doesn’t required any administration or setup procedure of the database.
Important Note – The database created is saved in a directory: data/data/APP_Name/databases/DATABASE_NAME.
Constructors of SQLiteOpenHelper class

SQLiteDatabase class
It contains methods to be performed on sqlite database such as create, update, delete, select etc.

Methods of SQLiteDatabase class


There are many methods in SQLiteDatabase class. Some of them are as follows:

Method Description

void execSQL(String sql) executes the sql query not select query.

long insert(String table, String nullColumnHack, inserts a record on the database. The table specifies the table name,
ContentValues values) nullColumnHack doesn't allow completely null values. If second argument is
null, android will store null values if values are empty. The third argument
specifies the values to be stored.

int update(String table, ContentValues values, String updates a row.


whereClause, String[] whereArgs)

Cursor query(String table, String[] columns, String returns a cursor over the resultset.
selection, String[] selectionArgs, String groupBy,
String having, String orderBy)

10.Create/Read/Write with database (SQLite).


Activity_main.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<EditText
android:id="@+id/input_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:hint="Add item"
android:ems="10" />

<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/input_label"
android:layout_centerHorizontal="true"
android:layout_marginTop="67dp"
android:text="Add item" />

<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/btn_add"
android:layout_marginTop="70dp" />
</RelativeLayout>
Mainactivity.java

package com.example.databasepgm1;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.List;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {


Spinner spinner;
Button btnAdd;
EditText inputLabel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = findViewById(R.id.spinner);
btnAdd = findViewById(R.id.btn_add);
inputLabel = findViewById(R.id.input_label);

spinner.setOnItemSelectedListener(this);

// Loading spinner data from database


loadSpinnerData();

btnAdd.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
String label = inputLabel.getText().toString();

if (label.trim().length() > 0) {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
db.insertLabel(label);

// making input filed text to blank


inputLabel.setText("");

// Hiding the keyboard


InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);
// loading spinner with newly added data
loadSpinnerData();
} else {
Toast.makeText(getApplicationContext(), "Please enter label name",
Toast.LENGTH_SHORT).show();
}

}
});
}

/**
* Function to load the spinner data from SQLite database
* */
private void loadSpinnerData() {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
List<String> labels = db.getAllLabels();

// Creating adapter for spinner


ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, labels);

// Drop down layout style - list view with radio button


dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// attaching data adapter to spinner


spinner.setAdapter(dataAdapter);
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
String label = parent.getItemAtPosition(position).toString();

// Showing selected spinner item


Toast.makeText(parent.getContext(), "You selected: " + label,
Toast.LENGTH_LONG).show();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}
}

DatabaseHandler.java

package com.example.databasepgm1;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;

public class DatabaseHandler extends SQLiteOpenHelper {


private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "spinnerExample";
private static final String TABLE_NAME = "labels";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";

public DatabaseHandler(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
// Category table create query
String CREATE_ITEM_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT)";
db.execSQL(CREATE_ITEM_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

// Create tables again


onCreate(db);
}

/**
* Inserting new lable into lables table
* */
public void insertLabel(String label){
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();


values.put(COLUMN_NAME, label);//column name, column value

// Inserting Row
db.insert(TABLE_NAME, null, values);//tableName, nullColumnHack, CotentValues
db.close(); // Closing database connection
}

/**
* Getting all labels
* returns list of labels
* */
public List<String> getAllLabels(){
List<String> list = new ArrayList<String>();

// Select All Query


String selectQuery = "SELECT * FROM " + TABLE_NAME;

SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);//selectQuery,selectedArguments

// looping through all rows and adding to list


if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(1));//adding 2nd column data
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return list;
}
}
Output:

Android Google Map


Android provides facility to integrate Google map in our application. Google map displays your current location, navigate location direction, search location etc. We
can also customize Google map according to our requirement.

Types of Google Maps

There are four different types of Google maps, as well as an optional to no map at all. Each of them gives different view on map. These maps are as follow:
1. Normal: This type of map displays typical road map, natural features like river and some features build by humans.
2. Hybrid: This type of map displays satellite photograph data with typical road maps. It also displays road and feature labels.
3. Satellite: Satellite type displays satellite photograph data, but doesn't display road and feature labels.
4. Terrain: This type displays photographic data. This includes colors, contour lines and labels and perspective shading.
5. None: This type displays an empty grid with no tiles loaded.

Syntax of different types of map


1. googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
2. googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
3. googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
4. googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

Methods of Google map

Google map API provides several methods that help to customize Google map. These methods are as following:

Methods Description

addCircle(CircleOptions options) This method add circle to map.

addPolygon(PolygonOptions options) This method add polygon to map.

addTileOverlay(TileOverlayOptions options) This method add tile overlay to the map.

animateCamera(CameraUpdate update) This method moves the map according to the


update with an animation.

clear() This method removes everything from the


map.

getMyLocation() This method returns the currently displayed


user location.

moveCamera(CameraUpdate update) This method reposition the camera according


to the instructions defined in the update.

setTrafficEnabled(boolean enabled) This method set the traffic layer on or off.

snapshot(GoogleMap.SnapshotReadyCallback This method takes a snapshot of the map.


callback)

stopAnimation() This method stops the camera animation if


there is any progress.

Example of Google Map

Let's create an example of Google map integrating within our app. For doing this we select Google Maps Activity.
Copy the URL from google_map_api.xml file to generate Google map key.

Paste the copied URL at the browser. It will open the following page.
Click on Create API key to generate API key.

After clicking on Create API key, it will generate our API key displaying the following screen.
Copy this generated API key in our google_map_api.xml file

activity_maps.xml

1. <fragment xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:map="http://schemas.android.com/apk/res-auto"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:id="@+id/map"
5. android:name="com.google.android.gms.maps.SupportMapFragment"
6. android:layout_width="match_parent"
7. android:layout_height="match_parent"
8. tools:context="example.com.mapexample.MapsActivity" />

MapsActivity.java

To get the GoogleMap object in our MapsActivity.java class we need to implement the OnMapReadyCallback interface and override the onMapReady() callback
method.

1. package example.com.mapexample;
2.
3. import android.support.v4.app.FragmentActivity;
4. import android.os.Bundle;
5. import com.google.android.gms.maps.CameraUpdateFactory;
6. import com.google.android.gms.maps.GoogleMap;
7. import com.google.android.gms.maps.OnMapReadyCallback;
8. import com.google.android.gms.maps.SupportMapFragment;
9. import com.google.android.gms.maps.model.LatLng;
10. import com.google.android.gms.maps.model.MarkerOptions;
11.
12. public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{
13.
14. private GoogleMap mMap;
15.
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_maps);
20. // Obtain the SupportMapFragment and get notified when the map is ready to be used.
21. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
22. .findFragmentById(R.id.map);
23. mapFragment.getMapAsync(this);
24.
25. }
26.
27. @Override
28. public void onMapReady(GoogleMap googleMap) {
29. mMap = googleMap;
30.
31. // Add a marker in Sydney and move the camera
32. LatLng sydney = new LatLng(-34, 151);
33. mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
34. mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
35.
36. }
37. }

Required Permission

Add the following user-permission in AndroidManifest.xml file.

1. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />


2. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
3. <uses-permission android:name="android.permission.INTERNET" />

AndroidManifest.xml

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


2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. package="example.com.mapexample">
4. <!--
5. The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
6. Google Maps Android API v2, but you must specify either coarse or fine
7. location permissions for the 'MyLocation' functionality.
8. -->
9. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
10. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
11. <uses-permission android:name="android.permission.INTERNET" />
12.
13. <application
14. android:allowBackup="true"
15. android:icon="@mipmap/ic_launcher"
16. android:label="@string/app_name"
17. android:roundIcon="@mipmap/ic_launcher_round"
18. android:supportsRtl="true"
19. android:theme="@style/AppTheme">
20.
21. <meta-data
22. android:name="com.google.android.geo.API_KEY"
23. android:value="@string/google_maps_key" />
24.
25. <activity
26. android:name=".MapsActivity"
27. android:label="@string/title_activity_maps">
28. <intent-filter>
29. <action android:name="android.intent.action.MAIN" />
30.
31. <category android:name="android.intent.category.LAUNCHER" />
32. </intent-filter>
33. </activity>
34. </application>
35.
36. </manifest>

build.gradel

Add the following dependencies in build.gradel file.

1. dependencies {
2. implementation fileTree(dir: 'libs', include: ['*.jar'])
3. implementation 'com.android.support:appcompat-v7:26.1.0'
4. implementation 'com.google.android.gms:play-services-maps:11.8.0'
5. testImplementation 'junit:junit:4.12'
6. androidTestImplementation 'com.android.support.test:runner:1.0.1'
7. androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
8. }

Output

Role of GPS

 GPS stands for Global Positioning System. It's a technology developed by the U.S. Navy and currently
owned (yes, owned) by the U.S. government and overseen by its Air Force.
 GPS is a radio navigation system. It uses radio waves between satellites and a receiver inside your phone
to provide location and time information to any software that needs to use it. You don't have to send any
actual data back into space for GPS to work; you only need to be able to receive data from four or more
of the 28 satellites in orbit that are dedicated for geolocation use.
 Each satellite has its own internal atomic clock and sends a time-coded signal on a specific frequency.
Your receiver chip determines which satellites are visible and unobstructed then starts gathering data
from the satellites with the strongest signals. GPS data is slow, and this is by design — satellites run on
rechargeable batteries, and sending a fast signal hundreds of thousands of miles would require more
power — so it'll take up to a minute to get your geolocation.
 Your phone's GPS receiver uses the data from these signals to triangulate where you are and what time it
is.

You might also like