Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

Content Provider

In Android, Every Application is treated as a separate process.

The Process can have database for saving its data into tables.

Take a scenario where App 2 wants to access App1’s database. Direct access is not allowed because
database is private to the App1.
Content Provider

As the database is private, The legal way to get that data is to request data from app1 and in response
App2 will get data. The question is how App1 will provide data to App2 in secure Manner. To solve this
question, a new component comes into picture i.e. Content Provider

App2 will use an API ContentResolver using which it will hit the database and the content provider
defined in the app1 will respond back with the data requested in the form of cursor.
Content Provider

Here Content Provider is providing a kind of Abstraction.

In real world example,

ContentResolver resolver=getContentResolver(); // creates the object of ContentResolver

Uri which is unique of every Content provider. Eg.


Uri uri= ContactsContract.CommonDataKinds.Phone.CONTENT_URI;// uri for accesing
Contacts App database.
Content Provider

Cursor cursor=resolver.query(uri,projection,selection,selectionargs,sortorder);
Data returned by the content provider is going to parse by cursor.

Through the object of cursor we can browse data row by row using
Cursor.moveToNext()

Example: Uri uri= ContactsContract.CommonDataKinds.Phone.CONTENT_URI;


Content Provider

projection= set of columns to which u want to query. It’s a String array


//String[] projection= {
Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER};
Selection= where clause in sql .its a String type
Selectionargs= (No exact equivalent. Selection arguments replace ? placeholders in the
selection clause.). Filter kind of effect It is String Array type
Sortorder= orderby in sql. It is String type

If cursor is having some data then only we will try to retrieve data

Fetching all the records of Name and phone no. from the database of Contact
application of our device through the use of Content provider .

package com.example.content_provider_example;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {


ListView listView;
Content Provider

ArrayAdapter arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=findViewById(R.id.listcontact);
fetch_contact();
}
private void fetch_contact()
{
ArrayList<String> contacts=new ArrayList<>();

ContentResolver resolver=getContentResolver();
Uri uri= ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String mselection=ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+"=?";
String [] mselectionargs= new String []{"Harjinder"};
String selection =null;
String[] projection=
{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds
.Phone.NUMBER};
String[] selectionargs=null;
String sortorder=null;
String msortorder=ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;

Cursor
cursor=resolver.query(uri,projection,mselection,mselectionargs,msortorder);

while(cursor.moveToNext()) {

String name=
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLA
Y_NAME));
String
number=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.
NUMBER));
contacts.add(name+"\t"+number);
}
arrayAdapter=new
ArrayAdapter(this,android.R.layout.simple_list_item_1,contacts);
listView.setAdapter(arrayAdapter);
}
}

<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
Paste these two lines for permission before or after <Application> tag in Manifest
file.
Content Provider

How to create your own Content provider:

Application 1 --Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sqlite_demo">

<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/AppTheme">
<provider
android:name=".MyContentProvider"
android:authorities="Com.Own.Provider" // uri provided here
android:enabled="true"
android:exported="true"></provider>

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


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

</manifest>

Application 1 –DbHelper.java
package com.example.sqlite_demo;

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

import androidx.annotation.Nullable;

public class DbHelper extends SQLiteOpenHelper {


public static final String DB_NAME = "CCSIT";
public static final int DB_VERSION = 1;
public static final String COL_NAME ="NAME" ;
public static final String DROP_TABLE ="DROP TABLE IF EXISTS " +
TableDbContract.StuTable.TABLE_NAME ;
Content Provider

public static final String COL_PHONE ="PHONE";


SQLiteDatabase sqLiteDatabase;

public DbHelper(Context context) {


super(context,DB_NAME, null,DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
String create_table="CREATE TABLE "+ TableDbContract.StuTable.TABLE_NAME
+"("+ TableDbContract.StuTable.COL_ID +" INTEGER PRIMARY KEY,"+
TableDbContract.StuTable.COL_NAME +" TEXT,"+ TableDbContract.StuTable.COL_PHONE +"
TEXT)";
db.execSQL(create_table);

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
onCreate(db);

}
public void insertRecord(String name,String phone)
{
sqLiteDatabase=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(COL_NAME,name);
values.put(COL_PHONE,phone);
sqLiteDatabase.insert(TableDbContract.StuTable.TABLE_NAME,null,values);
sqLiteDatabase.close();
}
}

Application 1 –TableDbContract.java
package com.example.sqlite_demo;

import android.provider.BaseColumns;
public class TableDbContract {

public class StuTable implements BaseColumns {

public static final String TABLE_NAME = "STUDENT";


public static final String COL_ID = "ID";
public static final String COL_NAME = "NAME";
public static final String COL_PHONE = "PHONE";
}
}
Content Provider

Application 1 –MyContentProvider.java

package com.example.sqlite_demo;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

public class MyContentProvider extends ContentProvider {


private DbHelper helper;
public MyContentProvider() {
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// Implement this to handle requests to delete one or more rows.
throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public String getType(Uri uri) {
// TODO: Implement this to handle requests for the MIME type of the data
// at the given URI.
throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO: Implement this to handle requests to insert a new row.
throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public boolean onCreate() {
helper=new DbHelper(getContext());
return true;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[]
selectionArgs, String sortOrder)
{
Cursor cursor=
helper.getReadableDatabase().query(TableDbContract.StuTable.TABLE_NAME,projection,sel
ection,selectionArgs,null,null,sortOrder);
return cursor;
}

@Override
public int update(Uri uri, ContentValues values, String selection,
Content Provider

String[] selectionArgs) {
// TODO: Implement this to handle requests to update one or more rows.
throw new UnsupportedOperationException("Not yet implemented");
}
}

Now lets move to Application2

MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayAdapter arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=findViewById(R.id.listcontact);
fetch_contact();
}
private void fetch_contact()
{
ArrayList<String> contacts=new ArrayList<>();

ContentResolver resolver=getContentResolver();

Uri uri= Uri.parse("content://Com.Own.Provider"+"/"+"STUDENT");

Cursor cursor=resolver.query(uri,null,null,null,null);

while(cursor.moveToNext()) {
int id=cursor.getInt(cursor.getColumnIndex("ID"));
String name= cursor.getString(cursor.getColumnIndex("NAME"));
String number=cursor.getString(cursor.getColumnIndex("PHONE"));
contacts.add(id+"\t"+name+"\t"+number);
}
arrayAdapter=new
ArrayAdapter(this,android.R.layout.simple_list_item_1,contacts);
listView.setAdapter(arrayAdapter);
}
}
Content Provider

activity_man.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ListView
android:id="@+id/listcontact"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

</LinearLayout>

Application 2 is accessing Student table of Application 1. Above is the


output .

That’s how we can create our own Content provider.

You might also like