Skip to content

Commit 3a91dca

Browse files
committed
[Android] finished query(), delete() for my content provider
bugs: update() waitToTest: insert()
1 parent f174a0a commit 3a91dca

File tree

6 files changed

+519
-269
lines changed

6 files changed

+519
-269
lines changed

AAD-Preparation/.idea/workspace.xml

Lines changed: 195 additions & 235 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

AAD-Preparation/app/src/main/java/com/catherine/materialdesignapp/adapters/AlbumAdapter.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,8 @@ public Bitmap getBitmapFromCache(String url) {
125125
ImageRequest imageRequest = ImageRequest.fromUri(url);
126126
CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(imageRequest, null);
127127
BinaryResource resource = ImagePipelineFactory.getInstance().getMainFileCache().getResource(cacheKey);
128+
if (resource == null)
129+
return null;
128130
File file = ((FileBinaryResource) resource).getFile();
129131
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
130132
} catch (Exception e) {
Lines changed: 45 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,60 @@
11
package com.catherine.materialdesignapp.jetpack.daos;
22

3+
import android.database.Cursor;
34
import androidx.lifecycle.LiveData;
4-
import androidx.room.Dao;
5-
import androidx.room.Insert;
6-
import androidx.room.OnConflictStrategy;
7-
import androidx.room.Query;
5+
import androidx.room.*;
6+
import androidx.sqlite.db.SupportSQLiteQuery;
87
import com.catherine.materialdesignapp.jetpack.entities.Album;
98

109
import java.util.List;
1110

1211
@Dao
1312
public interface AlbumDao {
13+
/**
14+
* @param album
15+
* @return _id (primary key)
16+
*/
1417
@Insert(onConflict = OnConflictStrategy.REPLACE)
15-
void insert(Album album);
18+
long insert(Album album);
1619

20+
@Insert(onConflict = OnConflictStrategy.REPLACE)
21+
void insertAll(Album[] albums);
22+
23+
/**
24+
* @return row ID
25+
*/
1726
@Query("DELETE FROM album_table")
18-
void deleteAll();
27+
int deleteAll();
28+
29+
/**
30+
* @return row ID
31+
*/
32+
@RawQuery
33+
int deleteByRawQuery(SupportSQLiteQuery query);
34+
35+
/**
36+
* @param album
37+
* @return row ID
38+
*/
39+
@Update
40+
int updateAll(Album[] album);
1941

20-
@Query("SELECT * from album_table ORDER BY `title` ASC")
42+
/**
43+
* update
44+
*
45+
* @param query
46+
* @return
47+
*/
48+
@RawQuery
49+
Cursor updateByRawQuery(SupportSQLiteQuery query);
50+
51+
@Query("SELECT * FROM album_table ORDER BY _id ASC")
2152
LiveData<List<Album>> getAllAlbums();
53+
54+
@RawQuery
55+
Cursor select(SupportSQLiteQuery query);
56+
57+
@Query("SELECT COUNT(*) FROM album_table")
58+
int count();
59+
2260
}

AAD-Preparation/app/src/main/java/com/catherine/materialdesignapp/jetpack/entities/Album.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.catherine.materialdesignapp.jetpack.entities;
22

33
import androidx.annotation.NonNull;
4+
import androidx.room.ColumnInfo;
45
import androidx.room.Entity;
56
import androidx.room.PrimaryKey;
67
import com.catherine.materialdesignapp.listeners.ProguardIgnored;
@@ -15,15 +16,26 @@ public class Album implements ProguardIgnored {
1516
private String artist;
1617

1718
@NonNull
18-
@PrimaryKey
1919
private String title;
2020

21+
@PrimaryKey(autoGenerate = true)
22+
@ColumnInfo(index = true, name = "_id")
23+
private long id;
24+
2125
private String url;
2226

2327
private String thumbnail_image;
2428

2529
private List<String> songs;
2630

31+
public long getId() {
32+
return id;
33+
}
34+
35+
public void setId(long id) {
36+
this.id = id;
37+
}
38+
2739
public String getImage() {
2840
return image;
2941
}
Lines changed: 205 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,72 +1,259 @@
11
package com.catherine.materialdesignapp.providers;
22

33
import android.content.ContentProvider;
4+
import android.content.ContentUris;
45
import android.content.ContentValues;
56
import android.content.UriMatcher;
67
import android.database.Cursor;
78
import android.net.Uri;
89
import android.text.TextUtils;
10+
import android.util.Log;
911
import androidx.annotation.NonNull;
1012
import androidx.annotation.Nullable;
1113
import androidx.room.Room;
14+
import androidx.sqlite.db.SimpleSQLiteQuery;
15+
import androidx.sqlite.db.SupportSQLiteQuery;
16+
import androidx.sqlite.db.SupportSQLiteQueryBuilder;
17+
import com.catherine.materialdesignapp.jetpack.StringListConverter;
18+
import com.catherine.materialdesignapp.jetpack.daos.AlbumDao;
1219
import com.catherine.materialdesignapp.jetpack.databases.AlbumRoomDatabase;
20+
import com.catherine.materialdesignapp.jetpack.entities.Album;
21+
22+
import java.util.Arrays;
1323

1424
public class AlbumsProvider extends ContentProvider {
1525
public final static String TAG = AlbumsProvider.class.getSimpleName();
1626
private final static String AUTHORITY = "com.catherine.materialdesignapp.providers.AlbumsProvider";
1727
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
1828

1929

30+
private static final int ALBUMS = 1;
31+
private static final int ALBUMS_ID = 2;
32+
2033
static {
21-
sURIMatcher.addURI(AUTHORITY, "albums", 0);
22-
sURIMatcher.addURI(AUTHORITY, "albums/#", 1);
34+
sURIMatcher.addURI(AUTHORITY, "albums", ALBUMS);
35+
sURIMatcher.addURI(AUTHORITY, "albums/#", ALBUMS_ID);
2336
}
2437

25-
private AlbumRoomDatabase albumRoomDatabase;
38+
private AlbumDao albumDao;
2639

2740

2841
@Override
2942
public boolean onCreate() {
30-
albumRoomDatabase = Room.databaseBuilder(getContext(),
43+
if (getContext() == null)
44+
return false;
45+
46+
AlbumRoomDatabase albumRoomDatabase = Room.databaseBuilder(getContext(),
3147
AlbumRoomDatabase.class, "album_database")
32-
// Wipes and rebuilds instead of migrating
33-
// if no Migration object.
34-
// Migration is not part of this practical.
3548
.fallbackToDestructiveMigration()
3649
.build();
50+
albumDao = albumRoomDatabase.albumDao();
3751
return true;
3852
}
3953

4054
@Override
4155
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
42-
String query = "SELECT title FROM album_table";
43-
String[] args = null;
44-
if (!TextUtils.isEmpty(sortOrder)) {
45-
query += " ORDER BY ? ASC";
46-
args = new String[]{sortOrder};
56+
SupportSQLiteQuery mQuery;
57+
switch (sURIMatcher.match(uri)) {
58+
case ALBUMS:
59+
mQuery = SupportSQLiteQueryBuilder
60+
.builder("album_table")
61+
.columns(projection)
62+
.selection(selection, selectionArgs)
63+
.orderBy(sortOrder)
64+
.create();
65+
return albumDao.select(mQuery);
66+
case ALBUMS_ID:
67+
if (!TextUtils.isEmpty(selection) && !selection.trim().contains("_id=")) {
68+
String mSelection = selection + " AND _id = ?";
69+
String[] mSelectionArgs = new String[selectionArgs.length + 1];
70+
System.arraycopy(selectionArgs, 0, mSelectionArgs, 0, selectionArgs.length);
71+
mSelectionArgs[mSelectionArgs.length - 1] = ContentUris.parseId(uri) + "";
72+
mQuery = SupportSQLiteQueryBuilder
73+
.builder("album_table")
74+
.columns(projection)
75+
.selection(mSelection, mSelectionArgs)
76+
.orderBy(sortOrder)
77+
.create();
78+
} else {
79+
mQuery = SupportSQLiteQueryBuilder
80+
.builder("album_table")
81+
.columns(projection)
82+
.selection(selection, selectionArgs)
83+
.orderBy(sortOrder)
84+
.create();
85+
}
86+
return albumDao.select(mQuery);
87+
default:
88+
throw new IllegalArgumentException("Unknown URI: " + uri);
4789
}
48-
return albumRoomDatabase.query(query, args);
4990
}
5091

5192

5293
@Override
5394
public String getType(@NonNull Uri uri) {
54-
return null;
95+
switch (sURIMatcher.match(uri)) {
96+
case ALBUMS:
97+
return "vnd.android.cursor.dir/" + AUTHORITY + "." + "albums";
98+
case ALBUMS_ID:
99+
return "vnd.android.cursor.item/" + AUTHORITY + "." + "albums/#";
100+
default:
101+
throw new IllegalArgumentException("Unknown URI: " + uri);
102+
}
55103
}
56104

57105
@Override
58106
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
59-
return null;
107+
if (getContext() == null || values == null)
108+
return null;
109+
110+
switch (sURIMatcher.match(uri)) {
111+
case ALBUMS:
112+
Album album = new Album();
113+
if (values.containsKey("title"))
114+
album.setTitle(values.getAsString("title"));
115+
116+
if (values.containsKey("artist"))
117+
album.setArtist(values.getAsString("artist"));
118+
119+
if (values.containsKey("image"))
120+
album.setImage(values.getAsString("image"));
121+
122+
if (values.containsKey("thumbnail_image"))
123+
album.setThumbnail_image(values.getAsString("thumbnail_image"));
124+
125+
if (values.containsKey("url"))
126+
album.setUrl(values.getAsString("url"));
127+
128+
if (values.containsKey("songs")) {
129+
album.setSongs(StringListConverter.fromString("songs"));
130+
}
131+
long id = albumDao.insert(album);
132+
getContext().getContentResolver().notifyChange(uri, null);
133+
return ContentUris.withAppendedId(uri, id);
134+
case ALBUMS_ID:
135+
throw new IllegalArgumentException("Invalid URI, cannot insert with _id: " + uri);
136+
default:
137+
throw new IllegalArgumentException("Unknown URI: " + uri);
138+
}
60139
}
61140

62141
@Override
63142
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
64-
return 0;
143+
int count;
144+
SimpleSQLiteQuery query;
145+
switch (sURIMatcher.match(uri)) {
146+
case ALBUMS:
147+
if (TextUtils.isEmpty(selection) || selection.trim().contains("_id="))
148+
throw new IllegalArgumentException("Invalid URI, cannot delete without _id: " + uri);
149+
150+
query = new SimpleSQLiteQuery("DELETE FROM album_table WHERE " + selection, selectionArgs);
151+
count = albumDao.deleteByRawQuery(query);
152+
getContext().getContentResolver().notifyChange(uri, null);
153+
return count;
154+
case ALBUMS_ID:
155+
if (getContext() == null)
156+
return -1;
157+
158+
String mSelection;
159+
String[] mSelectionArgs;
160+
if (TextUtils.isEmpty(selection)) {
161+
mSelection = "DELETE FROM album_table WHERE _id = ?";
162+
mSelectionArgs = new String[]{ContentUris.parseId(uri) + ""};
163+
} else if (!selection.trim().contains("_id=")) {
164+
mSelection = "DELETE FROM album_table WHERE " + selection + " AND _id = ?";
165+
mSelectionArgs = new String[selectionArgs.length + 1];
166+
System.arraycopy(selectionArgs, 0, mSelectionArgs, 0, selectionArgs.length);
167+
mSelectionArgs[mSelectionArgs.length - 1] = ContentUris.parseId(uri) + "";
168+
} else {
169+
throw new IllegalArgumentException("Invalid URI, cannot delete with duplicated _id: " + uri);
170+
}
171+
172+
query = new SimpleSQLiteQuery(mSelection, mSelectionArgs);
173+
count = albumDao.deleteByRawQuery(query);
174+
getContext().getContentResolver().notifyChange(uri, null);
175+
return count;
176+
default:
177+
throw new IllegalArgumentException("Unknown URI: " + uri);
178+
}
65179
}
66180

67181
@Override
68-
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
69-
return 0;
182+
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String
183+
selection, @Nullable String[] selectionArgs) {
184+
if (getContext() == null)
185+
return -1;
186+
187+
if (sURIMatcher.match(uri) != ALBUMS && sURIMatcher.match(uri) != ALBUMS_ID)
188+
throw new IllegalArgumentException("Invalid URI: " + uri);
189+
190+
if (values == null)
191+
throw new IllegalArgumentException("Invalid URI, cannot update without values: " + uri);
192+
193+
String header = "UPDATE album_table SET ";
194+
StringBuilder mQuery = new StringBuilder(header);
195+
if (values.containsKey("title"))
196+
mQuery.append(appendQuery(values, "title"));
197+
198+
if (values.containsKey("artist"))
199+
mQuery.append(appendQuery(values, "artist"));
200+
201+
if (values.containsKey("image"))
202+
mQuery.append(appendQuery(values, "image"));
203+
204+
if (values.containsKey("thumbnail_image"))
205+
mQuery.append(appendQuery(values, "thumbnail_image"));
206+
207+
if (values.containsKey("url"))
208+
mQuery.append(appendQuery(values, "url"));
209+
210+
if (values.containsKey("songs"))
211+
mQuery.append(appendQuery(values, "songs"));
212+
213+
if (header.length() == mQuery.length())
214+
throw new IllegalArgumentException("Invalid URI, cannot update with incorrect values: " + uri);
215+
216+
mQuery.delete(mQuery.length() - " AND ".length(), mQuery.length());
217+
218+
String[] mSelectionArgs = selectionArgs;
219+
if (sURIMatcher.match(uri) == ALBUMS) {
220+
if (!TextUtils.isEmpty(selection)) {
221+
mQuery.append(" WHERE ");
222+
mQuery.append(selection);
223+
}
224+
} else {
225+
// sURIMatcher.match(uri) == ALBUMS_ID
226+
if (TextUtils.isEmpty(selection)) {
227+
mQuery.append(" WHERE _id = ?");
228+
mSelectionArgs = new String[]{ContentUris.parseId(uri) + ""};
229+
} else if (!selection.trim().contains("_id=")) {
230+
mQuery.append(" WHERE ");
231+
mQuery.append(selection);
232+
mSelectionArgs = new String[selectionArgs.length + 1];
233+
System.arraycopy(selectionArgs, 0, mSelectionArgs, 0, selectionArgs.length);
234+
mSelectionArgs[mSelectionArgs.length - 1] = ContentUris.parseId(uri) + "";
235+
} else {
236+
throw new IllegalArgumentException("Invalid URI, cannot update with duplicated _id: " + uri);
237+
}
238+
}
239+
240+
Log.d(TAG, "query: " + mQuery.toString());
241+
Log.d(TAG, "args: " + Arrays.toString(mSelectionArgs));
242+
SimpleSQLiteQuery query = new SimpleSQLiteQuery(mQuery.toString(), mSelectionArgs);
243+
Cursor cursor = albumDao.updateByRawQuery(query);
244+
getContext().getContentResolver().notifyChange(uri, null);
245+
return cursor.getCount();
246+
}
247+
248+
private String appendQuery(ContentValues values, String str) {
249+
StringBuilder sb = new StringBuilder();
250+
if (values.containsKey(str)) {
251+
sb.append(str);
252+
sb.append(" = ");
253+
sb.append(values.getAsString(str));
254+
sb.append(" AND ");
255+
}
256+
return sb.toString();
70257
}
71258

72259
}

0 commit comments

Comments
 (0)