You are on page 1of 5

www.giaotrinhcntt.

com
www.giaotrinhcntt.com

Android Content Provider


Cui tun rnh ri hn, nh ra l phi tip tc vit Tutorial cho din n, rt nhiu
cc Newbies ang cn
Trc khi vo bi, cc bn down Sourcecode ca bi hc ti y
Sourcecode ca bi hc bao gm 3 Project demo :
ContentProviderDemo
ContentProviderDemo1
ContentProviderDemo2
Mi Demo s gii quyt tng vn ca Tutorial. Cc bn c add ht vo
workspace tin theo di.
1. Gii thiu Content Provider
Content Provider l 1 trong 4 thnh phn c bn ca 1 ng dng Android thng
c bao gm:
1. Activity
2. Service
3. Broadcast Receiver
4. Content Provider
Mt Content Provider cung cp mt tp chi tit d liu ng dng n cc ng dng
khc. Thng c s dng khi chng ta mun to c s d liu di dng public
(cc ng dng khc c th truy xut ).
D liu thng c lu tr file h thng, hoc trong mt SQLite database.
n gin cc bn c th hnh dung nh : Danh b, Call log, cu hnh ci
t...trn in thoi l d liu di dng Content Provider.

www.giaotrinhcntt.com
www.giaotrinhcntt.com

Content Provider hin thc mt tp phng thc chun m cc ng dng khc c


th truy xut v lu tr d liu ca loi n iu khin.
Tuy nhin, nhng ng dng khng th gi cc phng thc trc tip. Hn th
chng dng lp Content Resolver v gi nhng phng thc . Mt Content
Resolver c th giao tip n nhiu content provider; n cng tc vi cc provider
qun l bt k giao tip bn trong lin quan.
n gin hn, chng ta c th lm 1 ng dng nh ly tt c cc thng tin cu
hnh trong my load ln listview. Cc bn c th chy Project
ContentProviderDemo1 trong SourcecodeDemo.

www.giaotrinhcntt.com
www.giaotrinhcntt.com

Chng ta c th tm hiu s qua v code ca demo ny, rt ngn gn

www.giaotrinhcntt.com
www.giaotrinhcntt.com

M:
ContentResolver cr = getContentResolver();
Cursor cursor =
cr.query(Settings.System.CONTENT_URI, null, null, null,
null);
startManagingCursor(cursor);
ListView listView = (ListView)
findViewById(R.id.listView);
String[] from = { Settings.System.NAME,
Settings.System.VALUE };
int[] to = { R.id.textName, R.id.textValue };
SimpleCursorAdapter adapter = new
SimpleCursorAdapter(this, R.layout.row, cursor, from,
to);
listView.setAdapter(adapter);
Nh cc bn thy, ch cn 2 dng code n gin ly c con tr thao tc trn
tp d liu cn ly:
M:
ContentResolver cr = getContentResolver();
Cursor cursor =
cr.query(Settings.System.CONTENT_URI, null, null, null,
null);
Lp Content Resolver cung cp cc phng thc x l d liu thng qua cc Uri,
mi Content Provider c 1 Uri c th , y Uri Settings.System.CONTENT_URI
s tr li tp d liu l thng tin cu hnh ca thit b.
Sau khi ly c con tr ti tp d liu, vic cn li n gin l bind data ln
listview hin th:

www.giaotrinhcntt.com
www.giaotrinhcntt.com

M:
startManagingCursor(cursor);
ListView listView = (ListView)
findViewById(R.id.listView);
String[] from = { Settings.System.NAME,
Settings.System.VALUE };
int[] to = { R.id.textName, R.id.textValue };
SimpleCursorAdapter adapter = new
SimpleCursorAdapter(this, R.layout.row, cursor, from,
to);
listView.setAdapter(adapter)

You might also like