SlideShare ist ein Scribd-Unternehmen logo
1 von 23
Workshop India
» Content providers allow programs access to data
  which is present on the device.

» A content provider manages access to a central
  repository of data.

» They encapsulate the data from tables, and provide
  mechanisms for defining data security and unified
  usage.

» Content providers are the standard interface that
  connects data in one process with code running in
  another process.
Content Provider   Intended Data
Browser            Browser bookmarks, browser
                   history, etc.
CallLog            Missed calls, call details, etc.
Contacts           Contact details
MediaStore         Media files such as audio, video
                   and images
Settings           Device settings and preferences
» Irrespective of how the data is stored, Content
  Providers give a uniform interface to access the data.

» Data is exposed as a simple table with rows and
  columns where row is a record and column is a
  particular data type with a specific meaning.

» Each record is identified by a unique _ID field which is
  the key to the record.

» Each content provider exposes a unique URI that
  identifies its data set uniquely. URI == table-name
» First we need to create a layout and activity class.

» In our layout we need to create a ListView.

» Create a cursor to query the phone database for
  the contacts..

» Use an adaptor to send the results to the view for
  displaying
» An application accesses the data from a content
  provider with a ContentResolver client object.

» The ContentResolver methods provide the basic
  "CRUD" (create, retrieve, update, and delete)
  functions of persi

          // Queries the user dictionary and returns results
          mCursor = getContentResolver().query(
             UserDictionary.Words.CONTENT_URI, // The content URI of the words table
             mProjection,                       // The columns to return for each row
             mSelectionClause                     // Selection statement
             mSelectionArgs,                    // Selection criteria
             mSortOrder);                        // The sort order for the returned rows
» A content URI is a URI that identifies data in a
  provider.

» Content URIs include the symbolic name of the
  entire provider (its authority) and a name that
  points to a table (a path).

» content://user_dictionary/words
» To retrieve data from a provider, your application
  needs "read access permission" for the provider in
  androidmanifest.xml.

» Construct the query
   ˃ A "projection" defines the columns that will be returned for each row

   ˃ Do a query and return a cursor object which holds the result returned from the
     database


» Read the result with the cursor implementation
   ˃   you can iterate over the rows in the results
   ˃   determine the data type of each column
   ˃   get the data out of a column
   ˃   And more!
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <ListView android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
</LinearLayout>
                         This would create a listView of id list in the layout.
» Cursor is an interface that provides random read-write access
  to the result of a database query from a content provider.

» A cursor is a collection of rows

» All field access methods are based on column number. You have
  to convert column name to a column number first

» Random means (you can move forward and backwards)

» You can also find size / traverse result set easily.

             Cursor cur;
             for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext()) {
             //access methods
             }
» Since a Cursor is a "list" of rows, a good way to
  display the contents of a Cursor is to link it to
  a ListView via an adaptor.


       // Creates a new SimpleCursorAdapter
       mCursorAdapter = new SimpleCursorAdapter(
          getApplicationContext(),          // The application's Context object
          R.layout.wordlistrow,           // A layout in XML for one row in the ListView
          mCursor,                           // The result from the query
          mWordListColumns,               // A string array of column names in the cursor
          mWordListItems,                   // An integer array of view IDs in the row layout
          0);                               // Flags (usually none are needed)

       // Sets the adapter for the ListView
       mWordList.setAdapter(mCursorAdapter);
Since our activity consists of a list, we can extend the class
public class MyActivity extends ListActivity
                                                       ListActivity to make life easier.
{
  ListView lv;
  Cursor Cursor1;        lv is used to manage the Listview, note that since the layout contains only one listview,
                       the extend ListActivity is enough for the connection.
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);                    A projection is the specific columns of the
    setContentView(R.layout.main);                         table that we want to query.
    String [] projection = new String[] { Phone.DISPLAY_NAME,
         Phone.NUMBER,
         Phone._ID                                  getContentResolver() – returns a ContentResolver object
    };                                              from the activity class that can be used to query the
                                                 content databases with
    Cursor1 = getContentResolver().query(        query(projection, selection, selectionargs, sortorder)
        Phone.CONTENT_URI,
        projection,
        null,
        null,                                Phone.CONTENT_URI :
        Phone.DISPLAY_NAME + " ASC");        (android.provider.ContactsContract.CommonDataKinds.Phone)
                                             Points to the contact database location
    startManagingCursor(Cursor1);
