Unit 4 - MAD
Unit 4 - MAD
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−
<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>
@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());
Toast.makeText(getBaseContext(),
uri.toString(), Toast.LENGTH_LONG).show();
}
public void onClickRetrieveStudents(View view) {
// Retrieve student records
String URL = "content://com.example.PG8.StudentsProvider";
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;
/**
* Database specific constant declarations
*/
/**
* Helper class that actually creates and manages
* the provider's underlying data repository.
*/
@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;
}
@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:
}
<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" />
</manifest>
Output:
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
Activity_Main.xml
<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
<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" />
</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:
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.
<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" />
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
// 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.
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.
Cursor query(String table, String[] columns, String returns a cursor over the resultset.
selection, String[] selectionArgs, String groupBy,
String having, String orderBy)
<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;
spinner.setOnItemSelectedListener(this);
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);
}
});
}
/**
* Function to load the spinner data from SQLite database
* */
private void loadSpinnerData() {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
List<String> labels = db.getAllLabels();
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
String label = parent.getItemAtPosition(position).toString();
@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;
// 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);
/**
* Inserting new lable into lables table
* */
public void insertLabel(String label){
SQLiteDatabase db = this.getWritableDatabase();
// 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>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);//selectQuery,selectedArguments
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.
Google map API provides several methods that help to customize Google map. These methods are as following:
Methods Description
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
AndroidManifest.xml
build.gradel
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.