프로그래밍/안드로이드

안드로이드 - ContentResolver

가카리 2013. 12. 31. 19:22
반응형

참고 사이트 : http://android-runner.springnote.com/pages/3075250

  • Shared Preferences : UI state, user preferences, application setting 값들을 저장할때 사용할 수 있는 lightweight mechanism 으로 key/value 형태로 primitive data 를 저장할 수 있음
  • Files : Device 내/외부 미디어에 파일을 생성하고 읽기/쓰기 할수 있는 기능을 제공함
  • SQLite  Databases : managed, structured data 접근이 필요할 때 SQLite relational database library 를 제공함
  • Content Providers : 데이터를 저장하는 어느 방법보다도 개인적인 데이타를 공유하고 사용하는데 있어 잘 정의된 인터페이스를 사용할 수 있는 방법을 제공함. 안드로이드 표준 보안체계(Shared Permission System)을 사용하면 접근제어를 할 수도 있다.

 

 

Introducing Content Providers

  •  Application 데이터를 다른 Application과 공유가 필요할 때 사용되는 일반적인 인터페이스 매커니즘
  •  URI를 이용하여 query, write 같은 데이터 작업을 지원함
  •  Contact Manager, Media Player, Picture 등 다양한 곳에서 사용

 http://developer.android.com/guide/topics/providers/content-providers.html

 

 

Using Content Providers

 Content Provider에서 제공하는 기능은 ContentResolver class를 통해 사용 가능함

 

 

Introducing Content Resolvers

 각 Application Context는 하나의 ContentResolver를 가짐

  1.  ContentResolver cr = getContentResolver();

 

 Content Provider의 URI는 AndroidManifest.xml에서 authority로 정의됨 (대부분의 Provider는 CONTENT_URI를 사용함)

  1.  <provider android:name="MyProvider" android:authorities="com.paad.provider.myapp"/>

 

 ContentResolver class를 이용하여 query, insery, delete, update method를 이용할 때 URI를 사용함

content://com.<CompanyName>.provider.<ApplicationName>/<DataPath> : 어떤 type의 모든 결과 값을 나타냄

content://com.paad.provider.myapp/items/<rowID> : 어떤 type의 특정한 레코드

  1.  content://com.paad.provider.myapp/items
  2.  content://com.paad.provider.myapp/items/5

 

 Querying for Content

Content Provider의 query는 데이터베이스의 query와 유사
데이터베이스를 사용한 것처럼 query에 대한 result set을 Cursor로 얻음
데이터베이스의 "Extracting Results from a Cursor"에서 설명한 방법을 이용하여 cursor로 부터 원하는 값을 추출하여 사용

 