startManagingCursor(Cursor1);         From and to are used to convert between the
                                                  result of the query in the cursor to the textview’s
            String[] from = {                     in a list layout
            Phone.DISPLAY_NAME,
            Phone.NUMBER,
                                                                               SimpleCursorAdapter maps columns
            Phone._ID};                                                        from a cursor to TextViews or
                                                                               ImageViews defined in an XML file.
            int[] to = {android.R.id.text1, android.R.id.text2};               Cursor1, from, to are the respective data
                                                                               args
            SimpleCursorAdapter listadapter = new SimpleCursorAdapter(this,
                                        android.R.layout.simple_list_item_2,
                                        Cursor1, from, to );

             setListAdapter(listadapter);
                                                             android.R.layout.simple_list_item_2 is an inbuilt
            lv = getListView();                              layout with 2 textviews for a list.

                                                             A custom XML layout in res/layout can be inserted
} // onCreate ends here
                                                             here too with the id names of the textveiws replaced
                                                             in the to variable.
[…]

                                                                Get the cursor object and
cursor = managedQuery(EXTERNAL_CONTENT_URI,                     perform the query on it
                  proj, selection, arg, sort);

                                                   Find the listview view from
list = (ListView) findViewById(R.id.List01);       the view


list.setAdapter(new N_Adapter(getApplicationContext(), cursor));

[..]
                              Use this function to bind the listview to an adaptor of
                              class N_Adapter..

                              The function is taking a constructor to this class as
                              arguments
public class N_Adapter extends BaseAdapter {     This class extends BaseAdapter which is the base
    private Context mContext;                    class for all adapter implementations
    Cursor cursor;

    public N_Adapter(Context c,Cursor m) {      This constructor takes in the arguments passed to it
      mContext = c;                             and returns the object to the setadapter method.
      cursor = m;
    }

    public int getCount() {
      return count;
    }

    public Object getItem(int position) {
      return position;                         These functions are required for the adapter to work
    }                                          properly within the android subsystem

    public long getItemId(int position) {
      return position;
    }
This function performs
                                                                                               the binding between the
public View getView(int position, View convertView, ViewGroup parent) {                        cursor and the listview.
      TextView tv;
      View row;                                         The view row is used to hold the xml file to place the
      LayoutInflater inflater = getLayoutInflater();    listview’s contents in.

          if (convertView == null) {                                     convertView is in case the inflated view is being
             row = inflater.inflate(android.R.layout.item, null);        passed in as arguments, in this case – we don’t
         } else                                                          want to inflate again..
             row = convertView;                                          android.R.layout.item -> xml file for the list
                                                                         elements
         tv = (TextView) row.findViewById(R.id.TextView01);

         cursor.moveToPosition(position);
         music_column_index = cursor .getColumnIndexOrThrow(People.DISPLAY_NAME);
         id = cursor.getString(music_column_index);
                                                                    Cursor is a class member initialized by the
         tv.setText(id);                                            argument to the constructor, these lines extract
         return row;                                                the data required and pass it to the textView
     }                                                              element in the listview XML file.
 }
» Create a large text white background contacts list.

» Attach an on click event to each list item and open
  a new activity that shows that contact’s details

» Make an application that allows you to enter a
  phrase and searches through the SMS messages
  for all sms’s containing that text.
» Make a edittext view in a layout and load it in
  activity.

» Make a button and bind an onclickhandler() to it

» When the button is clicked, load sms from the
  content provider and search the contents for all
  messages containing that word.

» Display all messages (one by one or in a listview as
  per your choice)
» <uses-permission
  android:name="android.permission.READ_SMS"></uses-permission>
» <uses-permission
  android:name="android.permission.READ_CONTACTS"></uses-
  permission>


»   URI for sms content providers is as follows
»   Inbox = "content://sms/inbox"
»   Failed = "content://sms/failed"
»   Queued = "content://sms/queued"
»   Sent = "content://sms/sent"
»   Draft = "content://sms/draft"
»   Outbox = "content://sms/outbox"
»   Undelivered = "content://sms/undelivered"
»   All = "content://sms/all"
»   Conversations = "content://sms/conversations"
»   addressCol= mCurSms.getColumnIndex("address");
»   personCol= mCurSms.getColumnIndex("person");
»   dateCol = mCurSms.getColumnIndex("date");
»   protocolCol= mCurSms.getColumnIndex("protocol");
»   readCol = mCurSms.getColumnIndex("read");
»   statusCol = mCurSms.getColumnIndex("status");
»   typeCol = mCurSms.getColumnIndex("type");
»   subjectCol = mCurSms.getColumnIndex("subject");
»   bodyCol = mCurSms.getColumnIndex("body");
» Uri uri = Uri.parse("content://sms/inbox");

