Breaking News

30.What is Content Provider in android | Accessing the music file from mobile

Introduction of content provider?

ContentProvider,  is a very important component of the Android System and is the one of the  building blocks of Android like Activity  and Intent.

ContentProvider  is our Android system’s middleman, facilitating data interchange between different Android applications

◼In simple words we can say that a ContentProvider  exposes an app’s data for use in that app or in other apps.

Why ContentProvider Is Needed?

◼The need for ContentProvider arises because the database created in one application is not visible to the second application.

◼It is simple to create and store database in different applications using SQLite, however the problem is this, a database in Android is private to the application that creates it. 

There is no common storage area in Android that every application can access. 

◼Therefore, for different applications to use a database, Android system needs an interface that allows such inter-application and inter-process data exchange. 

◼This is where content provider comes to play.

Default ContentProviders Given By Android

⬛Android ships with many useful content providers, including the following:

       ◾Browser—Stores data such as browser bookmarks, browser history, and so on

       ◾CallLog—Stores data such as missed calls, call details, and so on

       ◾Contacts—Stores contact details

       ◾MediaStore—Stores media files such as audio, video, and images

       ◾Settings—Stores the device's settings and preferences

Accessing ContentProvider

⬛To access any ContentProvider from our code we have two options:

       ☐Using The Content URI

       ☐Using Predefined Query String Constant

Using The Content URL

◼To query a content provider, we specify the query string in the form of a Uniform Resource Identifier (URI), with an optional specifier for a particular row.

 ◼Here's the format of the query URI:


◼The various parts of the URI are as follows:

         ⃣  The standard prefix for content providers is always content://.

         ⃣  The authority specifies the name of the content provider. An example would be contacts for the built-in Contacts content provider. For third-party content providers, this could be the fully qualified name, such as or com.whatsapp.provider .

       ☐The data path specifies the kind of data requested. For example, if we are getting all the contacts from the contacts content provider then the data path would be people, and the URI would look like this: content://contacts/people.

      ☐The id specifies the specific record requested. For example, if we are looking for contact number 2 in the contacts content provider, the URI would look like this: content://contacts/people/2.

◼So , the complete statement to create a URI which can be used to access Contacts app data would be:
        ⃣  Uri allContacts = Uri.parse("content://contacts/people");

Some More Content URL

Following are some popular content providers for other built-in apps:

Using Predefined Query String Constant

◼Besides using the query URI, we can use a list of predefined query string constants in Android to specify the URI for the different data types. 

◼For example, besides using the query content://contacts/people, we can rewrite this statement:

        ☐Uri allContacts = Uri.parse("content://contacts/people");
using one of the predefined constants in Android, as follows:

          ⃣   Uri allContacts = ContactsContract.Contacts.CONTENT_URI;

Accessing The Music Files

◼To access audio files from the device , we need to follow below mentioned steps:
Create a Uri object using the content uri "content://media/external/audio/media”

           ⃣  Create an object of ContentResolver using the method getContentResolver( ) of Activity class

         ☐A  Content Provider exposes the apps data to other apps while a ContentResolver is the corresponding class used to resolve the uri , query the underlying database and perform Transactions on those Content Providers.

◼Using ContentResolver object , we call it’s very important  method query( ) .

◼This method accepts the target uri , resolves it to the actual database and return a cursor to the database . 

◼In our case this database would be database for audio files

◼The prototype of the method is:
public Cursor query(Uri uri, String[ ] projection, String selection, String[ ] selectionArgs, String sortOrder)

◼Following are it’s arguments:

        ◾uri: The content uri representing the database to be accessed

        ◾projection: Names of the columns to be accessed, null for all columns

        ◾selection: The search condition containing placeholder, null for all rows

        ◾selectionArgs: The value to be set for placeholder, null if no values to be set

        ◾sortOrder: The column using which sorting is to be done, null if no sorting is to be done

◼Iterate over the cursor object using the method moveToNext( )

◼Fetch the data using cursor objects getXXX( ) methods.

◼All the getXXX( ) methods accept column index as argument , so get the index of the column we also have to call the method getColumnIndex( ) of cursor object which accepts column name and returns the corresponding index.

◼Write the permission
 android.permission.READ_EXTERNAL_STORAGE as well as required code in the java file

The Code

public class MainActivity extends AppCompatActivity {
   protected void onCreate(Bundle savedInstanceState) {
  if (ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
   Toast.makeText(this,"No permission given for reading the SD Card.Requesting the user. . .",Toast.LENGTH_LONG).show();
   ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
        Toast.makeText(this,"App already has the permission",Toast.LENGTH_LONG).show();
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  switch (requestCode) {
   if (grantResults.length > 0&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    Toast.makeText(this,"Permission granted",Toast.LENGTH_LONG).show();
 public void getSongList(){
  ArrayList<String> songRows=new ArrayList<String>();
  String[] requestedColumns = {MediaStore.Audio.Media.TITLE,  MediaStore.Audio.Media.DURATION };
  Uri mediaUri=Uri.parse("content://media/external/audio/media"); 
  // can also be MediaStore.Audio.Media.EXTERNAL_CONTENT_URI ContentResolver resolver=getContentResolver();
  Cursor cur = resolver.query(mediaUri,requestedColumns, null, null, null);
  ListView songsList=(ListView) findViewById(;
  Toast.makeText(this, "Audio files: " + cur.getCount(),Toast.LENGTH_LONG).show();
  int nameindex = cur.getColumnIndex(MediaStore.Audio.Media.TITLE);
  int lengthindex = cur.getColumnIndex(MediaStore.Audio.Media.DURATION);
  while (cur.moveToNext()) {
   String songName=cur.getString(nameindex);
   int lengthsec=cur.getInt(lengthindex)/1000;
   int min=lengthsec/60;
  ArrayAdapter<String> arrayAdpt=new ArrayAdapter<String>(this,R.layout.mylistlayout, songRows);

The OutPut



1 comment: