Fundamentals
Introduction
1st Android Application

OOPS Concepts
Class
Object
Abstraction
Encapsulation

Polymorphism
Inheritance
Message Passing
Dynamic Binding

UI Controls
TextView
Button
Toggle Button
CheckBox
Radio Button
Spinner
ProgressBar
SeekBar
RadioGroup
RatingBar
Switch
EditText
AutoComplete
TextView

MultiAutoComplete
TextView

ImageView
ImageButton
Gallery
MediaPlayer
VideoView
MediaController

TimePicker
DatePicker
CalendarView
Chronometer
Analog Clock
Digital Clock

Layouts
LinearLayout
RelativeLayout
GridLayout
TableLayout
FrameLayout
Fragment

Composite
ListView
ExpandableListView
GridView
ScrollView
SearchView
Sliding Drawer
Tab Widget
WebView

Transitions
Image Switcher
StackView
TextSwitcher
ViewAnimator
View Flipper
View Switcher

Advanced
Request Focus
View
View Stub
TextureView
Gesture Overlay View

SurfaceView
NumberPicker
Zoom Button
Zoom Controls
AbsoluteLayout

Database
SharedPreference
SQLite DB
MySQL DB

Webservices
Check HttpURLConnection
Single Webservice Call
Multi Webservice Call
ListView from Webservice
SQLite from Webservice
Data from Database

Telephone Manager
IMEI
IMSI
Phone Type
Sim Type
Network Type

Content Providers
Contact Provider
BookMark Provider
Own Provider


Message & Networking
Send SMS
SMS with Reports
Group SMS

Send E-Mail
Download Binary Data


Location Based Service
Display Google Map
Events with Google Map

Android Services
Create Service
Create Longtime Service

Asynchronous Task
Repeating Services
IntentService

Activity from a Service
Bind Activity to Service


Sample Projects
HMS
CNB
Login Screen
Camera Event
Browse Option
QR Code Events
Accelerometer Sensor
EditText from Spinner

Android Content Provider

  1. Contact Content Provider Creation in Android
  2. Browser Content Provider Creation in Android
  3. Create and Use your Own Content Provider in Android

Note                     Download ADT Plugin Here.
Here I am using,
OS : Linux (Ubuntu 12.04)
Eclipse : Juno (Version 4.2.0)
Android API Level : 3 to 'n' as per need
Emulator API Level : It will be displayed in output image

A. Contact Content Provider Creation in Android


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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" >
    
    <ListView
        android:id="@+id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    
    <TextView
        android:id="@+id/contactName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        android:textSize="17dp"/>
    
    <TextView
        android:id="@+id/contactID"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textSize="17dp" />
    
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.contentprovider_contacts;
 
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.ListActivity;
import android.database.Cursor;
import android.view.Menu;
import android.widget.SimpleCursorAdapter;
 
public class MainActivity extends ListActivity {
 
    @SuppressWarnings("deprecation")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Uri allContacts = Uri.parse("content://contacts/people");
        Cursor c = managedQuery(allContacts, null, null, null, null);
            
        String[] columns = new String[] {
        		ContactsContract.Contacts.DISPLAY_NAME,
                	ContactsContract.Contacts._ID };
            
        int[] views = new int[] {R.id.contactName, R.id.contactID };
        
        SimpleCursorAdapter adapter = new SimpleCursorAdapter
		(this, R.layout.activity_main, c, columns, views);
        this.setListAdapter(adapter);
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

Step 4 : Open AndroidManifest.xml and add following code :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.contentprovider_contacts"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="15" />
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Step 5 : Open res ->values ->strings.xml and add following code :

<resources>
 
    <string name="app_name">ContentProvider_Contacts</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
 
</resources>

Step 6 : Create Contacts in Emulator like below :


Output

Step 7 : Our output will be like this :


Output









B. Browser Content Provider Creation in Android


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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" >
    
    <ListView
        android:id="@+id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    
    <TextView
        android:id="@+id/Title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        android:textSize="17dp"/>
    
    <TextView
        android:id="@+id/BookMark"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textSize="17dp" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.contentprovider_browser;
 
import android.os.Bundle;
import android.provider.Browser;
import android.app.ListActivity;
import android.database.Cursor;
import android.view.Menu;
import android.widget.SimpleCursorAdapter;
 
public class MainActivity extends ListActivity {
 
 	@SuppressWarnings("deprecation")
	@Override
    	public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.activity_main);
	        