» Cursor c= getContentResolver().query(uri, null,
  null ,null,null);

» startManagingCursor(c)
body = new String[c.getCount()];
number = new String[c.getCount()];

if(c.moveToFirst()){
     for(int i=0;i<c.getCount();i++){
           body[i]= c.getString(c.getColumnIndexOrThrow("body")).toString();
           number[i]=c.getString(c.getColumnIndexOrThrow("address")).toString();
           c.moveToNext();
     }
}
c.close();
» Understand the application and do proper
  research online!

» This example has some concepts that you have to
  figure out on your own.

» Use documentation, books provided and other
  online resources to code the application.

» Ask help in online forums also!

Weitere ähnliche Inhalte

Was ist angesagt?

Lecture14Slides.ppt
Lecture14Slides.pptLecture14Slides.ppt
Lecture14Slides.ppt
Videoguy
 
Asp net interview_questions
Asp net interview_questionsAsp net interview_questions
Asp net interview_questions
Bilam
 

Was ist angesagt? (20)

Android Insights - 3 [Content Providers]
Android Insights - 3 [Content Providers]Android Insights - 3 [Content Providers]
Android Insights - 3 [Content Providers]
 
Android content provider explained
Android content provider explainedAndroid content provider explained
Android content provider explained
 
Android Training Session 1
Android Training Session 1Android Training Session 1
Android Training Session 1
 
Lecture14Slides.ppt
Lecture14Slides.pptLecture14Slides.ppt
Lecture14Slides.ppt
 
Android - Saving data
Android - Saving dataAndroid - Saving data
Android - Saving data
 
Backendless apps
Backendless appsBackendless apps
Backendless apps
 
Data Binding and Data Grid View Classes
Data Binding and Data Grid View ClassesData Binding and Data Grid View Classes
Data Binding and Data Grid View Classes
 
Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
Show loader to open url in web view
Show loader to open url in web viewShow loader to open url in web view
Show loader to open url in web view
 
Lab2-android
Lab2-androidLab2-android
Lab2-android
 
Level 1 &amp; 2
Level 1 &amp; 2Level 1 &amp; 2
Level 1 &amp; 2
 
BioJS specification document
BioJS specification documentBioJS specification document
BioJS specification document
 
Level 4
Level 4Level 4
Level 4
 
Level 3
Level 3Level 3
Level 3
 
WPF DATA BINDING CHEATSHEET V1.1
WPF DATA BINDING CHEATSHEET V1.1WPF DATA BINDING CHEATSHEET V1.1
WPF DATA BINDING CHEATSHEET V1.1
 
Ado.net
Ado.netAdo.net
Ado.net
 
Android App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsAndroid App Development - 04 Views and layouts
Android App Development - 04 Views and layouts
 
Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptx
 
Asp net interview_questions
Asp net interview_questionsAsp net interview_questions
Asp net interview_questions
 

Ähnlich wie 05 content providers - Android

Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViews
Ahsanul Karim
 
Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011
Johan Nilsson
 
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with EclipseEclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
Heiko Behrens
 
Coherence SIG: Advanced usage of indexes in coherence
Coherence SIG: Advanced usage of indexes in coherenceCoherence SIG: Advanced usage of indexes in coherence
Coherence SIG: Advanced usage of indexes in coherence
aragozin
 
Pavel_Kravchenko_Mobile Development
Pavel_Kravchenko_Mobile DevelopmentPavel_Kravchenko_Mobile Development
Pavel_Kravchenko_Mobile Development
Ciklum
 
Android ui adapter
Android ui adapterAndroid ui adapter
Android ui adapter
Krazy Koder
 
Need help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdf
Need help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdfNeed help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdf
Need help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdf
fastechsrv
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
timourian
 

Ähnlich wie 05 content providers - Android (20)

Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViews
 
Cursor & Content Value.pdf
Cursor & Content Value.pdfCursor & Content Value.pdf
Cursor & Content Value.pdf
 
Spring data ii
Spring data iiSpring data ii
Spring data ii
 
How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)
 
