android.database.MatrixCursor#addRow ( )源码实例Demo

下面列出了android.database.MatrixCursor#addRow ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: mobile-manager-tool   文件: NowPlayingFragment.java
@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);
  }
 
源代码2 项目: microorm   文件: GetFunctionTest.java
@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);
}
 
源代码3 项目: AndroidDownload   文件: EssAlbumLoader.java
@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});
}
 
源代码4 项目: mollyim-android   文件: ContactsCursorLoader.java
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;
}
 
源代码5 项目: letv   文件: FileProvider.java
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;
}
 
源代码6 项目: ShaderEditor   文件: BackBufferParametersView.java
@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;
}
 
源代码9 项目: sqlbrite   文件: BriteContentResolverTest.java
@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;
}
 
源代码10 项目: matlog   文件: LogcatActivity.java
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);
}
 
源代码11 项目: trekarta   文件: ExportProvider.java
/**
 * 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;
}
 
源代码12 项目: coursera-android   文件: StringsContentProvider.java
@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;
}
 
源代码13 项目: mobile-manager-tool   文件: AddIdCursorLoader.java
@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;
  }
 
源代码14 项目: MHViewer   文件: FileProvider.java
/**
 * 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;
}
 
源代码15 项目: coursera-android   文件: StringsContentProvider.java
@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;
}
 
源代码16 项目: FilePicker   文件: EssMediaLoader.java
@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});
}
 
源代码17 项目: XPrivacy   文件: PrivacyProvider.java
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 });
	}
}
 
源代码18 项目: Meteorite   文件: DBFlowManagerActivity.java
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;
    }


}
 
源代码19 项目: arca-android   文件: ViewBinderTest.java
private static MatrixCursor createCursor(final String[] columns) {
	final MatrixCursor cursor = new MatrixCursor(columns);
	cursor.addRow(new String[] { "test" });
	cursor.moveToFirst();
	return cursor;
}
 
源代码20 项目: bcm-android   文件: PartProvider.java
@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;
}