Use ContentProvider to access non-database data

Source: Internet
Author: User

Use ContentProvider to access non-database data
Generally, ContentProvider is used to access database data, but sometimes non-database data, such as XML or local data, needs to be specially processed.
The most important thing is to customize the Cursor, because the ContentProvider's query method can only return the Cursor reference. Let's talk about the code.

 
 
  1. Public class MyContentProvider extends ContentProvider {

  2. // URI operation class
  3. Public static final UriMatcher uriMatcher;
  4. // Add a custom URI for UriMatcher
  5. Static {
  6. UriMatcher = new UriMatcher (UriMatcher. NO_MATCH );
  7. UriMatcher. addURI (ProviderConstant. AUTHORITIES, "/user ",
  8. ProviderConstant. INCOMING_USER_COLLECTION );
  9. UriMatcher. addURI (ProviderConstant. AUTHORITIES, "/user /#",
  10. ProviderConstant. INCOMING_USER_SINGLE );
  11. }

  12. Private HashMap > AllDatas = new HashMap > ();


  13. Private MyCursor cursor;

  14. Public MyContentProvider (){
  15. Cursor = new MyCursor ();
  16. LoadAllData ();
  17. }


  18. /**
  19. * Load our data information
  20. */
  21. Public void loadAllData (){
  22. AllDatas. clear ();
  23. For (int pos = 0; pos <5; pos ++) {// fill in 5 student data
  24. ArrayList DataList = new ArrayList <> ();
  25. DataList. add (pos + ""); // id
  26. DataList. add ("name" + pos); // name
  27. AllDatas. put (pos + "", dataList );
  28. }
  29. }

  30. /**
  31. * Delete data
  32. */
  33. @ Override
  34. Public int delete (Uri uri, String selection, String [] selectionArgs ){
  35. System. out. println ("delete ");
  36. Int count = 0;
  37. String id = getUserId (selection, selectionArgs );
  38. If (allDatas. containsKey (id )){
  39. AllDatas. remove (id );
  40. Count = 1;
  41. }
  42. Return count;
  43. }

  44. /**
  45. * Database access type
  46. */
  47. @ Override
  48. Public String getType (Uri uri ){
  49. System. out. println ("getType ");
  50. // Obtain the data type based on the user request
  51. Switch (uriMatcher. match (uri )){
  52. Case ProviderConstant. INCOMING_USER_COLLECTION:
  53. Return ProviderConstant. CONTENT_TYPE;
  54. Case ProviderConstant. INCOMING_USER_SINGLE:
  55. Return ProviderConstant. CONTENT_TYPE_ITEM;
  56. Default:
  57. Throw new IllegalArgumentException ("UnKnown URI" + uri );
  58. }
  59. }

  60. /**
  61. * Insert data
  62. */
  63. @ Override
  64. Public Uri insert (Uri uri, ContentValues values ){
  65. ArrayList Data = new ArrayList <> ();
  66. Int id = values. getAsInteger (ProviderConstant. ID );
  67. String name = values. getAsString (ProviderConstant. NAME );
  68. Data. add (id + "");
  69. Data. add (name );
  70. AllDatas. put (id + "", data );
  71. Return uri;
  72. }

  73. /**
  74. * Callback function called when ContentProvider is created
  75. */
  76. @ Override
  77. Public boolean onCreate (){
  78. System. out. println ("onCreate ");
  79. Return true;
  80. }

  81. /**
  82. * Query a database
  83. */
  84. @ Override
  85. Public Cursor query (Uri uri, String [] projection, String selection,
  86. String [] selectionArgs, String sortOrder ){
  87. // Determine whether a user request is a single query
  88. Switch (uriMatcher. match (uri )){
  89. Case ProviderConstant. INCOMING_USER_COLLECTION:
  90. Cursor. updateAllData (allDatas. values ());
  91. Break;
  92. Case ProviderConstant. INCOMING_USER_SINGLE:
  93. String id = uri. getLastPathSegment ();
  94. Cursor. updateUserData (allDatas. get (id ));
  95. Break;
  96. }
  97. Return cursor;
  98. }

  99. /**
  100. * Update a database
  101. */
  102. @ Override
  103. Public int update (Uri uri, ContentValues values, String selection,
  104. String [] selectionArgs ){
  105. System. out. println ("update ");
  106. String id = getUserId (selection, selectionArgs );
  107. Int count = 0;
  108. If (allDatas. containsKey (id )){
  109. String name = values. getAsString (ProviderConstant. NAME );
  110. // Index depends on the column where name is located
  111. AllDatas. get (id). set (cursor. getColumnIndex (ProviderConstant. NAME), name );
  112. Count = 1;
  113. }
  114. Return count;
  115. }

  116. /**
  117. * Obtain key information and user ID
  118. * @ Param selection
  119. * @ Param selectionArgs
  120. * @ Return
  121. */
  122. Private String getUserId (String selection, String [] selectionArgs ){
  123. If (selectionArgs = null | selectionArgs. length = 0 ){
  124. // Id is included in selection
  125. Return selection. substring (selection. indexOf ("=") + 1). trim ();
  126. } Else {
  127. Return selectionArgs [0];
  128. }
  129. }

  130. }