ContentResolver.query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)

 

 - uri : 필요한 Content Provider data의 URI(content:// scheme)
 - projection : select절 (result set에 포함되기를 원하는 컬럼)
 - selection : where절 (? 사용가능)
 - selectionArgs : where절에서 ?를 대체할 수 있는 args
 - sortOrder : order

 

  1.  // Return all rows
    Cursor allRows = getContentResolver().query(MyProvider.CONTENT_URI, null, null, null, null);
    // Return all columns for rows where column 3 equals a set value
    // and the rows are ordered by column 5.
    String where = KEY_COL3 + “=” + requiredValue;
    String order = KEY_COL5;

          Cursor someRows = getContentResolver().query(MyProvider.CONTENT_URI, null, where, null, order);

 

 

 

 

_ID _COUNT NAME NUMBER
44 3 Alan Vain 212 555 1234
13 3 Bully Pulpit 425 555 6677
53 3 Rex Cars 201 555 4433

 

 Adding, Updating, and Deleting Content

 

Inserts

 ContentResolver는 record를 추가하기 위한 두 가지 method를 제공

 

Uri android.content.ContentResolver.insert(Uri url, ContentValues values) : 한개의 record를 추가하는 method로서 추가된 record의 새로운 URI를 리턴함


 

int android.content.ContentResolver.bulkInsert(Uri url, ContentValues[] values)  : 여러개의 record를 추가하는 method로서 추가된 record의 개수를 리턴함

 

  1.  // Create a new row of values to insert.
    ContentValues newValues = new ContentValues();
  2. // Assign values for each row.
    newValues.put(COLUMN_NAME, newValue);
    [ ... Repeat for each column ... ]
    Uri myRowUri = getContentResolver().insert(MyProvider.CONTENT_URI, newValues);
    // Create a new row of values to insert.
    ContentValues[] valueArray = new ContentValues[5];
    // TODO: Create an array of new rows
    int count = getContentResolver().bulkInsert(MyProvider.CONTENT_URI, valueArray);

 Deletes

int android.content.ContentResolver.delete(Uri url, String where, String[] selectionArgs)

  1.  // Remove a specific row.
    getContentResolver().delete(myRowUri, null, null);
    // Remove the first five rows.
    String where = “_id < 5”;
    getContentResolver().delete(MyProvider.CONTENT_URI, where, null);

 Updates

int android.content.ContentResolver.update(Uri uri, ContentValues values, String where, String[] selectionArgs)
  1.  // Create a new row of values to insert.
    ContentValues newValues = new ContentValues();
    // Create a replacement map, specifying which columns you want to
    // update, and what values to assign to each of them.
    newValues.put(COLUMN_NAME, newValue);
    // Apply to the first 5 rows.
    String where = “_id < 5”;
    getContentResolver().update(MyProvider.CONTENT_URI, newValues, where, null);

 

 Accessing Files in Content Providers

InputStream android.content.ContentResolver.openInputStream(Uri uri)
OutputStream android.content.ContentResolver.openOutputStream(Uri uri)
  1.  // Insert a new row into your provider, returning its unique URI.
    Uri uri = getContentResolver().insert(MyProvider.CONTENT_URI,newValues);
    try {
       // Open an output stream using the new row’s URI.
       OutputStream outStream = getContentResolver().openOutputStream(uri);
       // Compress your bitmap and save it into your provider.
       sourceBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
    }
    catch (FileNotFoundException e) { }

 

 

 Native Android Content Providers

 android.provider 패키지에 유용한 provider가 제공됨

  • Browser : bookmarks, browser history, web searches
  • CallLog : incoming/outgoing/missed calls, call details(caller ID, call durations)
  • Contacts : contacts’ details
  • MediaStore : multimedia(audio, video, images)
  • Settings : device’s preferences(Bluetooth settings, ring tones..)

 

 Using the Media Store Provider

Media Store Provider를 이용하여 audio, video, image 파일을 Android 파일시스템 상에서 관리할 수 있음

MediaStore class는 Media Store에 파일을 추가하는 간단하고 편리한 method를 제공

String android.provider.MediaStore.Images.Media.insertImage(ContentResolver cr, Bitmap source, String title, String description)
  1.  android.provider.MediaStore.Images.Media.insertImage(getContentResolver(),sourceBitmap,“my_cat_pic”,“Photo of my cat!”);

 

Using the Contacts Provider

Application이 Contacts Provider를 이용하기 위해서는 AndroidManifest.xml에서 권한이 추가되어야 함

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

 

  1.  // Get a cursor over every contact.
    Cursor cursor = getContentResolver().query(People.CONTENT_URI,null, null, null, null);
    // Let the activity manage the cursor lifecycle.
    startManagingCursor(cursor);
    // Use the convenience properties to get the index of the columns
    int nameIdx = cursor.getColumnIndexOrThrow(People.NAME);
  2. int phoneIdx = cursor. getColumnIndexOrThrow(People.NUMBER);
    String[] result = new String[cursor.getCount()];
    if (cursor.moveToFirst())
    do {
       // Extract the name.
       String name = cursor.getString(nameIdx);
       // Extract the phone number.
       String phone = cursor.getString(phoneIdx);
       result[cursor.getPosition()] = name + “ (“ + phone + “)”;
    } while(cursor.moveToNext());

 Creating a New Content Provider

 

1.  ContentProvider class를 상속받아 새로운 Content Provider class 생성하기

  1. import android.content.*;
    import android.database.Cursor;
    import android.net.Uri;
    import android.database.SQLException;

  2. public class MyProvider extends ContentProvider {
       @Override
       public boolean onCreate() {
       // TODO: Construct the underlying database.
       return true;
       }
    }

 

2. URI 등록하기

  1. public class MyProvider extends ContentProvider {
       private static final String myURI =“content://com.paad.provider.myapp/items”;
       public static final Uri CONTENT_URI = Uri.parse(myURI);
  2.  
  3. @Override
    public boolean onCreate() {
       // TODO: Construct the underlying database.
       return true;
    }
  4.  
  5. // Create the constants used to differentiate between the different
    // URI requests.
    private static final int ALLROWS = 1;
    private static final int SINGLE_ROW = 2;
    private static final UriMatcher uriMatcher;
    // Populate the UriMatcher object, where a URI ending in ‘items’ will
    // correspond to a request for all items, and ‘items/[rowID]’
    // represents a single row.
    static {
       uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
       uriMatcher.addURI(“com.paad.provider.myApp”, “items”, ALLROWS);
       uriMatcher.addURI(“com.paad.provider.myApp”, “items/#”, SINGLE_ROW);
    }
  6. }

 

3. ContentProvider의 query, insert, delete, update, getType method override

  1. @Override
    public Cursor query(Uri uri,
                          String[] projection,
                          String selection,
                          String[] selectionArgs,
                          String sort) {
            
        // If this is a row query, limit the result set to the passed in row.       
        switch (uriMatcher.match(uri)) {
          case SINGLE_ROW :
            // TODO: Modify selection based on row id, where:
            // rowNumber = uri.getPathSegments().get(1));
        }
        return null;
      }
  2.   @Override
      public Uri insert(Uri _uri, ContentValues _initialValues) {
        long rowID = 1;//[ ... Add a new item ... ]
              
        // Return a URI to the newly added item.
        if (rowID > 0) {
          return ContentUris.withAppendedId(CONTENT_URI, rowID);
        }
        throw new SQLException("Failed to add new item into " + _uri);
      }
  3.   @Override
      public int delete(Uri uri, String where, String[] whereArgs) {
        switch (uriMatcher.match(uri)) {
          case ALLROWS:
          case SINGLE_ROW:
          default: throw new IllegalArgumentException("Unsupported URI:" + uri);
        }
      }
  4.   @Override
      public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
        switch (uriMatcher.match(uri)) {
          case ALLROWS:
          case SINGLE_ROW:
          default: throw new IllegalArgumentException("Unsupported URI:" + uri);
        }
      }
  5.   @Override
      public String getType(Uri _uri) {
        switch (uriMatcher.match(_uri)) {
          case ALLROWS: return "vnd.paad.cursor.dir/myprovidercontent";
          case SINGLE_ROW: return "vnd.paad.cursor.item/myprovidercontent";
          default: throw new IllegalArgumentException("Unsupported URI: " + _uri);
        }
      }

 

4. Provder를 AndroidManifest.xml에 추가하기

  1. <provider android:name="MyProvider" android:authorities="com.paad.provider.myapp"/>

 

[출처] ContentResolver|작성자 MK

 

반응형