	        Cursor cursor = getContentResolver().query
	        		(Browser.BOOKMARKS_URI, null, null, null, null);
 
	        String s[] = new String[] {
	                Browser.BookmarkColumns.BOOKMARK,
	                Browser.BookmarkColumns.TITLE };
	        int view[] = new int[] {
	                R.id.BookMark, R.id.Title };
 
	        SimpleCursorAdapter adapter = new SimpleCursorAdapter
	        		(this, R.layout.activity_main, cursor, s, view);
	        this.setListAdapter(adapter);	        
        }
 
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
        	return true;
        }    
}

Step 4 : Open AndroidManifest.xml and add following code :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.contentprovider_browser"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="15" />
    <uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS"/>
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

Step 5 : Open res ->values ->strings.xml and add following code :

<resources>
 
    <string name="app_name">ContentProvider_Browser</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
 
</resources>

Step 6 : Our output will be like this :


Output









C. Create and Use your Own Content Provider in Android


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
	<EditText
	    android:id="@+id/txtISBN"
	    android:hint="ISBN"
	    android:textSize="15dp"
	    android:paddingLeft="10dp"
	    android:paddingRight="10dp"  
	    android:layout_height="wrap_content"
	    android:layout_width="fill_parent" />
	 
	<EditText
	    android:id="@+id/txtTitle"
	    android:hint="Title"
	    android:textSize="15dp"
	    android:paddingLeft="10dp"
	    android:paddingRight="10dp"  
	    android:layout_height="wrap_content"
	    android:layout_width="fill_parent" />
	 
	<Button
	    android:text="Add title"
	    android:id="@+id/btnAdd"
	    android:textSize="15dp"
	    android:paddingLeft="10dp"
	    android:paddingRight="10dp"  
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content" />
	 
	<Button
	    android:text="Retrieve titles"
	    android:id="@+id/btnRetrieve"
	    android:textSize="15dp"
	    android:paddingLeft="10dp"
	    android:paddingRight="10dp"  
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content" />
 
</LinearLayout>
    

Step 3 : Open src -> package -> BooksProvider.java and add following code :

package balaji.contentprovider_own;
 
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;
import android.util.Log;
 
public class BooksProvider extends ContentProvider
{
    public static final String PROVIDER_NAME =
        "net.learn2develop.provider.Books";
    public static final Uri CONTENT_URI =
        Uri.parse("content://"+ PROVIDER_NAME + "/books");
    public static final String _ID = "_id";
    public static final String TITLE = "title";
    public static final String ISBN = "isbn";
    private static final int BOOKS = 1;
    private static final int BOOK_ID = 2;
    private static final UriMatcher uriMatcher;
    static{
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(PROVIDER_NAME, "books", BOOKS);
        uriMatcher.addURI(PROVIDER_NAME, "books/#", BOOK_ID);
    }
    //---for database use---
    private SQLiteDatabase booksDB;
    