The above is the custom contentProvider. There are many examples and instructions on the Internet. We will not detail them here. Let's take a look at the query and I will return the custom Cursor.
Some constants are used as follows:
 
 
  1. Public class ProviderConstant {
  2. // Specify the URI. The string here must be consistent with the declared authorities.
  3. Public static final String AUTHORITIES = "com. zy. sports. app. MyContentProvider ";

  4. // Access the uri of the ContentProvider
  5. Public static final Uri CONTENT_URI = Uri. parse ("content: //" + AUTHORITIES + "/user ");

  6. // Define the data type returned by the ContentProvider
  7. Public static final String CONTENT_TYPE = "vnd. android. cursor. dir/vnd. myprovider. user ";
  8. Public static final String CONTENT_TYPE_ITEM = "vnd. android. cursor. item/vnd. myprovider. user ";


  9. // Access all columns in the table
  10. Public static final int INCOMING_USER_COLLECTION = 1;
  11. // Access a separate column
  12. Public static final int INCOMING_USER_SINGLE = 2;


  13. Public static final String ID = "id ";
  14. Public static final String NAME = "name ";

  15. }



The custom Cursor code is as follows:

 
 
  1. Public class MyCursor extends actcursor {
  2. Private static final String TAG = "MyCursor ";

  3. Private String [] columnNames = null; // when constructing a cursor, you must first input the list array to specify the number of Columns

  4. /**
  5. * Data Region
  6. */
  7. // All data
  8. Private ArrayList> allDatas = new ArrayList> (); // fill in the data during construction. The size of the layer data = columnNames. leng
  9. // Data of the current item
  10. Private ArrayList OneLineData = null; // fill in when onMove

  11. Public MyCursor (){
  12. // Complete column information must be constructed
  13. ColumnNames = new String [] {"id", "name "};
  14. }

  15. /**
  16. * Load our data information
  17. */
  18. Public void updateAllData (Collection> data ){
  19. MPos =-1;
  20. AllDatas. clear ();
  21. AllDatas. addAll (data );
  22. }

  23. /**
  24. * Load our data information
  25. */
  26. Public void updateUserData (ArrayList Data ){
  27. MPos =-1;
  28. AllDatas. clear ();
  29. AllDatas. add (data );
  30. }

  31. /**
  32. * Get the object of the current row, which is an oneLineDatastring []
  33. */

  34. @ Override
  35. Public boolean onMove (int oldPosition, int newPosition ){
  36. If (newPosition <0 | newPosition> = getCount ()){
  37. OneLineData = null;
  38. Return false;
  39. }

  40. Int index = newPosition;
  41. If (index <0 | index> = allDatas. size ()){
  42. Return false;
  43. }
  44. OneLineData = allDatas. get (index );
  45. Return super. onMove (oldPosition, newPosition );
  46. }

  47. /**
  48. * Get the number of cursor rows
  49. */
  50. @ Override
  51. Public int getCount (){
  52. Return allDatas. size ();
  53. }

  54. /**
  55. * Get the column name
  56. */
  57. @ Override
  58. Public String [] getColumnNames (){
  59. Return columnNames;
  60. }


  61. @ Override
  62. Public String getString (int column ){
  63. If (oneLineData = null ){
  64. Return null;
  65. }
  66. Return oneLineData. get (column );
  67. }

  68. @ Override
  69. Public int getInt (int column ){
  70. Object value = getString (column );
  71. Try {
  72. Return value! = Null? (Number) value). intValue (): null;
  73. } Catch (ClassCastException e ){
  74. If (value instanceof CharSequence ){
  75. Try {
  76. Return Integer. valueOf (value. toString ());
  77. } Catch (NumberFormatException e2 ){
  78. Log. e (TAG, "Cannotparse int value for" + value + "at key" + column );
  79. Return 0;
  80. }
  81. } Else {
  82. Log. e (TAG, "Cannotcast value for" + column + "to a int:" + value, e );
  83. Return 0;
  84. }
  85. }
  86. }

  87. /**
  88. * For the following information, see getInt (int column)
  89. */

  90. @ Override
  91. Public short getShort (int column ){
  92. Return 0;
  93. }

  94. @ Override
  95. Public long getLong (int column ){
  96. Return 0;
  97. }

  98. @ Override
  99. Public float getFloat (int column ){
  100. Return 0;
  101. }

  102. @ Override
  103. Public double getDouble (int column ){
  104. Return 0;
  105. }

  106. @ Override
  107. Public boolean isNull (int column ){
  108. Return false;
  109. }
  110. }
We can see that Cursor is an interface. We only need to inherit AbstractCursor or its subclass to redefine the Cursor method. For more information





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.