Android ContentProvider Example

Android ContentProvider Example

This is a ContentProvider tutorial. Through various examples you will learn how to use contentprovider to load data from an android device. ContentProvider is one of android’s fundamental components, alongside activity, service, application and broadcastreceiver. As such it is important for your android development journey.

Example 1 – How to Load Contacts from the device.

This example examines how to use content provider to load contacts from any android device.

Step 1: Dependencies

No third party dependency is needed.

Step 2: Add Permissions

To read contacts from a user’s device, you need permission from the user. Thus you need to add the READ_CONTACTS permission which will be shown to the user when the user is installing your app.

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

Step 3: Design UI

The UI will comprise a button a listview. The user presses the button and contacts are fetched and loaded onto the listview.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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="com.parag.contentprovidersample.MainActivity">

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get contact names"
        android:layout_margin="10dp"
        />

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/btn"
        android:layout_margin="10dp"/>

</RelativeLayout>

Step 3: Write Code

The code is in java but can be converted to kotlin.

MainActivity.java

Add imports including the LoaderManager and cursorLoader:

import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;

Extend the appcompactivity and implement several interfaces including the LoaderManager.LoaderCallbacks<Cursor>:

public class MainActivity extends AppCompatActivity implements View.OnClickListener,LoaderManager.LoaderCallbacks<Cursor>{

Declare our UI widgets as well as projection:

    Button button;
    ListView listView;
    String[] projection = {ContactsContract.Contacts.DISPLAY_NAME};
    boolean hasLoaded;

Here’s the rest of the code:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button)findViewById(R.id.btn);
        listView = (ListView)findViewById(R.id.listview);
        button.setOnClickListener(this);

    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { // CursorLoader instance
        Uri uri = ContactsContract.Contacts.CONTENT_URI;
        String orderBy = ContactsContract.Contacts.DISPLAY_NAME_PRIMARY;
        if(i == 1) {
            return new CursorLoader(this,uri ,projection,null,null,orderBy);
        }
        else
        {
            return null;
        }
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {

        ArrayList<String> contactList = new ArrayList<>();
        if(cursor != null && cursor.getCount() > 0)
        {
            while(cursor.moveToNext())
            {
                contactList.add(cursor.getString(0));
            }
            ArrayAdapter<String> contactArrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,contactList);
            listView.setAdapter(contactArrayAdapter);
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId())
        {
            case R.id.btn:
                if(!hasLoaded)
                {
                    getLoaderManager().initLoader(1,null,this);
                    hasLoaded = true;
                }
                else
                {
                    getLoaderManager().restartLoader(1,null,this);
                }
        }
    }
}

Reference

No. Name
1. Download Now
2. Visit Author

BEFORE YOU GO

YOU'VE BEEN SELECTED FOR A GIFT

Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .

Related Examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*

code