· 7 years ago · Oct 29, 2018, 08:16 PM
1/**********************
2 * MainActivity
3 *********************/
4
5package com.androidii.martial.contentprovider;
6
7import android.content.ContentValues;
8import android.database.Cursor;
9import android.net.Uri;
10import android.support.v7.app.AppCompatActivity;
11import android.os.Bundle;
12import android.view.View;
13import android.widget.EditText;
14import android.widget.Toast;
15
16public class MainActivity extends AppCompatActivity {
17
18 @Override
19 protected void onCreate(Bundle savedInstanceState) {
20 super.onCreate(savedInstanceState);
21 setContentView(R.layout.activity_main);
22 }
23 public void onClickAddName(View view) {
24 // Add a new student record
25 ContentValues values = new ContentValues();
26 values.put(StudentsProvider.NAME,
27 ((EditText)findViewById(R.id.editText2)).getText().toString());
28
29 values.put(StudentsProvider.GRADE,
30 ((EditText)findViewById(R.id.editText3)).getText().toString());
31
32 Uri uri = getContentResolver().insert(
33 StudentsProvider.CONTENT_URI, values);
34
35 Toast.makeText(getBaseContext(),
36 uri.toString(), Toast.LENGTH_LONG).show();
37 }
38 public void onClickRetrieveStudents(View view) {
39 // Retrieve student records
40 String URL = "content://com.example.MyApplication.StudentsProvider";
41
42 Uri students = Uri.parse(URL);
43 Cursor c = managedQuery(students, null, null, null, "name");
44
45 if (c.moveToFirst()) {
46 do{
47 Toast.makeText(this,
48 c.getString(c.getColumnIndex(StudentsProvider._ID)) +
49 ", " + c.getString(c.getColumnIndex( StudentsProvider.NAME)) +
50 ", " + c.getString(c.getColumnIndex( StudentsProvider.GRADE)),
51 Toast.LENGTH_SHORT).show();
52 } while (c.moveToNext());
53 }
54 }
55}
56
57/**********************
58 * StudentsProvider
59 *********************/
60
61package com.androidii.martial.contentprovider;
62
63import android.content.ContentProvider;
64import android.content.ContentUris;
65import android.content.ContentValues;
66import android.content.Context;
67import android.content.UriMatcher;
68import android.database.Cursor;
69import android.database.SQLException;
70import android.database.sqlite.SQLiteDatabase;
71import android.database.sqlite.SQLiteOpenHelper;
72import android.database.sqlite.SQLiteQueryBuilder;
73import android.net.Uri;
74import android.text.TextUtils;
75
76import java.util.HashMap;
77
78public class StudentsProvider extends ContentProvider {
79 static final String PROVIDER_NAME = "com.example.MyApplication.StudentsProvider";
80 static final String URL = "content://" + PROVIDER_NAME + "/students";
81 static final Uri CONTENT_URI = Uri.parse(URL);
82
83 static final String _ID = "_id";
84 static final String NAME = "name";
85 static final String GRADE = "grade";
86
87 private static HashMap<String, String> STUDENTS_PROJECTION_MAP;
88
89 static final int STUDENTS = 1;
90 static final int STUDENT_ID = 2;
91
92 static final UriMatcher uriMatcher;
93 static{
94 uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
95 uriMatcher.addURI(PROVIDER_NAME, "students", STUDENTS);
96 uriMatcher.addURI(PROVIDER_NAME, "students/#", STUDENT_ID);
97 }
98
99 /**
100 * Database specific constant declarations
101 */
102
103 private SQLiteDatabase db;
104 static final String DATABASE_NAME = "College";
105 static final String STUDENTS_TABLE_NAME = "students";
106 static final int DATABASE_VERSION = 1;
107 static final String CREATE_DB_TABLE =
108 " CREATE TABLE " + STUDENTS_TABLE_NAME +
109 " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
110 " name TEXT NOT NULL, " +
111 " grade TEXT NOT NULL);";
112
113 /**
114 * Helper class that actually creates and manages
115 * the provider's underlying data repository.
116 */
117
118 private static class DatabaseHelper extends SQLiteOpenHelper {
119 DatabaseHelper(Context context){
120 super(context, DATABASE_NAME, null, DATABASE_VERSION);
121 }
122
123 @Override
124 public void onCreate(SQLiteDatabase db) {
125 db.execSQL(CREATE_DB_TABLE);
126 }
127
128 @Override
129 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
130 db.execSQL("DROP TABLE IF EXISTS " + STUDENTS_TABLE_NAME);
131 onCreate(db);
132 }
133 }
134
135 @Override
136 public boolean onCreate() {
137 Context context = getContext();
138 DatabaseHelper dbHelper = new DatabaseHelper(context);
139
140 /**
141 * Create a write able database which will trigger its
142 * creation if it doesn't already exist.
143 */
144
145 db = dbHelper.getWritableDatabase();
146 return (db == null)? false:true;
147 }
148
149 @Override
150 public Uri insert(Uri uri, ContentValues values) {
151 /**
152 * Add a new student record
153 */
154 long rowID = db.insert( STUDENTS_TABLE_NAME, "", values);
155
156 /**
157 * If record is added successfully
158 */
159 if (rowID > 0) {
160 Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
161 getContext().getContentResolver().notifyChange(_uri, null);
162 return _uri;
163 }
164
165 throw new SQLException("Failed to add a record into " + uri);
166 }
167
168 @Override
169 public Cursor query(Uri uri, String[] projection,
170 String selection, String[] selectionArgs, String sortOrder) {
171 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
172 qb.setTables(STUDENTS_TABLE_NAME);
173
174 switch (uriMatcher.match(uri)) {
175 case STUDENTS:
176 qb.setProjectionMap(STUDENTS_PROJECTION_MAP);
177 break;
178
179 case STUDENT_ID:
180 qb.appendWhere( _ID + "=" + uri.getPathSegments().get(1));
181 break;
182
183 default:
184 }
185
186 if (sortOrder == null || sortOrder == ""){
187 /**
188 * By default sort on student names
189 */
190 sortOrder = NAME;
191 }
192
193 Cursor c = qb.query(db, projection, selection,
194 selectionArgs,null, null, sortOrder);
195 /**
196 * register to watch a content URI for changes
197 */
198 c.setNotificationUri(getContext().getContentResolver(), uri);
199 return c;
200 }
201
202 @Override
203 public int delete(Uri uri, String selection, String[] selectionArgs) {
204 int count = 0;
205 switch (uriMatcher.match(uri)){
206 case STUDENTS:
207 count = db.delete(STUDENTS_TABLE_NAME, selection, selectionArgs);
208 break;
209
210 case STUDENT_ID:
211 String id = uri.getPathSegments().get(1);
212 count = db.delete( STUDENTS_TABLE_NAME, _ID + " = " + id +
213 (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
214 break;
215 default:
216 throw new IllegalArgumentException("Unknown URI " + uri);
217 }
218
219 getContext().getContentResolver().notifyChange(uri, null);
220 return count;
221 }
222
223 @Override
224 public int update(Uri uri, ContentValues values,
225 String selection, String[] selectionArgs) {
226 int count = 0;
227 switch (uriMatcher.match(uri)) {
228 case STUDENTS:
229 count = db.update(STUDENTS_TABLE_NAME, values, selection, selectionArgs);
230 break;
231
232 case STUDENT_ID:
233 count = db.update(STUDENTS_TABLE_NAME, values,
234 _ID + " = " + uri.getPathSegments().get(1) +
235 (!TextUtils.isEmpty(selection) ? " AND (" +selection + ')' : ""), selectionArgs);
236 break;
237 default:
238 throw new IllegalArgumentException("Unknown URI " + uri );
239 }
240
241 getContext().getContentResolver().notifyChange(uri, null);
242 return count;
243 }
244
245 @Override
246 public String getType(Uri uri) {
247 switch (uriMatcher.match(uri)){
248 /**
249 * Get all student records
250 */
251 case STUDENTS:
252 return "vnd.android.cursor.dir/vnd.example.students";
253 /**
254 * Get a particular student
255 */
256 case STUDENT_ID:
257 return "vnd.android.cursor.item/vnd.example.students";
258 default:
259 throw new IllegalArgumentException("Unsupported URI: " + uri);
260 }
261 }
262}
263
264<!--/**********************-->
265 <!-- activity_main.xml -->
266<!--*********************/-->
267
268<?xml version="1.0" encoding="utf-8"?>
269<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
270 xmlns:tools="http://schemas.android.com/tools"
271 android:layout_width="match_parent"
272 android:layout_height="match_parent"
273 tools:context="com.androidii.martial.contentprovider.MainActivity">
274
275 <TextView
276 android:id="@+id/textView1"
277 android:layout_width="wrap_content"
278 android:layout_height="wrap_content"
279 android:text="Content provider"
280 android:layout_alignParentTop="true"
281 android:layout_centerHorizontal="true"
282 android:textSize="30dp" />
283
284 <TextView
285 android:id="@+id/textView2"
286 android:layout_width="wrap_content"
287 android:layout_height="wrap_content"
288 android:text="Tutorials point "
289 android:textColor="#ff87ff09"
290 android:textSize="30dp"
291 android:layout_below="@+id/textView1"
292 android:layout_centerHorizontal="true" />
293
294 <ImageButton
295 android:layout_width="200dp"
296 android:layout_height="200dp"
297 android:id="@+id/imageButton"
298 android:src="@drawable/abc"
299 android:layout_below="@+id/textView2"
300 android:layout_centerHorizontal="true" />
301
302 <Button
303 android:layout_width="wrap_content"
304 android:layout_height="wrap_content"
305 android:id="@+id/button2"
306 android:text="Add Name"
307 android:layout_below="@+id/editText3"
308 android:layout_alignRight="@+id/textView2"
309 android:layout_alignEnd="@+id/textView2"
310 android:layout_alignLeft="@+id/textView2"
311 android:layout_alignStart="@+id/textView2"
312 android:onClick="onClickAddName"/>
313
314 <EditText
315 android:layout_width="wrap_content"
316 android:layout_height="wrap_content"
317 android:id="@+id/editText"
318 android:layout_below="@+id/imageButton"
319 android:layout_alignRight="@+id/imageButton"
320 android:layout_alignEnd="@+id/imageButton" />
321
322 <EditText
323 android:layout_width="wrap_content"
324 android:layout_height="wrap_content"
325 android:id="@+id/editText2"
326 android:layout_alignTop="@+id/editText"
327 android:layout_alignLeft="@+id/textView1"
328 android:layout_alignStart="@+id/textView1"
329 android:layout_alignRight="@+id/textView1"
330 android:layout_alignEnd="@+id/textView1"
331 android:hint="Name"
332 android:textColorHint="@android:color/holo_blue_light" />
333
334 <EditText
335 android:layout_width="wrap_content"
336 android:layout_height="wrap_content"
337 android:id="@+id/editText3"
338 android:layout_below="@+id/editText"
339 android:layout_alignLeft="@+id/editText2"
340 android:layout_alignStart="@+id/editText2"
341 android:layout_alignRight="@+id/editText2"
342 android:layout_alignEnd="@+id/editText2"
343 android:hint="Grade"
344 android:textColorHint="@android:color/holo_blue_bright" />
345
346 <Button
347 android:layout_width="wrap_content"
348 android:layout_height="wrap_content"
349 android:text="Retrieve student"
350 android:id="@+id/button"
351 android:layout_below="@+id/button2"
352 android:layout_alignRight="@+id/editText3"
353 android:layout_alignEnd="@+id/editText3"
354 android:layout_alignLeft="@+id/button2"
355 android:layout_alignStart="@+id/button2"
356 android:onClick="onClickRetrieveStudents"/>
357</RelativeLayout>
358
359<!--/**********************-->
360 <!-- AndroidManifest.xml -->
361<!--*********************/-->
362
363<?xml version="1.0" encoding="utf-8"?>
364<manifest xmlns:android="http://schemas.android.com/apk/res/android"
365 package="com.androidii.martial.contentprovider">
366
367 <application
368 android:allowBackup="true"
369 android:icon="@mipmap/ic_launcher"
370 android:label="@string/app_name"
371 android:roundIcon="@mipmap/ic_launcher_round"
372 android:supportsRtl="true"
373 android:theme="@style/AppTheme">
374 <activity android:name=".MainActivity">
375 <intent-filter>
376 <action android:name="android.intent.action.MAIN" />
377
378 <category android:name="android.intent.category.LAUNCHER" />
379 </intent-filter>
380 </activity>
381
382 <provider android:name="StudentsProvider"
383 android:authorities="com.example.MyApplication.StudentsProvider"
384 android:enabled="true"
385 android:exported="true"/>
386 </application>
387
388</manifest>