List adapter with multiple objects
List adapter with multiple objectsList adapter with multiple objects
List adapter with multiple objects
 
Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011Custom UI Components at Android Only 2011
Custom UI Components at Android Only 2011
 
Android adapters
Android adaptersAndroid adapters
Android adapters
 
Session 2- day 3
Session 2- day 3Session 2- day 3
Session 2- day 3
 
SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4
 
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with EclipseEclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
 
Coherence SIG: Advanced usage of indexes in coherence
Coherence SIG: Advanced usage of indexes in coherenceCoherence SIG: Advanced usage of indexes in coherence
Coherence SIG: Advanced usage of indexes in coherence
 
Pavel_Kravchenko_Mobile Development
Pavel_Kravchenko_Mobile DevelopmentPavel_Kravchenko_Mobile Development
Pavel_Kravchenko_Mobile Development
 
Android ui adapter
Android ui adapterAndroid ui adapter
Android ui adapter
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
 
Murach: How to transfer data from controllers
Murach: How to transfer data from controllersMurach: How to transfer data from controllers
Murach: How to transfer data from controllers
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto University
 
Need help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdf
Need help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdfNeed help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdf
Need help coding MorseCode in JavaCreate Class MorseCodeClient. T.pdf
 
Stata cheatsheet programming
Stata cheatsheet programmingStata cheatsheet programming
Stata cheatsheet programming
 
collections
collectionscollections
collections
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 

Mehr von Wingston

03 layouts & ui design - Android
03   layouts & ui design - Android03   layouts & ui design - Android
03 layouts & ui design - Android
Wingston
 
Linux – an introduction
Linux – an introductionLinux – an introduction
Linux – an introduction
Wingston
 
Introduction to the Arduino
Introduction to the ArduinoIntroduction to the Arduino
Introduction to the Arduino
Wingston
 
4.content mgmt
4.content mgmt4.content mgmt
4.content mgmt
Wingston
 
8 Web Practices for Drupal
8  Web Practices for Drupal8  Web Practices for Drupal
8 Web Practices for Drupal
Wingston
 
7 Theming in Drupal
7 Theming in Drupal7 Theming in Drupal
7 Theming in Drupal
Wingston
 
6 Special Howtos for Drupal
6 Special Howtos for Drupal6 Special Howtos for Drupal
6 Special Howtos for Drupal
Wingston
 

Mehr von Wingston (20)

OpenCV @ Droidcon 2012
OpenCV @ Droidcon 2012OpenCV @ Droidcon 2012
OpenCV @ Droidcon 2012
 
04 activities - Android
04   activities - Android04   activities - Android
04 activities - Android
 
03 layouts & ui design - Android
03   layouts & ui design - Android03   layouts & ui design - Android
03 layouts & ui design - Android
 
02 hello world - Android
02   hello world - Android02   hello world - Android
02 hello world - Android
 
01 introduction & setup - Android
01   introduction & setup - Android01   introduction & setup - Android
01 introduction & setup - Android
 
OpenCV with android
OpenCV with androidOpenCV with android
OpenCV with android
 
C game programming - SDL
C game programming - SDLC game programming - SDL
C game programming - SDL
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 
Linux – an introduction
Linux – an introductionLinux – an introduction
Linux – an introduction
 
Embedded linux
Embedded linuxEmbedded linux
Embedded linux
 
04 Arduino Peripheral Interfacing
04   Arduino Peripheral Interfacing04   Arduino Peripheral Interfacing
04 Arduino Peripheral Interfacing
 
03 analogue anrduino fundamentals
03   analogue anrduino fundamentals03   analogue anrduino fundamentals
03 analogue anrduino fundamentals
 
02 General Purpose Input - Output on the Arduino
02   General Purpose Input -  Output on the Arduino02   General Purpose Input -  Output on the Arduino
02 General Purpose Input - Output on the Arduino
 
Introduction to the Arduino
Introduction to the ArduinoIntroduction to the Arduino
Introduction to the Arduino
 
4.content mgmt
4.content mgmt4.content mgmt
4.content mgmt
 
8 Web Practices for Drupal
8  Web Practices for Drupal8  Web Practices for Drupal
8 Web Practices for Drupal
 
7 Theming in Drupal
7 Theming in Drupal7 Theming in Drupal
7 Theming in Drupal
 
6 Special Howtos for Drupal
6 Special Howtos for Drupal6 Special Howtos for Drupal
6 Special Howtos for Drupal
 

