Android Development ContentProvider Get a list of songs and examples of contacts

Source: Internet
Author: User

ContentProvider (content Provider) is one of the four components of Android. Mainly used to share data externally, that is, by contentprovider the data in the application to other applications access, other applications can be contentprovider to the data in the specified application. ContentProvider are divided into systematic and customized systems, such as contacts, pictures and other data.

The following is a general overview of ContentProvider in Google Docs.
The content provider uses some specific application data to feed other applications. Data can be stored in a file system, SQLite database, or other means. The content provider inherits from the ContentProvider base class and implements a standard set of methods for other applications to fetch and store the data it manages. However, the application does not call these methods directly, but instead uses a Contentresolver object that invokes its method as an alternative. Contentresolver can work with any content provider to manage all relevant interactive communications.

1.ContentProvider
Android provides some of the main data types of contentprovider, such as audio, video, pictures, and personal contacts. Some Android-provided ContentProvider can be found under the Android.provider package. By obtaining these contentprovider, you can query the data they contain, as long as the appropriate read permissions have been obtained.
Main Method:
public boolean onCreate () calls
Public Cursor query (Uri, string[], String, string[] when creating ContentProvider, String) to query the ContentProvider of the specified URI, returning a cursor
public URI Insert (URI, contentvalues) for adding data to the contentprovider of the specified URI
public int Update (URI, Contentvalues, String, string[]) is used to update the data in the contentprovider of the specified Uri
public int Delete (URI, String, string[]) is used to remove data from the ContentProvider of the specified URI
public String getType (URI) to return the MIME type of the data in the specified URI
* If the data of the operation belongs to the collection type, then the MIME type string should start with vnd.android.cursor.dir/.
For example: To get the URI for all person Records is Content://contacts/person, the MIME type string returned is "Vnd.android.cursor.dir/person".
* If the data to be manipulated belongs to non-collection type data, the MIME type string should start with vnd.android.cursor.item/.
For example: To get the URI for the person record with ID 10 is CONTENT://CONTACTS/PERSON/10, the MIME type string returned should be "Vnd.android.cursor.item/person".

2.ContentResolver
When external applications need to add, delete, modify, and query the data in ContentProvider, you can use the Contentresolver class to get the Contentresolver object, You can use the Getcontentresolver () method provided by the context.

View Plaincopy to Clipboardprint?

Contentresolver CR = Getcontentresolver ();


The methods provided by Contentresolver and the methods provided by ContentProvider correspond to the following methods.
The public URI insert (URI uri, contentvalues values) is used to add data to the ContentProvider of the specified URI.
The public int Delete (URI Uri, String selection, string[] selectionargs) is used to delete data from the ContentProvider of the specified Uri.
The public int update (URI uri, contentvalues values, String selection, string[] selectionargs) is used to update the data in ContentProvider of the specified Uri.
Public Cursor query (URI uri, string[] projection, string selection, string[] Selectionargs, string sortOrder) for querying the CO of the specified Uri Ntentprovider.

3.Uri
The URI specifies the ContentProvider to be manipulated, in fact a URI can be considered as a URL, we divide the URI into three parts.
The first part is "content://". Can be viewed as the "http://" in the URL.
The second part is the hostname or authority, which uniquely identifies the contentprovider, and the external application needs to find it based on this identity. Can be viewed as the hostname in the URL, such as "blog.csdn.net".
The third part is the path name, which is used to represent the data that will be manipulated. Can be thought of as a broken-down content path in URLs.


Find all the song information on the SDcard card
Public List> Getmultidata () {
ArrayList> musiclist = new ArrayList> ();

Add code to encapsulate music information
Find All songs
Contentresolver musicresolver = This.getcontentresolver ();
Cursor musiccursor = Musicresolver.query (
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, NULL, NULL, NULL,
NULL);

int musiccolumnindex;

if (null! = Musiccursor && musiccursor.getcount () > 0) {
For (Musiccursor.movetofirst ();!musiccursor.isafterlast (); musiccursor
. MoveToNext ()) {
Map Musicdatamap = new HashMap ();

Random random = new random ();
int musicrating = Math.Abs (Random.nextint ())% 10;

Musicdatamap.put ("musicrating", musicrating);

Get the Music playback path
Musiccolumnindex = Musiccursor
. Getcolumnindex (MediaStore.Audio.AudioColumns.DATA);
Musicpath = musiccursor.getstring (Musiccolumnindex);
Musicdatamap.put ("Musicpath", Musicpath);

Get the name of the music
Musiccolumnindex = Musiccursor
. Getcolumnindex (MediaStore.Audio.AudioColumns.TITLE);
Musicname = musiccursor.getstring (Musiccolumnindex);
Musicdatamap.put ("Musicname", musicname);

Get the album name of the music
Musiccolumnindex = Musiccursor
. Getcolumnindex (MediaStore.Audio.AudioColumns.ALBUM);
Musicalbum = musiccursor.getstring (Musiccolumnindex);
Musicdatamap.put ("Musicalbum", musicalbum);

The singer who gets the music
Musiccolumnindex = Musiccursor
. Getcolumnindex (MediaStore.Audio.AudioColumns.ARTIST);
Musicartist = musiccursor.getstring (Musiccolumnindex);
Musicdatamap.put ("Musicartist", musicartist);

Get the key for the album corresponding to the song
Musiccolumnindex = Musiccursor
. Getcolumnindex (MediaStore.Audio.AudioColumns.ALBUM_KEY);
Musicalbumkey = musiccursor.getstring (Musiccolumnindex);

String[] Argarr = {Musicalbumkey};
Contentresolver albumresolver = This.getcontentresolver ();
Cursor albumcursor = Albumresolver.query (
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, NULL,
MediaStore.Audio.AudioColumns.ALBUM_KEY + "=?",
Argarr, NULL);

if (null! = Albumcursor && albumcursor.getcount () > 0) {
Albumcursor.movetofirst ();
int albumartindex = Albumcursor
. Getcolumnindex (MediaStore.Audio.AlbumColumns.ALBUM_ART);
Musicalbumartpath = albumcursor.getstring (Albumartindex);
if (null! = Musicalbumartpath
&& "". Equals (Musicalbumartpath)) {
Musicdatamap.put ("Musicalbumimage", Musicalbumartpath);
} else {
Musicdatamap.put ("Musicalbumimage",
"File:///mnt/sdcard/alb.jpg");
}
} else {
No album definition, give default picture
Musicdatamap.put ("Musicalbumimage",
"File:///mnt/sdcard/alb.jpg");
}
Musiclist.add (MUSICDATAMAP);
}
}
return musiclist;
}

