下面列出了android.database.MatrixCursor#addRow ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data == null) {
return;
}
long[] mNowPlaying = MusicUtils.getQueue();
String[] audioCols = new String[] { BaseColumns._ID, MediaColumns.TITLE, AudioColumns.ARTIST, AudioColumns.ALBUM};
MatrixCursor playlistCursor = new MatrixCursor(audioCols);
for(int i = 0; i < mNowPlaying.length; i++){
data.moveToPosition(-1);
while (data.moveToNext()) {
long audioid = data.getLong(data.getColumnIndexOrThrow(BaseColumns._ID));
if( audioid == mNowPlaying[i]) {
String trackName = data.getString(data.getColumnIndexOrThrow(MediaColumns.TITLE));
String artistName = data.getString(data.getColumnIndexOrThrow(AudioColumns.ARTIST));
String albumName = data.getString(data.getColumnIndexOrThrow(AudioColumns.ALBUM));
playlistCursor.addRow(new Object[] {audioid, trackName, artistName, albumName });
}
}
}
data.close();
mCursor = playlistCursor;
super.onLoadFinished(loader, playlistCursor);
}
@Test
public void functionShouldReturnTheSameObjectsAsListFromCursor() throws Exception {
MatrixCursor cursor = new MatrixCursor(new String[] { SIMPLE_ENTITY_COLUMN });
for (int i = 0; i != 5; i++) {
cursor.addRow(new Object[] { "row" + i });
}
List<SimpleEntity> reference = testSubject.listFromCursor(cursor, SimpleEntity.class);
List<SimpleEntity> fromFunction = Lists.newArrayList();
Function<Cursor, SimpleEntity> function = testSubject.getFunctionFor(SimpleEntity.class);
cursor.moveToFirst();
do {
fromFunction.add(function.apply(cursor));
} while (cursor.moveToNext());
assertThat(fromFunction).containsSequence(reference);
}
@Override
public Cursor loadInBackground() {
Cursor albums = super.loadInBackground();
MatrixCursor allAlbum = new MatrixCursor(COLUMNS);
int totalCount = 0;
String allAlbumCoverPath = "";
if (albums != null) {
while (albums.moveToNext()) {
totalCount += albums.getInt(albums.getColumnIndex(COLUMN_COUNT));
}
if (albums.moveToFirst()) {
allAlbumCoverPath = albums.getString(albums.getColumnIndex(MediaStore.MediaColumns.DATA));
}
}
allAlbum.addRow(new String[]{Album.ALBUM_ID_ALL, Album.ALBUM_ID_ALL, Album.ALBUM_NAME_ALL, allAlbumCoverPath,
String.valueOf(totalCount)});
return new MergeCursor(new Cursor[]{allAlbum, albums});
}
private Cursor getRecentsHeaderCursor() {
MatrixCursor recentsHeader = new MatrixCursor(CONTACT_PROJECTION);
recentsHeader.addRow(new Object[]{ null,
getContext().getString(R.string.ContactsCursorLoader_recent_chats),
"",
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
"",
ContactRepository.DIVIDER_TYPE });
return recentsHeader;
}
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
File file = this.mStrategy.getFileForUri(uri);
if (projection == null) {
projection = COLUMNS;
}
String[] cols = new String[projection.length];
Object[] values = new Object[projection.length];
String[] arr$ = projection;
int len$ = arr$.length;
int i$ = 0;
int i = 0;
while (i$ < len$) {
int i2;
String col = arr$[i$];
if ("_display_name".equals(col)) {
cols[i] = "_display_name";
i2 = i + 1;
values[i] = file.getName();
} else if ("_size".equals(col)) {
cols[i] = "_size";
i2 = i + 1;
values[i] = Long.valueOf(file.length());
} else {
i2 = i;
}
i$++;
i = i2;
}
cols = copyOf(cols, i);
values = copyOf(values, i);
MatrixCursor cursor = new MatrixCursor(cols, 1);
cursor.addRow(values);
return cursor;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
Context context = getContext();
MatrixCursor matrixCursor = new MatrixCursor(new String[]{
Database.TEXTURES_ID,
Database.TEXTURES_NAME,
Database.TEXTURES_WIDTH,
Database.TEXTURES_HEIGHT,
Database.TEXTURES_THUMB
});
matrixCursor.addRow(new Object[]{
-1,
context.getString(R.string.no_preset),
0,
0,
null
});
MergeCursor mergeCursor = new MergeCursor(new Cursor[]{
matrixCursor,
ShaderEditorApp.db.getTextures()
});
adapter = new TextureSpinnerAdapter(context, mergeCursor);
presetView = findViewById(R.id.backbuffer_preset);
presetView.setAdapter(adapter);
}
/**
* Query the casedb for the key/value pairs for a specific case.
*/
private Cursor queryCaseData(String caseId) {
//Demo only, we'll pull this out when we're doing this for real and centralize it/manage its lifecycle more carefully
SqlStorage<ACase> storage = CommCareApplication.instance().getUserStorage(ACase.STORAGE_KEY, ACase.class);
//Default projection.
MatrixCursor retCursor = new MatrixCursor(new String[] {CaseDataAPI.DataColumns._ID,
CaseDataAPI.DataColumns.CASE_ID,
CaseDataAPI.DataColumns.DATUM_ID,
CaseDataAPI.DataColumns.VALUE});
Case c;
try {
c = storage.getRecordForValue(ACase.INDEX_CASE_ID, caseId);
} catch(NoSuchElementException nsee) {
//No cases with a matching index.
return retCursor;
}
int i = 0;
Hashtable<String, String> properties = c.getProperties();
for(String key : properties.keySet()) {
retCursor.addRow(new Object[] {i, caseId, key, c.getPropertyString(key)});
++i;
}
return retCursor;
}
/**
* Return a cursor over the list of all fixture IDs and names
*/
private Cursor getFixtureNames() {
MatrixCursor retCursor = new MatrixCursor(new String[]{FixtureDataAPI.MetadataColumns._ID, FixtureDataAPI.MetadataColumns.FIXTURE_ID});
IStorageUtilityIndexed<FormInstance> userFixtureStorage = CommCareApplication.instance().getUserStorage("fixture", FormInstance.class);
for (IStorageIterator<FormInstance> userFixtures = userFixtureStorage.iterate(); userFixtures.hasMore(); ) {
FormInstance fi = userFixtures.nextRecord();
String instanceId = fi.getInstanceId();
retCursor.addRow(new Object[]{fi.getID(), instanceId});
}
return retCursor;
}
@Override public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
MatrixCursor result = new MatrixCursor(new String[] { KEY, VALUE });
for (Map.Entry<String, String> entry : storage.entrySet()) {
result.addRow(new Object[] { entry.getKey(), entry.getValue() });
}
return result;
}
private void populateSuggestionsAdapter(String query) {
final MatrixCursor c = new MatrixCursor(new String[]{BaseColumns._ID, "suggestion"});
List<String> suggestionsForQuery = getSuggestionsForQuery(query);
for (int i = 0, suggestionsForQuerySize = suggestionsForQuery.size(); i < suggestionsForQuerySize; i++) {
String suggestion = suggestionsForQuery.get(i);
c.addRow(new Object[]{i, suggestion});
}
mSearchSuggestionsAdapter.changeCursor(c);
}
/**
* Use a content URI returned by
* {@link #getUriForFile(Context, File) getUriForFile()} to get information about a file
* managed by the FileProvider.
* FileProvider reports the column names defined in {@link android.provider.OpenableColumns}:
* <ul>
* <li>{@link android.provider.OpenableColumns#DISPLAY_NAME}</li>
* <li>{@link android.provider.OpenableColumns#SIZE}</li>
* </ul>
* For more information, see
* {@link ContentProvider#query(Uri, String[], String, String[], String)
* ContentProvider.query()}.
*
* @param uri A content URI returned by {@link #getUriForFile}.
* @param projection The list of columns to put into the {@link Cursor}. If null all columns are
* included.
* @param selection Selection criteria to apply. If null then all data that matches the content
* URI is returned.
* @param selectionArgs An array of {@link java.lang.String}, containing arguments to bind to
* the <i>selection</i> parameter. The <i>query</i> method scans <i>selection</i> from left to
* right and iterates through <i>selectionArgs</i>, replacing the current "?" character in
* <i>selection</i> with the value at the current position in <i>selectionArgs</i>. The
* values are bound to <i>selection</i> as {@link java.lang.String} values.
* @param sortOrder A {@link java.lang.String} containing the column name(s) on which to sort
* the resulting {@link Cursor}.
* @return A {@link Cursor} containing the results of the query.
*/
@Override
public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
if (projection == null) {
projection = COLUMNS;
}
String[] cols = new String[projection.length];
Object[] values = new Object[projection.length];
int i = 0;
for (String col : projection) {
if (OpenableColumns.DISPLAY_NAME.equals(col)) {
cols[i] = OpenableColumns.DISPLAY_NAME;
values[i++] = file.getName();
} else if (OpenableColumns.SIZE.equals(col)) {
cols[i] = OpenableColumns.SIZE;
values[i++] = file.length();
} else if (COLUMN_LAST_MODIFIED.equals(col)) {
cols[i] = COLUMN_LAST_MODIFIED;
values[i++] = file.lastModified();
}
}
cols = copyOf(cols, i);
values = copyOf(values, i);
final MatrixCursor cursor = new MatrixCursor(cols, 1);
cursor.addRow(values);
return cursor;
}
@Override
public synchronized Cursor query(Uri uri, String[] projection,
String selection, String[] selectionArgs, String sortOrder) {
// Create simple cursor
MatrixCursor cursor = new MatrixCursor(DataContract.ALL_COLUMNS);
if (isTableUri(uri)) {
// Add all rows to cursor
for (int idx = 0; idx < db.size(); idx++) {
DataRecord dataRecord = db.get(db.keyAt(idx));
cursor.addRow(new Object[] { dataRecord.getID(),
dataRecord.getData() });
}
} else if (isItemUri(uri)){
// Add single row to cursor
Integer requestId = Integer.parseInt(uri.getLastPathSegment());
if (null != db.get(requestId)) {
DataRecord dr = db.get(requestId);
cursor.addRow(new Object[] { dr.getID(), dr.getData() });
}
}
return cursor;
}
@Override
public Cursor loadInBackground() {
Cursor mediaCursor = getContext().getContentResolver().query(mUri, mProjection, mSelection,
mSelectionArgs, mSortOrder);
//Get cursor filled with Audio Id's
String [] projection = new String[] {
BaseColumns._ID, AlbumColumns.ALBUM
};
Uri uri = Audio.Albums.EXTERNAL_CONTENT_URI;
String sortOrder = Audio.Albums.DEFAULT_SORT_ORDER;
Cursor albumCursor = getContext().getContentResolver().query(uri, projection, null, null, sortOrder);
//Matrix cursor to hold final data to be returned to calling context
MatrixCursor cursor = new MatrixCursor( new String[]
{ BaseColumns._ID, MediaColumns.TITLE, AudioColumns.ARTIST, AudioColumns.ALBUM, AudioColumns.ALBUM_ID});
//Map data from Audio Id cursor to the ALbumName Colum
ContentQueryMap mQueryMap = new ContentQueryMap(albumCursor, AlbumColumns.ALBUM, false, null);
Map<String, ContentValues> data = mQueryMap.getRows();
if (mediaCursor != null) {
while(mediaCursor.moveToNext()) {
String id = mediaCursor.getString(mediaCursor.getColumnIndexOrThrow(BaseColumns._ID));
String title = mediaCursor.getString(mediaCursor.getColumnIndexOrThrow(MediaColumns.TITLE));
String artist = mediaCursor.getString(mediaCursor.getColumnIndexOrThrow(AudioColumns.ARTIST));
String album = mediaCursor.getString(mediaCursor.getColumnIndexOrThrow(AudioColumns.ALBUM));
ContentValues tData = data.get(album);
String albumid = (String) tData.get(BaseColumns._ID);
cursor.addRow(new String[] {id, title, artist, album, albumid});
}
mediaCursor.close();
}
if (cursor != null) {
// Ensure the cursor window is filled
registerContentObserver(cursor, mObserver);
}
return cursor;
}
/**
* Use a content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()} to get information about a file
* managed by the FileProvider.
* FileProvider reports the column names defined in {@link android.provider.MediaStore.MediaColumns}:
* <ul>
* <li>{@link android.provider.MediaStore.MediaColumns#DISPLAY_NAME}</li>
* <li>{@link android.provider.MediaStore.MediaColumns#SIZE}</li>
* <li>{@link android.provider.MediaStore.MediaColumns#DATA}</li>
* </ul>
* For more information, see
* {@link ContentProvider#query(Uri, String[], String, String[], String)
* ContentProvider.query()}.
*
* @param uri A content URI returned by {@link #getUriForFile}.
* @param projection The list of columns to put into the {@link Cursor}. If null all columns are
* included.
* @param selection Selection criteria to apply. If null then all data that matches the content
* URI is returned.
* @param selectionArgs An array of {@link java.lang.String}, containing arguments to bind to
* the <i>selection</i> parameter. The <i>query</i> method scans <i>selection</i> from left to
* right and iterates through <i>selectionArgs</i>, replacing the current "?" character in
* <i>selection</i> with the value at the current position in <i>selectionArgs</i>. The
* values are bound to <i>selection</i> as {@link java.lang.String} values.
* @param sortOrder A {@link java.lang.String} containing the column name(s) on which to sort
* the resulting {@link Cursor}.
* @return A {@link Cursor} containing the results of the query.
*
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
if (projection == null) {
projection = COLUMNS;
}
String[] cols = new String[projection.length];
Object[] values = new Object[projection.length];
int i = 0;
for (String col : projection) {
if (MediaStore.MediaColumns.DISPLAY_NAME.equals(col)) {
cols[i] = MediaStore.MediaColumns.DISPLAY_NAME;
values[i++] = file.getName();
} else if (MediaStore.MediaColumns.SIZE.equals(col)) {
cols[i] = MediaStore.MediaColumns.SIZE;
values[i++] = file.length();
} else if (MediaStore.MediaColumns.DATA.equals(col)) {
cols[i] = MediaStore.MediaColumns.DATA;
values[i++] = file.getPath();
}
}
cols = copyOf(cols, i);
values = copyOf(values, i);
final MatrixCursor cursor = new MatrixCursor(cols, 1);
cursor.addRow(values);
return cursor;
}
@Override
public synchronized Cursor query(Uri uri, String[] projection,
String selection, String[] selectionArgs, String sortOrder) {
// Create simple cursor
MatrixCursor cursor = new MatrixCursor(DataContract.ALL_COLUMNS);
if (isTableUri(uri)) {
// Add all rows to cursor
for (int idx = 0; idx < db.size(); idx++) {
DataRecord dataRecord = db.get(db.keyAt(idx));
cursor.addRow(new Object[]{dataRecord.getID(),
dataRecord.getData()});
}
} else if (isItemUri(uri)) {
// Add single row to cursor
Integer requestId = Integer.parseInt(uri.getLastPathSegment());
if (null != db.get(requestId)) {
DataRecord dr = db.get(requestId);
cursor.addRow(new Object[]{dr.getID(), dr.getData()});
}
}
return cursor;
}
@Override
public Cursor loadInBackground() {
Cursor result = super.loadInBackground();
if (!mEnableCapture || !MediaStoreCompat.hasCameraFeature(getContext())) {
return result;
}
MatrixCursor dummy = new MatrixCursor(PROJECTION);
dummy.addRow(new Object[]{"-1", "capture", "", 0, ""});
return new MergeCursor(new Cursor[]{dummy, result});
}
private void getUsage(int uid, String restrictionName, String methodName, MatrixCursor cursor) {
SharedPreferences prefs = getContext().getSharedPreferences(PREF_USAGE + "." + restrictionName,
Context.MODE_PRIVATE);
String values = prefs.getString(getUsagePref(uid, methodName), null);
if (values != null) {
String[] value = values.split(":");
long timeStamp = Long.parseLong(value[0]);
boolean restricted = Boolean.parseBoolean(value[1]);
cursor.addRow(new Object[] { uid, restrictionName, methodName, restricted, timeStamp });
}
}
public ArrayList<Cursor> getData(String Query){
//get writable database
// TODO: Add Your Database Class Here
if (myClass == null)
{
throw new RuntimeException("myClass is not initialized yet!");
}
FlowSQLiteOpenHelper fom = new FlowSQLiteOpenHelper(FlowManager.getDatabase(myClass), null);
//SQLiteDatabase sqlDB = this.getWritableDatabase();
SQLiteDatabase sqlDB = fom.getWritableDatabase();
String[] columns = new String[] { "mesage" };
//an array list of cursor to save two cursors one has results from the query
//other cursor stores error message if any errors are triggered
ArrayList<Cursor> alc = new ArrayList<Cursor>(2);
MatrixCursor Cursor2= new MatrixCursor(columns);
alc.add(null);
alc.add(null);
try{
String maxQuery = Query ;
//execute the query results will be save in Cursor c
Cursor c = sqlDB.rawQuery(maxQuery, null);
//add value to cursor2
Cursor2.addRow(new Object[] { "Success" });
alc.set(1,Cursor2);
if (null != c && c.getCount() > 0) {
alc.set(0,c);
c.moveToFirst();
return alc ;
}
return alc;
} catch(SQLException sqlEx){
Log.d("printing exception", sqlEx.getMessage());
//if any exceptions are triggered save the error message to cursor an return the arraylist
Cursor2.addRow(new Object[] { ""+sqlEx.getMessage() });
alc.set(1,Cursor2);
return alc;
} catch(Exception ex){
Log.d("printing exception", ex.getMessage());
//if any exceptions are triggered save the error message to cursor an return the arraylist
Cursor2.addRow(new Object[] { ""+ex.getMessage() });
alc.set(1,Cursor2);
return alc;
}
}
private static MatrixCursor createCursor(final String[] columns) {
final MatrixCursor cursor = new MatrixCursor(columns);
cursor.addRow(new String[] { "test" });
cursor.moveToFirst();
return cursor;
}
@Override
public Cursor query(@NonNull Uri url, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Log.w(TAG, "query() called: " + url);
if (projection == null || projection.length <= 0) return null;
switch (uriMatcher.match(url)) {
case SINGLE_ROW:
PartUriParser partUri = new PartUriParser(url);
AttachmentRepo repo = Repository.getAttachmentRepo(AMELogin.INSTANCE.getMajorContext());
if (repo == null) {
ALog.w(TAG, "AttachmentRepo is null!");
return null;
}
AttachmentRecord attachmentRecord = repo.getAttachment(partUri.getPartId().getRowId(), partUri.getPartId().getUniqueId());
if (attachmentRecord == null) return null;
MatrixCursor matrixCursor = new MatrixCursor(projection, 1);
Object[] resultRow = new Object[projection.length];
for (int i = 0; i < projection.length; i++) {
if (OpenableColumns.DISPLAY_NAME.equals(projection[i])) {
resultRow[i] = attachmentRecord.getFileName();
}
}
matrixCursor.addRow(resultRow);
return matrixCursor;
case GROUP_ROW:
GroupUriParser uriParser = new GroupUriParser(url);
AmeGroupMessageDetail messageDetail = MessageDataManager.INSTANCE.fetchOneMessageByGidAndIndexId(AMELogin.INSTANCE.getMajorContext(), uriParser.getGid(), uriParser.getIndexId());
if (messageDetail == null || !messageDetail.getMessage().isFile()) return null;
MatrixCursor groupMatrixCursor = new MatrixCursor(projection, 1);
Object[] groupResultRow = new Object[projection.length];
for (int i = 0; i < projection.length; i++) {
if (OpenableColumns.DISPLAY_NAME.equals(projection[i])) {
groupResultRow[i] = ((AmeGroupMessage.FileContent) messageDetail.getMessage().getContent()).getFileName();
}
}
groupMatrixCursor.addRow(groupResultRow);
return groupMatrixCursor;
case UNENCRYPTED_ROW:
MatrixCursor ueMatrixCursor = new MatrixCursor(projection, 1);
Object[] ueResultRow = new Object[projection.length];
for (int i = 0; i < projection.length; i++) {
if (OpenableColumns.DISPLAY_NAME.equals(projection[i])) {
ueResultRow[i] = url.getLastPathSegment();
}
}
ueMatrixCursor.addRow(ueResultRow);
return ueMatrixCursor;
default:
break;
}
return null;
}