Kürzlich hochgeladen

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 

Kürzlich hochgeladen (20)

Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 

05 content providers - Android

  • 2. » Content providers allow programs access to data which is present on the device. » A content provider manages access to a central repository of data. » They encapsulate the data from tables, and provide mechanisms for defining data security and unified usage. » Content providers are the standard interface that connects data in one process with code running in another process.
  • 3. Content Provider Intended Data Browser Browser bookmarks, browser history, etc. CallLog Missed calls, call details, etc. Contacts Contact details MediaStore Media files such as audio, video and images Settings Device settings and preferences
  • 4. » Irrespective of how the data is stored, Content Providers give a uniform interface to access the data. » Data is exposed as a simple table with rows and columns where row is a record and column is a particular data type with a specific meaning. » Each record is identified by a unique _ID field which is the key to the record. » Each content provider exposes a unique URI that identifies its data set uniquely. URI == table-name
  • 5. » First we need to create a layout and activity class. » In our layout we need to create a ListView. » Create a cursor to query the phone database for the contacts.. » Use an adaptor to send the results to the view for displaying
  • 6. » An application accesses the data from a content provider with a ContentResolver client object. » The ContentResolver methods provide the basic "CRUD" (create, retrieve, update, and delete) functions of persi // Queries the user dictionary and returns results mCursor = getContentResolver().query( UserDictionary.Words.CONTENT_URI, // The content URI of the words table mProjection, // The columns to return for each row mSelectionClause // Selection statement mSelectionArgs, // Selection criteria mSortOrder); // The sort order for the returned rows
  • 7. » A content URI is a URI that identifies data in a provider. » Content URIs include the symbolic name of the entire provider (its authority) and a name that points to a table (a path). » content://user_dictionary/words
  • 8. » To retrieve data from a provider, your application needs "read access permission" for the provider in androidmanifest.xml. » Construct the query ˃ A "projection" defines the columns that will be returned for each row ˃ Do a query and return a cursor object which holds the result returned from the database » Read the result with the cursor implementation ˃ you can iterate over the rows in the results ˃ determine the data type of each column ˃ get the data out of a column ˃ And more!
  • 9. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent"/> </LinearLayout> This would create a listView of id list in the layout.
  • 10. » Cursor is an interface that provides random read-write access to the result of a database query from a content provider. » A cursor is a collection of rows » All field access methods are based on column number. You have to convert column name to a column number first » Random means (you can move forward and backwards) » You can also find size / traverse result set easily. Cursor cur; for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext()) { //access methods }
  • 11. » Since a Cursor is a "list" of rows, a good way to display the contents of a Cursor is to link it to a ListView via an adaptor. // Creates a new SimpleCursorAdapter mCursorAdapter = new SimpleCursorAdapter( getApplicationContext(), // The application's Context object R.layout.wordlistrow, // A layout in XML for one row in the ListView mCursor, // The result from the query mWordListColumns, // A string array of column names in the cursor mWordListItems, // An integer array of view IDs in the row layout 0); // Flags (usually none are needed) // Sets the adapter for the ListView mWordList.setAdapter(mCursorAdapter);
  • 12. Since our activity consists of a list, we can extend the class public class MyActivity extends ListActivity ListActivity to make life easier. { ListView lv; Cursor Cursor1; lv is used to manage the Listview, note that since the layout contains only one listview, the extend ListActivity is enough for the connection. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); A projection is the specific columns of the setContentView(R.layout.main); table that we want to query. String [] projection = new String[] { Phone.DISPLAY_NAME, Phone.NUMBER, Phone._ID getContentResolver() – returns a ContentResolver object }; from the activity class that can be used to query the content databases with Cursor1 = getContentResolver().query( query(projection, selection, selectionargs, sortorder) Phone.CONTENT_URI, projection, null, null, Phone.CONTENT_URI : Phone.DISPLAY_NAME + " ASC"); (android.provider.ContactsContract.CommonDataKinds.Phone) Points to the contact database location startManagingCursor(Cursor1);
  • 13. startManagingCursor(Cursor1); From and to are used to convert between the result of the query in the cursor to the textview’s String[] from = { in a list layout Phone.DISPLAY_NAME, Phone.NUMBER, SimpleCursorAdapter maps columns Phone._ID}; from a cursor to TextViews or ImageViews defined in an XML file. int[] to = {android.R.id.text1, android.R.id.text2}; Cursor1, from, to are the respective data args SimpleCursorAdapter listadapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, Cursor1, from, to ); setListAdapter(listadapter); android.R.layout.simple_list_item_2 is an inbuilt lv = getListView(); layout with 2 textviews for a list. A custom XML layout in res/layout can be inserted } // onCreate ends here here too with the id names of the textveiws replaced in the to variable.
  • 14. […] Get the cursor object and cursor = managedQuery(EXTERNAL_CONTENT_URI, perform the query on it proj, selection, arg, sort); Find the listview view from list = (ListView) findViewById(R.id.List01); the view list.setAdapter(new N_Adapter(getApplicationContext(), cursor)); [..] Use this function to bind the listview to an adaptor of class N_Adapter.. The function is taking a constructor to this class as arguments
  • 15. public class N_Adapter extends BaseAdapter { This class extends BaseAdapter which is the base private Context mContext; class for all adapter implementations Cursor cursor; public N_Adapter(Context c,Cursor m) { This constructor takes in the arguments passed to it mContext = c; and returns the object to the setadapter method. cursor = m; } public int getCount() { return count; } public Object getItem(int position) { return position; These functions are required for the adapter to work } properly within the android subsystem public long getItemId(int position) { return position; }
  • 16. This function performs the binding between the public View getView(int position, View convertView, ViewGroup parent) { cursor and the listview. TextView tv; View row; The view row is used to hold the xml file to place the LayoutInflater inflater = getLayoutInflater(); listview’s contents in. if (convertView == null) { convertView is in case the inflated view is being row = inflater.inflate(android.R.layout.item, null); passed in as arguments, in this case – we don’t } else want to inflate again.. row = convertView; android.R.layout.item -> xml file for the list elements tv = (TextView) row.findViewById(R.id.TextView01); cursor.moveToPosition(position); music_column_index = cursor .getColumnIndexOrThrow(People.DISPLAY_NAME); id = cursor.getString(music_column_index); Cursor is a class member initialized by the tv.setText(id); argument to the constructor, these lines extract return row; the data required and pass it to the textView } element in the listview XML file. }
  • 17. » Create a large text white background contacts list. » Attach an on click event to each list item and open a new activity that shows that contact’s details » Make an application that allows you to enter a phrase and searches through the SMS messages for all sms’s containing that text.
  • 18. » Make a edittext view in a layout and load it in activity. » Make a button and bind an onclickhandler() to it » When the button is clicked, load sms from the content provider and search the contents for all messages containing that word. » Display all messages (one by one or in a listview as per your choice)
  • 19. » <uses-permission android:name="android.permission.READ_SMS"></uses-permission> » <uses-permission android:name="android.permission.READ_CONTACTS"></uses- permission> » URI for sms content providers is as follows » Inbox = "content://sms/inbox" » Failed = "content://sms/failed" » Queued = "content://sms/queued" » Sent = "content://sms/sent" » Draft = "content://sms/draft" » Outbox = "content://sms/outbox" » Undelivered = "content://sms/undelivered" » All = "content://sms/all" » Conversations = "content://sms/conversations"
  • 20. » addressCol= mCurSms.getColumnIndex("address"); » personCol= mCurSms.getColumnIndex("person"); » dateCol = mCurSms.getColumnIndex("date"); » protocolCol= mCurSms.getColumnIndex("protocol"); » readCol = mCurSms.getColumnIndex("read"); » statusCol = mCurSms.getColumnIndex("status"); » typeCol = mCurSms.getColumnIndex("type"); » subjectCol = mCurSms.getColumnIndex("subject"); » bodyCol = mCurSms.getColumnIndex("body");
  • 21. » Uri uri = Uri.parse("content://sms/inbox"); » Cursor c= getContentResolver().query(uri, null, null ,null,null); » startManagingCursor(c)
  • 22. body = new String[c.getCount()]; number = new String[c.getCount()]; if(c.moveToFirst()){ for(int i=0;i<c.getCount();i++){ body[i]= c.getString(c.getColumnIndexOrThrow("body")).toString(); number[i]=c.getString(c.getColumnIndexOrThrow("address")).toString(); c.moveToNext(); } } c.close();
  • 23. » Understand the application and do proper research online! » This example has some concepts that you have to figure out on your own. » Use documentation, books provided and other online resources to code the application. » Ask help in online forums also!