The following is a contentprovider reading of the contact data, which belongs to the system data. Full code Download: Android_contentprovider_system.rar

Note: The contact operation here is a bit messy, the key is that I am not very familiar with the SDK1.6 and SDK2.1 contact operation is very different, I hope that the hero pointing.

View Plaincopy to Clipboardprint?

public class Mainactivity extends Activity {

Private EditText Nameet;

Private EditText Numberet;

Private Button insertbtn;

Private Button deletebtn;

Private Button querybtn;

Private ListView Contentview;

@Override

public void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.main);

Nameet = (EditText) Findviewbyid (r.id.name);

Numberet = (EditText) Findviewbyid (R.id.number);

INSERTBTN = (Button) Findviewbyid (R.id.insert);

DELETEBTN = (Button) Findviewbyid (r.id.delete);

QUERYBTN = (Button) Findviewbyid (r.id.query);

Used to display data

Contentview = (ListView) Findviewbyid (r.id.content);

Insertbtn.setonclicklistener (New Operateonclicklistener ());

Deletebtn.setonclicklistener (New Operateonclicklistener ());

Querybtn.setonclicklistener (New Operateonclicklistener ());

}

Class Operateonclicklistener implements Onclicklistener {

@Override

public void OnClick (View v) {

String name = Nameet.gettext (). toString ();

String number = Numberet.gettext (). toString ();

Person p = new person (name, number);

Switch (V.getid ()) {

Inserting data

Case R.id.insert:

Insert (p);

View ();

Break

Delete data

Case R.id.delete:

Delete (name);

View ();

Break

Querying data

Case R.id.query:

View ();

Break

}

}

}

Show data

private void View () {

Cursor c = Query ("");

ListAdapter listadapter = new Simplecursoradapter (this, r.layout.list,

C, new string[] {people._id, people.name, People.number},

New int[] {r.id.id, r.id.name, r.id.number});

Contentview.setadapter (ListAdapter);

}

Insert Contact

private void Insert (person p) {

Get Contentresolver Object

Contentresolver CR = Getcontentresolver ();

Contentvalues values = new Contentvalues ();

Values.put (People.name, p.name);

Indicates whether to add a contact to the collection (asterisking), 1 to join, 0 to not join, this line of code comment is not joined by default.

Values.put (Contacts.People.STARRED, 1);

Uri uri = Contacts.People.createPersonInMyContactsGroup (CR, values);

Get the URI of the contact people table

Uri url = uri.withappendedpath (URI,

Contacts.People.Phones.CONTENT_DIRECTORY);

Values.clear ();

Values.put (Contacts.Phones.TYPE, Contacts.Phones.NUMBER);

Values.put (Contacts.Phones.NUMBER, P.number);

Insert operation

Cr.insert (URL, values);

}

Insert Contact

private void Delete (String name) {

Get Contentresolver Object

Contentresolver CR = Getcontentresolver ();

Uri url = Contacts.People.CONTENT_URI;

Set deletion criteria

String where = people.name + "=?";

String[] Selectionargs = {name};

Cr.delete (URL, where, Selectionargs);

}

Query Contact

Private Cursor Query (String name) {

Get Contentresolver Object

Contentresolver CR = Getcontentresolver ();

Uri uri = Contacts.People.CONTENT_URI;

Querying objects

string[] projection = {people._id, people.name, people.number};

Set the query criteria, where I set the selection and Selectionargs parameters to null, which means querying all data

String selection = null;

string[] Selectionargs = null;

if (! "". Equals (name)) {

Selection = People.name + "=?";

Selectionargs = new string[] {name};

}

Set sorting criteria

String sortOrder = contacts.people._id;

Cursor C = cr.query (URI, projection, selection, Selectionargs,

SortOrder);

if (C.movetofirst ()) {

for (int i = 0; i < C.getcount (); i++) {

C.movetoposition (i);

String name = c.getstring (C.getcolumnindexorthrow (people.name));

String number = C.getstring (c

. Getcolumnindexorthrow (People.number));

// }

// }

return C;

}

}

Android Development ContentProvider Get a list of songs and examples of contacts

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.