    private static final String DATABASE_NAME = "Books";
    private static final String DATABASE_TABLE = "titles";
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_CREATE =
            "create table " + DATABASE_TABLE +
            " (_id integer primary key autoincrement, "
            + "title text not null, isbn text not null);";
    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
        @Override
        public void onCreate(SQLiteDatabase db)
        {
            db.execSQL(DATABASE_CREATE);
        }
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion,
        int newVersion) {
            Log.w("Content provider database",
                 "Upgrading database from version " +
                 oldVersion + " to " + newVersion +
                 ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS titles");
            onCreate(db);
        }
    }
    @Override
    public int delete(Uri arg0, String arg1, String[] arg2) {
 
    	// arg0 = uri
        // arg1 = selection
        // arg2 = selectionArgs
        int count=0;
        switch (uriMatcher.match(arg0)){
            case BOOKS:
                count = booksDB.delete(
                        DATABASE_TABLE,
                        arg1,
                        arg2);
                break;
            case BOOK_ID:
                String id = arg0.getPathSegments().get(1);
                count = booksDB.delete(
                        DATABASE_TABLE,
                        _ID + " = " + id +
                        (!TextUtils.isEmpty(arg1) ? " AND (" +
                                arg1 + ')' : ""),
                                arg2);
                break;
            default: throw new IllegalArgumentException("Unknown URI " + arg0);
 
        }
        getContext().getContentResolver().notifyChange(arg0, null);
        return count;
    }
    @Override
    public String getType(Uri uri) {
        switch (uriMatcher.match(uri)){
            //---get all books---
            case BOOKS:
                return "vnd.android.cursor.dir/vnd.learn2develop.books ";
            //---get a particular book---
            case BOOK_ID:
                return "vnd.android.cursor.item/vnd.learn2develop.books ";
            default:
                throw new IllegalArgumentException("Unsupported URI: " + uri);
        }
    }
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        //---add a new book---
        long rowID = booksDB.insert(
            DATABASE_TABLE,
            "",
            values);
        //---if added successfully---
        if (rowID>0)
        {
            Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
            getContext().getContentResolver().notifyChange(_uri, null);
            return _uri;
        }
        throw new SQLException("Failed to insert row into " + uri);
    }
    @Override
    public boolean onCreate() {
        Context context = getContext();
        DatabaseHelper dbHelper = new DatabaseHelper(context);
        booksDB = dbHelper.getWritableDatabase();
        return (booksDB == null)? false:true;
    }
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
        sqlBuilder.setTables(DATABASE_TABLE);
        if (uriMatcher.match(uri) == BOOK_ID)
            //---if getting a particular book---
            sqlBuilder.appendWhere(
 
            		_ID + " = " + uri.getPathSegments().get(1));
        if (sortOrder==null || sortOrder=="")
            sortOrder = TITLE;
        Cursor c = sqlBuilder.query(
                booksDB,
                projection,
                selection,
                selectionArgs,
                null,
                null,
                sortOrder);
        //---register to watch a content URI for changes---
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }
    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        int count = 0;
        switch (uriMatcher.match(uri)){
            case BOOKS:
                count = booksDB.update(
                        DATABASE_TABLE,
                        values,
                        selection,
                        selectionArgs);
                break;
 
            case BOOK_ID:
                count = booksDB.update(
                        DATABASE_TABLE,
                        values,
                        _ID + " = " + uri.getPathSegments().get(1) +
                        (!TextUtils.isEmpty(selection) ? " AND (" +
                            selection + ')' : ""),
                        selectionArgs);
                break;
            default: throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }
}

Step 4 : Open src -> package -> MainActivity.java and add following code :

package balaji.contentprovider_own;
 
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Button btnAdd = (Button) findViewById(R.id.btnAdd);
        
        btnAdd.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
        		//---add a book---
        		ContentValues values = new ContentValues();
                
        		values.put(BooksProvider.TITLE,((EditText) 
                		findViewById(R.id.txtTitle)).getText().toString());
                
        		values.put(BooksProvider.ISBN, ((EditText) 
                		findViewById(R.id.txtISBN)).getText().toString());
                
        		Uri uri = getContentResolver().insert(
                    		BooksProvider.CONTENT_URI, values);
 
        		Toast.makeText(getBaseContext(),uri.toString(),
                		Toast.LENGTH_LONG).show();
		}
	});

        Button btnRetrieve = (Button) findViewById(R.id.btnRetrieve);
        
        btnRetrieve.setOnClickListener(new View.OnClickListener() {
        	@SuppressWarnings("deprecation")
        	public void onClick(View v) {
        		//---retrieve the titles---
        		Uri allTitles = Uri.parse(
				"content://net.learn2develop.provider.Books/books");
        		Cursor c = managedQuery(allTitles, null, null, null,
				"title desc");
        		if (c.moveToFirst()) {
        			do{
        				Toast.makeText(getBaseContext(), "ContentProviders "+ 
        				c.getString(c.getColumnIndex(
					BooksProvider._ID)) + ", " +
					c.getString(c.getColumnIndex(
					BooksProvider.TITLE)) + ", " +
					c.getString(c.getColumnIndex(
					BooksProvider.ISBN))+"", Toast.LENGTH_LONG).show();
        			} while (c.moveToNext());
        		}
        	}
        });
    }
                		
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }    
}

Step 5 : Open AndroidManifest.xml and add following code :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.contentprovider_own"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="15" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider android:name="BooksProvider"
                android:authorities="net.learn2develop.provider.Books" />
        
    </application>
 
</manifest>

Step 6 : Open res ->values ->strings.xml and add following code :

<resources>
 
    <string name="app_name">ContentProvider_Own</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
 
</resources>

Step 7 : Our output will be like this :


Output


Output









SHARE THIS PAGE



product 2

product 3

product 4

Feedbacks : balaji.scz@gmail.com