码迷,mamicode.com
首页 > 其他好文 > 详细

MyContentProvider

时间:2015-07-30 12:59:21      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
 1 package com.example.shad_fnst.mycontentprovider;
 2 
 3 import android.app.Activity;
 4 import android.content.ContentResolver;
 5 import android.content.ContentValues;
 6 import android.database.Cursor;
 7 import android.net.Uri;
 8 import android.os.Bundle;
 9 import android.view.Menu;
10 import android.view.MenuItem;
11 import android.view.View;
12 import android.widget.EditText;
13 import android.widget.Toast;
14 
15 
16 public class MainActivity extends Activity{
17 
18     @Override
19     protected void onCreate(Bundle savedInstanceState) {
20         super.onCreate(savedInstanceState);
21         setContentView(R.layout.activity_main);
22     }
23 
24     @Override
25     public boolean onCreateOptionsMenu(Menu menu) {
26         // Inflate the menu; this adds items to the action bar if it is present.
27         getMenuInflater().inflate(R.menu.menu_main, menu);
28         return true;
29     }
30 
31     public void onClickAddName(View view){
32         ContentValues values = new ContentValues();
33 
34         values.put(StudentsProvider.NAME,
35                 ((EditText)findViewById(R.id.txtName)).getText().toString());
36         values.put(StudentsProvider.GRADE,
37                 ((EditText)findViewById(R.id.txtGrade)).getText().toString());
38         Uri uri = getContentResolver().insert(StudentsProvider.CONTENT_URI, values);
39         Toast.makeText(getBaseContext(),
40                 uri.toString(), Toast.LENGTH_LONG).show();
41     }
42 
43     public void onClickRetrieveStudents(View view){
44         // Retrieve student records
45         String URL = "content://com.example.provider.College/students";
46         Uri students = Uri.parse(URL);
47         //Cursor c = managedQuery(students, null, null, null, "name");
48         ContentResolver contentResolver = getContentResolver();
49         Cursor cursor = contentResolver.query(StudentsProvider.CONTENT_URI, null, null, null, "name");
50         if(cursor.moveToFirst()){
51             do{
52                 String message = cursor.getString(cursor.getColumnIndex(StudentsProvider._ID)) + ", " +
53                         cursor.getString(cursor.getColumnIndex(StudentsProvider.NAME)) + ", " +
54                         cursor.getString(cursor.getColumnIndex(StudentsProvider.GRADE));
55                 Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
56             }while(cursor.moveToNext());
57         }
58         cursor.close();
59     }
60 }
MainActivity.java


 

技术分享
  1 package com.example.shad_fnst.mycontentprovider;
  2 
  3 import android.content.ContentProvider;
  4 import android.content.ContentUris;
  5 import android.content.ContentValues;
  6 import android.content.Context;
  7 import android.content.UriMatcher;
  8 import android.database.Cursor;
  9 import android.database.sqlite.SQLiteDatabase;
 10 import android.database.sqlite.SQLiteOpenHelper;
 11 import android.database.sqlite.SQLiteQueryBuilder;
 12 import android.net.Uri;
 13 import android.text.TextUtils;
 14 
 15 import java.sql.SQLException;
 16 import java.util.HashMap;
 17 
 18 /**
 19  * Created by shad-fnst on 2015/07/27.
 20  */
 21 public class StudentsProvider extends ContentProvider{
 22 
 23     static final String PROVIDER_NAME = "com.example.provider.College";
 24     static final String URL = "content://" + PROVIDER_NAME + "/students";
 25     static final Uri CONTENT_URI = Uri.parse(URL);
 26 
 27     static final String _ID = "id";
 28     static final String NAME = "name";
 29     static final String GRADE = "grade";
 30 
 31     private static HashMap<String, String> STUDENTS_PROJECTION_MAP;
 32 
 33     static final int STUDENTS = 1;
 34     static final int STUDENT_ID = 2;
 35 
 36     static final UriMatcher uriMatcher;
 37     static {
 38         uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
 39         uriMatcher.addURI(PROVIDER_NAME, "students", STUDENTS);
 40         uriMatcher.addURI(PROVIDER_NAME, "students/#", STUDENT_ID);
 41     }
 42 
 43     /**
 44      * Database specific constant declarations
 45      */
 46     private SQLiteDatabase db;
 47     static final String DATABASE_NAME = "College";
 48     static final String STUDENTS_TABLE_NAME = "students";
 49     static final int DATABASE_VERSION = 1;
 50     static final String CREATE_DB_TABLE =
 51             " CREATE TABLE " + STUDENTS_TABLE_NAME +
 52                     " ( id INTEGER PRIMARY KEY AUTOINCREMENT, " +
 53                     " name TEXT NOT NULL, " +
 54                     " grade TEXT NOT NULL);";
 55 
 56     /**
 57      * Helper class that actually creates and manages
 58      * the provider‘s underlying data repository.
 59      * @return
 60      */
 61     private static class DatabaseHelper extends SQLiteOpenHelper{
 62         DatabaseHelper(Context context){
 63 
 64             super(context, DATABASE_NAME, null, DATABASE_VERSION);
 65         }
 66 
 67         @Override
 68         public void onCreate(SQLiteDatabase db){
 69             db.execSQL(CREATE_DB_TABLE);
 70         }
 71 
 72         @Override
 73         public void onUpgrade(SQLiteDatabase db, int oldVersion,
 74                               int newVersion){
 75             db.execSQL("DROP TABLE IF EXISTS " + STUDENTS_TABLE_NAME);
 76             onCreate(db);
 77         }
 78     }
 79 
 80     @Override
 81     public boolean onCreate(){
 82         Context context = getContext();
 83         DatabaseHelper dbHelper =new DatabaseHelper(context);
 84         /**
 85          * Create a write able database which will trigger its
 86          * creation if it doesn‘t already exist.
 87          */
 88         db = dbHelper.getWritableDatabase();
 89         return (db == null) ? false:true;
 90     }
 91 
 92     @Override
 93     public Uri insert(Uri uri, ContentValues values){
 94         /**
 95          * Add a new student record
 96          */
 97         long rowID = db.insert(STUDENTS_TABLE_NAME, "", values);
 98         /**
 99          * If record is added successfully
100          */
101         if(rowID > 0){
102             Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
103             getContext().getContentResolver().notifyChange(_uri, null);     //通知其他ContentObserver数据改变
104             return uri;
105         }
106         //throw new SQLException("Failed to add a record into " + uri);
107         return uri;
108     }
109 
110     @Override
111     public Cursor query(Uri uri, String[] projection, String selection,
112                         String[] selectionArgs, String sortOrder){
113         SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
114         qb.setTables(STUDENTS_TABLE_NAME);
115 
116         switch (uriMatcher.match(uri)){
117             case STUDENTS:
118                 qb.setProjectionMap(STUDENTS_PROJECTION_MAP);
119                 break;
120             case STUDENT_ID:
121                 qb.appendWhere( _ID + "=" + uri.getPathSegments().get(1));
122                 break;
123             default:
124                 throw new IllegalArgumentException("Unknown URI " + uri);
125         }
126         if(sortOrder == null || sortOrder == ""){
127             sortOrder =NAME;
128         }
129         Cursor c = qb.query(db, projection, selection, selectionArgs,
130                 null, null, sortOrder);
131         c.setNotificationUri(getContext().getContentResolver(), uri);
132 
133         return c;
134     }
135 
136 /*
137     @Override
138     public Cursor query(Uri uri, String[] projection, String selection,
139                         String[] selectionArgs, String sortOrder){
140         //SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
141         //qb.setTables(STUDENTS_TABLE_NAME);
142 
143         Cursor cursor = null;
144         switch (uriMatcher.match(uri)){
145             case STUDENTS:
146                 cursor = db.query(STUDENTS_TABLE_NAME, projection, selection, selectionArgs, null, null, null);
147                 break;
148             case STUDENT_ID:
149                 //qb.appendWhere( _ID + "=" + uri.getPathSegments().get(1));
150                 break;
151         }
152 
153         return cursor;
154     }
155     */
156 
157     @Override
158     public int delete(Uri uri, String selection, String[] selectionArgs){
159         int count = 0;
160 
161         switch (uriMatcher.match(uri)){
162             case STUDENTS:
163                 count = db.delete(STUDENTS_TABLE_NAME, selection, selectionArgs);
164                 break;
165             case STUDENT_ID:
166                 String id = uri.getPathSegments().get(1);
167                 count = db.delete(STUDENTS_TABLE_NAME, _ID + " = " + id +
168                         (!TextUtils.isEmpty(selection) ? " AND (" +
169                         selection + ‘)‘ : ""), selectionArgs);
170                 break;
171             default:
172                 throw new IllegalArgumentException("Unknown URI " + uri);
173         }
174 
175         getContext().getContentResolver().notifyChange(uri, null);
176         return count;
177     }
178 
179     @Override
180     public int update(Uri uri, ContentValues values, String selection,
181                       String[] selectionArgs){
182         int count = 0;
183 
184         switch (uriMatcher.match(uri)){
185             case STUDENTS:
186                 count = db.update(STUDENTS_TABLE_NAME, values, selection, selectionArgs);
187                 break;
188             case STUDENT_ID:
189                 count = db.update(STUDENTS_TABLE_NAME, values, _ID +
190                         " = " +uri.getPathSegments().get(1) +
191                         (!TextUtils.isEmpty(selection) ? " AND (" +
192                         selection + ‘)‘ : ""), selectionArgs);
193                 break;
194             default:
195                 throw new IllegalArgumentException("Unknown URI " + uri);
196         }
197         getContext().getContentResolver().notifyChange(uri, null);
198         return  count;
199     }
200 
201     @Override
202     public String getType(Uri uri){
203         switch (uriMatcher.match(uri)){
204             /**
205              * Get all students records
206              */
207             case STUDENTS:
208                 return "vnd.android.cursor.dir/vnd.example.students";
209             /**
210              * Get a particular student
211              */
212             case STUDENT_ID:
213                 return "vnd.android.cursor.item/vnd.example.students";
214             default:
215                 throw new IllegalArgumentException("Unsupported URI: " + uri);
216 
217         }
218     }
219 }
StudentsProvider.java

 

技术分享
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.example.shad_fnst.mycontentprovider"
 4     android:versionCode="1"
 5     android:versionName="1.0" >
 6 
 7     <uses-sdk
 8         android:minSdkVersion="8"
 9         android:targetSdkVersion="17" >
10     </uses-sdk>
11 
12     <application
13         android:allowBackup="true"
14         android:icon="@mipmap/ic_launcher"
15         android:label="@string/app_name"
16         android:theme="@style/AppTheme" >
17         <activity
18             android:name="com.example.shad_fnst.mycontentprovider.MainActivity"
19             android:label="@string/app_name" >
20             <intent-filter>
21                 <action android:name="android.intent.action.MAIN" />
22 
23                 <category android:name="android.intent.category.LAUNCHER" />
24             </intent-filter>
25         </activity>
26 
27         <provider
28             android:authorities="com.example.provider.College"
29             android:name=".StudentsProvider">
30         </provider>
31 
32     </application>
33 
34 </manifest>
AndroidMainfest.xml

 

技术分享
 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:paddingLeft="@dimen/activity_horizontal_margin"
 6     android:paddingRight="@dimen/activity_horizontal_margin"
 7     android:paddingTop="@dimen/activity_vertical_margin"
 8     android:paddingBottom="@dimen/activity_vertical_margin"
 9     android:orientation="vertical"
10     tools:context=".MainActivity">
11 
12     <TextView
13         android:layout_width="fill_parent"
14         android:layout_height="wrap_content"
15         android:text="Name" />
16     <EditText
17         android:id="@+id/txtName"
18         android:layout_width="fill_parent"
19         android:layout_height="wrap_content" />
20 
21     <TextView
22         android:layout_width="fill_parent"
23         android:layout_height="wrap_content"
24         android:text="Grade" />
25     <EditText
26         android:id="@+id/txtGrade"
27         android:layout_width="fill_parent"
28         android:layout_height="wrap_content" />
29 
30     <Button
31         android:layout_width="fill_parent"
32         android:layout_height="wrap_content"
33         android:text="Add Name"
34         android:id="@+id/btnAdd"
35         android:onClick="onClickAddName" />
36 
37     <Button
38         android:layout_width="fill_parent"
39         android:layout_height="wrap_content"
40         android:text="Retrieve Students"
41         android:id="@+id/btnRetrieve"
42         android:onClick="onClickRetrieveStudents" />
43 
44 </LinearLayout>
activity_main.xml

 

MyContentProvider

标签:

原文地址:http://www.cnblogs.com/hello-sandy/p/4688578.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!