Java Code Examples for android.database.Cursor.getColumnIndex()

The following are Jave code examples for showing how to use getColumnIndex() of the android.database.Cursor class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: androidnative.pri   File: VideoPicker.java   View Source Code Vote up 6 votes
static private Uri resolveUri(Uri uri) {
    Activity activity = org.qtproject.qt5.android.QtNative.activity();

    String[] columns = { MediaStore.Video.Media.DATA };

    Cursor cursor = activity.getContentResolver().query(uri, columns, null, null, null);
    if (cursor == null) {
        Log.d(TAG,"Query failed");
        return Uri.parse("");
    }

    cursor.moveToFirst();
    int columnIndex;

    columnIndex = cursor.getColumnIndex(columns[0]);
    String path = cursor.getString(columnIndex);

    cursor.close();
    return Uri.fromParts("file",path,"");
}
 
Example 2
Project: android-dev-challenge   File: TestUtilities.java   View Source Code Vote up 6 votes
/**
 * This method iterates through a set of expected values and makes various assertions that
 * will pass if our app is functioning properly.
 *
 * @param error          Message when an error occurs
 * @param valueCursor    The Cursor containing the actual values received from an arbitrary query
 * @param expectedValues The values we expect to receive in valueCursor
 */
static void validateCurrentRecord(String error, Cursor valueCursor, ContentValues expectedValues) {
    Set<Map.Entry<String, Object>> valueSet = expectedValues.valueSet();

    for (Map.Entry<String, Object> entry : valueSet) {
        String columnName = entry.getKey();
        int index = valueCursor.getColumnIndex(columnName);

        /* Test to see if the column is contained within the cursor */
        String columnNotFoundError = "Column '" + columnName + "' not found. " + error;
        assertFalse(columnNotFoundError, index == -1);

        /* Test to see if the expected value equals the actual value (from the Cursor) */
        String expectedValue = entry.getValue().toString();
        String actualValue = valueCursor.getString(index);

        String valuesDontMatchError = "Actual value '" + actualValue
                + "' did not match the expected value '" + expectedValue + "'. "
                + error;

        assertEquals(valuesDontMatchError,
                expectedValue,
                actualValue);
    }
}
 
Example 3
Project: android-dev-challenge   File: TestUtilities.java   View Source Code Vote up 6 votes
/**
 * This method iterates through a set of expected values and makes various assertions that
 * will pass if our app is functioning properly.
 *
 * @param error          Message when an error occurs
 * @param valueCursor    The Cursor containing the actual values received from an arbitrary query
 * @param expectedValues The values we expect to receive in valueCursor
 */
static void validateCurrentRecord(String error, Cursor valueCursor, ContentValues expectedValues) {
    Set<Map.Entry<String, Object>> valueSet = expectedValues.valueSet();

    for (Map.Entry<String, Object> entry : valueSet) {
        String columnName = entry.getKey();
        int index = valueCursor.getColumnIndex(columnName);

        /* Test to see if the column is contained within the cursor */
        String columnNotFoundError = "Column '" + columnName + "' not found. " + error;
        assertFalse(columnNotFoundError, index == -1);

        /* Test to see if the expected value equals the actual value (from the Cursor) */
        String expectedValue = entry.getValue().toString();
        String actualValue = valueCursor.getString(index);

        String valuesDontMatchError = "Actual value '" + actualValue
                + "' did not match the expected value '" + expectedValue + "'. "
                + error;

        assertEquals(valuesDontMatchError,
                expectedValue,
                actualValue);
    }
}
 
Example 4
Project: OneTwo   File: CounterFragment.java   View Source Code Vote up 6 votes
private void updateUI() {
    ArrayList<String> objList = new ArrayList<>();
    ArrayList<Integer> numList = new ArrayList<>();
    SQLiteDatabase db = mHelper.getReadableDatabase();
    Cursor cursor = db.query(TaskContract.TaskEntry.TABLE,
            new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.COL_TASK_TITLE, TaskContract.TaskEntry.COL_NUM_TITLE},
            null, null, null, null, null);
    while (cursor.moveToNext()) {
        int idx = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
        int idx_num = cursor.getColumnIndex(TaskContract.TaskEntry.COL_NUM_TITLE);
        objList.add(cursor.getString(idx));
        numList.add(cursor.getInt(idx_num));
    }

    mListAdapter.setData(objList, numList);
    cursor.close();
    db.close();

    if (objList.size() > 0) {
        instructionTextView.setVisibility(View.INVISIBLE);
    }else {
        instructionTextView.setVisibility(View.VISIBLE);
    }
}
 
Example 5
Project: syncplayer   File: videoPlayer.java   View Source Code Vote up 5 votes
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            Uri selectedFile = data.getData();
            if (selectedFile != null) {
                mService.setUri(selectedFile);

                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                retriever.setDataSource(getApplicationContext(), selectedFile);
                String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                long duration = Long.parseLong(time );

                int size = 0;
                Cursor cursor = getContentResolver()
                        .query(selectedFile, null, null, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    size = cursor.getColumnIndex(OpenableColumns.SIZE);
                    if (!cursor.isNull(size)) {
                        // Technically the column stores an int, but cursor.getString()
                        // will do the conversion automatically.
                        size = cursor.getInt(size);
                    }
                }
                mService.mSyncPlayClient.set_file(duration / 1000, size, getFileName(selectedFile));
                mService.preparePlayer();
            } else if (resultCode != REQUEST_INVITE) {
                Toast.makeText(this, "Error loading the file.", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }
}
 
Example 6
Project: PSNine   File: FileUtils.java   View Source Code Vote up 5 votes
public static File getImageFile(Context context, Uri selectedImage) {
    String[] filePathColumn = {MediaStore.Images.Media.DATA};
    Cursor cursor = context.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
    cursor.moveToFirst();
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String imagePath = cursor.getString(columnIndex);
    cursor.close();
    return new File(imagePath);
}
 
Example 7
Project: GitHub   File: MediaStoreDataLoader.java   View Source Code Vote up 5 votes
private List<MediaStoreData> query(Uri contentUri, String[] projection, String sortByCol,
    String idCol, String dateTakenCol, String dateModifiedCol, String mimeTypeCol,
    String orientationCol, MediaStoreData.Type type) {
  final List<MediaStoreData> data = new ArrayList<MediaStoreData>();
  Cursor cursor = getContext().getContentResolver()
      .query(contentUri, projection, null, null, sortByCol + " DESC");

  if (cursor == null) {
    return data;
  }

  try {
    final int idColNum = cursor.getColumnIndexOrThrow(idCol);
    final int dateTakenColNum = cursor.getColumnIndexOrThrow(dateTakenCol);
    final int dateModifiedColNum = cursor.getColumnIndexOrThrow(dateModifiedCol);
    final int mimeTypeColNum = cursor.getColumnIndex(mimeTypeCol);
    final int orientationColNum = cursor.getColumnIndexOrThrow(orientationCol);

    while (cursor.moveToNext()) {
      long id = cursor.getLong(idColNum);
      long dateTaken = cursor.getLong(dateTakenColNum);
      String mimeType = cursor.getString(mimeTypeColNum);
      long dateModified = cursor.getLong(dateModifiedColNum);
      int orientation = cursor.getInt(orientationColNum);

      data.add(new MediaStoreData(id, Uri.withAppendedPath(contentUri, Long.toString(id)),
          mimeType, dateTaken, dateModified, orientation, type));
    }
  } finally {
    cursor.close();
  }

  return data;
}
 
Example 8
Project: keemob   File: ContentFilesystem.java   View Source Code Vote up 5 votes
protected Long lastModifiedDateForCursor(Cursor cursor) {
       int columnIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DATE_MODIFIED);
       if (columnIndex == -1) {
           columnIndex = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_LAST_MODIFIED);
       }
       if (columnIndex != -1) {
           String dateStr = cursor.getString(columnIndex);
           if (dateStr != null) {
               return Long.parseLong(dateStr);
           }
       }
       return null;
}
 
Example 9
Project: IslamicLibraryAndroid   File: UserDataDBHelper.java   View Source Code Vote up 5 votes
public Highlight getHighlightById(int highlightId, int pageId, Context mContext, int bookId) {
    Cursor c = getReadableDatabase().query(UserDataDBContract.HighlightEntry.TABLE_NAME,
            new String[]{
                    UserDataDBContract.HighlightEntry.COLUMN_CLASS_NAME,
                    UserDataDBContract.HighlightEntry.COLUMN_CONTAINER_ELEMENT_ID,
                    UserDataDBContract.HighlightEntry.COLUMN_TEXT,
                    UserDataDBContract.HighlightEntry.COLUMN_NAME_TIME_STAMP,
                    UserDataDBContract.HighlightEntry.COLUMN_NOTE_TEXT
            },
            UserDataDBContract.HighlightEntry.COLUMN_NAME_BOOK_ID + "=?" + " and " +
                    UserDataDBContract.HighlightEntry.COLUMN_NAME_PAGE_ID + "=?" + " and " +
                    UserDataDBContract.HighlightEntry.COLUMN_NAME_HIGHLIGHT_ID + "=?",
            new String[]{String.valueOf(bookId), String.valueOf(pageId), String.valueOf(highlightId)},
            null,
            null,
            UserDataDBContract.BookmarkEntry.COLUMN_NAME_PAGE_ID
    );


    final int INDEX_CLASS_NAME = c.getColumnIndex(UserDataDBContract.HighlightEntry.COLUMN_CLASS_NAME);
    final int INDEX_ELEMENT_ID = c.getColumnIndex(UserDataDBContract.HighlightEntry.COLUMN_CONTAINER_ELEMENT_ID);
    final int INDEX_TEXT = c.getColumnIndex(UserDataDBContract.HighlightEntry.COLUMN_TEXT);
    final int INDEX_NOTE_TEXT = c.getColumnIndex(UserDataDBContract.HighlightEntry.COLUMN_NOTE_TEXT);
    final int INDEX_TIME_STAMP = c.getColumnIndex(UserDataDBContract.HighlightEntry.COLUMN_NAME_TIME_STAMP);
    BookDatabaseHelper bookDatabaseHelper = BookDatabaseHelper.getInstance(mContext, bookId);
    Highlight highlight = null;
    if (c.moveToFirst()) {
        PageInfo pageInfo = bookDatabaseHelper.getPageInfoByPageId(pageId);
        String className = c.getString(INDEX_CLASS_NAME);
        int elementId = c.getInt(INDEX_ELEMENT_ID);
        String timeStamp = c.getString(INDEX_TIME_STAMP);
        String text = c.getString(INDEX_TEXT);
        String noteText = c.getString(INDEX_NOTE_TEXT);
        highlight = new Highlight(text, highlightId, className, elementId, timeStamp, pageInfo, bookId, bookDatabaseHelper.getParentTitle(pageId), noteText);
    }
    c.close();
    return highlight;
}
 
Example 10
Project: alerta-fraude   File: ContentFilesystem.java   View Source Code Vote up 5 votes
protected Long lastModifiedDateForCursor(Cursor cursor) {
       int columnIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DATE_MODIFIED);
       if (columnIndex == -1) {
           columnIndex = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_LAST_MODIFIED);
       }
       if (columnIndex != -1) {
           String dateStr = cursor.getString(columnIndex);
           if (dateStr != null) {
               return Long.parseLong(dateStr);
           }
       }
       return null;
}
 
Example 11
Project: EasyEmoji   File: CommonUtil.java   View Source Code Vote up 5 votes
public static String getContactNameByPhoneNumber(Context context, String address) {
    String[] projection = {ContactsContract.PhoneLookup.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER};
    // 将自己添加到 msPeers 中
    Cursor cursor = context.getContentResolver().query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            projection,
            ContactsContract.CommonDataKinds.Phone.NUMBER + " = '"
                    + address + "'", null,null);
    if (cursor == null) {
        return null;
    }
    try {
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToPosition(i);
            // 取得联系人名字
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
            String name = cursor.getString(nameFieldColumnIndex);
            return name;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        cursor.close();
        cursor = null;
    }
    return null;
}
 
Example 12
Project: RLibrary   File: ContactsPickerHelper.java   View Source Code Vote up 5 votes
/**
     * 同步返回联系人列表
     */
    public static List<ContactsInfo> getContactsList(Context context) {

        //检查权限
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                return  new ArrayList<>();
            }
        }

        final ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, new String[]{"_id"}, null, null, null);
        List<ContactsInfo> contactsInfos = new ArrayList<>();

        if (cursor != null) {
            //枚举所有联系人的id
            if (cursor.getCount() > 0) {
                L.w("联系人总数量:" + cursor.getCount()); //就是联系人的总数
                int count = 0;
                if (cursor.moveToFirst()) {
                    do {
                        int contactIdIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);//获取 id 所在列的索引
                        String contactId = cursor.getString(contactIdIndex);//联系人id

                        final List<String> phones = getData1(contentResolver, contactId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                        if (phones.isEmpty()) {
                            continue;
                        } else {
                            String name;
                            final List<String> names = getData1(contentResolver, contactId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
                            if (names.isEmpty()) {
                                name = phones.get(0);
                            } else {
                                name = names.get(0);
                            }

                            //相同联系人的不同手机号码视为不同的联系人
                            for (String phone : phones) {
                                // 去除非手机号
                                if (!RegexUtils.isMobileExact(StringUtil.removeBlanks(phone))) {
                                    continue;
                                }
                                ContactsInfo io = new ContactsInfo();
                                io.contactId = contactId;
                                io.name = name;
                                io.phone = StringUtil.removeBlanks(phone);
                                io.letter = String.valueOf(Pinyin.toPinyin(name.charAt(0)).toUpperCase().charAt(0));
                                contactsInfos.add(io);
                            }
                        }

//                    L.e("-------------------------" + count + "----------------------");
//                    L.w("联系人ID:" + contactId);
//                    final String name = getData1(contentResolver, contactId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
//                    L.w("联系人名称:" + Pinyin.toPinyin(name.charAt(0)).toUpperCase().charAt(0) + " " + name);
//                    L.w("联系人电话:" + getData1(contentResolver, contactId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE));
//                    logData(contentResolver, contactId);
//                    count++;
                    } while (cursor.moveToNext());
                }
            }
            cursor.close();
        }
        return contactsInfos;
    }
 
Example 13
Project: BlackList   File: DatabaseAccessHelper.java   View Source Code Vote up 5 votes
ContactCursorWrapper(Cursor cursor) {
    super(cursor);
    cursor.moveToFirst();
    ID = cursor.getColumnIndex(ContactTable.Column.ID);
    NAME = getColumnIndex(ContactTable.Column.NAME);
    TYPE = getColumnIndex(ContactTable.Column.TYPE);
}
 
Example 14
Project: aos-Video   File: TvshowFragment.java   View Source Code Vote up 5 votes
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
    if (cursorLoader.getId()==SEASONS_LOADER_ID) {
        //TODO:
        // CAUTION: we get an update here each time a single episode resume point is changed...
        // Basic solution: fill the season rows only the first time, i.e. guess it does not change over
        // time, which is true with the current feature set at least...

        cursor.moveToFirst();
        final int seasonNumberColumn = cursor.getColumnIndex(VideoStore.Video.VideoColumns.SCRAPER_E_SEASON);

        mSeasonAdapters = new SparseArray<CursorObjectAdapter>();

        // Build one row for each season
        while (!cursor.isAfterLast()) {
            int seasonNumber = cursor.getInt(seasonNumberColumn);
            CursorObjectAdapter seasonAdapter = new CursorObjectAdapter(new PosterImageCardPresenter(getActivity(), PosterImageCardPresenter.EpisodeDisplayMode.FOR_SEASON_LIST));
            seasonAdapter.setMapper(new CompatibleCursorMapperConverter(new VideoCursorMapper()));
            mSeasonAdapters.put(seasonNumber, seasonAdapter);
            mRowsAdapter.add(new ListRow(seasonNumber,
                    new HeaderItem(seasonNumber, "Season " + seasonNumber),
                    seasonAdapter));
            getLoaderManager().restartLoader(seasonNumber, null, this);
            cursor.moveToNext();
        }
        cursor.close();
    }
    else {
        // We got the list of episode for one season, load it
        mSeasonAdapters.get(cursorLoader.getId()).changeCursor(cursor);
    }
}
 
Example 15
Project: XERUNG   File: Comman.java   View Source Code Vote up 5 votes
public String getRealPathFromURI(Context context, String contentURI) {
    Uri contentUri = Uri.parse(contentURI);
    Cursor cursor = context.getContentResolver().query(contentUri, null, null, null, null);
    if (cursor == null) {
        return contentUri.getPath();
    } else {
        cursor.moveToFirst();
        int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(index);
    }
}
 
Example 16
Project: aos-Video   File: SeasonHeaderCursorMapper.java   View Source Code Vote up 5 votes
@Override
public void bindColumns(Cursor c) {
    mIdColumn = c.getColumnIndex(BaseColumns._ID);
    mScraperTypeColumn = c.getColumnIndex(VideoStore.Video.VideoColumns.ARCHOS_MEDIA_SCRAPER_TYPE);

    mNameColumn = c.getColumnIndex(VideoLoader.COLUMN_NAME);

    // Episodes stuff
    mEpisodeIdColumn = c.getColumnIndex(VideoStore.Video.VideoColumns.SCRAPER_EPISODE_ID);
    mEpisodeSeasonColumn = c.getColumnIndex(VideoStore.Video.VideoColumns.SCRAPER_E_SEASON);
    mEpisodeNumberColumn = c.getColumnIndex(VideoStore.Video.VideoColumns.SCRAPER_E_EPISODE);
    mEpisodeNameColumn = c.getColumnIndex(VideoStore.Video.VideoColumns.SCRAPER_E_NAME);

    // Movies stuff
    mMovieIdColumn =  c.getColumnIndex(VideoStore.Video.VideoColumns.SCRAPER_MOVIE_ID);

    // Movies/Episodes common stuff
    mBackdropUrlColumn = c.getColumnIndex(VideoStore.Video.VideoColumns.SCRAPER_BACKDROP_LARGE_URL);
    mBackdropFileColumn = c.getColumnIndex(VideoStore.Video.VideoColumns.SCRAPER_BACKDROP_LARGE_FILE);
    mDateColumn = c.getColumnIndex(VideoLoader.COLUMN_DATE);
    mRatingColumn = c.getColumnIndex(VideoLoader.COLUMN_RATING);
    mPlotColumn = c.getColumnIndex(VideoLoader.COLUMN_PLOT);

    mShowNameColumn = c.getColumnIndex(VideoStore.Video.VideoColumns.SCRAPER_TITLE);
    mPathColumn = c.getColumnIndex(VideoStore.MediaColumns.DATA);
    mPosterPathColumn = c.getColumnIndex(VideoLoader.COLUMN_COVER_PATH);
    mDurationColumn = c.getColumnIndex(VideoStore.Video.VideoColumns.DURATION);
    mResumeColumn = c.getColumnIndex(VideoStore.Video.VideoColumns.BOOKMARK);
    mBookmarkColumn = c.getColumnIndex(VideoStore.Video.VideoColumns.ARCHOS_BOOKMARK);
    m3dColumn = c.getColumnIndex(VideoStore.Video.VideoColumns.ARCHOS_VIDEO_STEREO);
    mGuessedDefinitionColumn = c.getColumnIndex(VideoStore.Video.VideoColumns.ARCHOS_VIDEO_DEFINITION);

    // Trakt
    mTraktSeenColumn = c.getColumnIndex(VideoStore.Video.VideoColumns.ARCHOS_TRAKT_SEEN);
    mTraktLibraryColumn = c.getColumnIndex(VideoStore.Video.VideoColumns.ARCHOS_TRAKT_LIBRARY);
    // User can show/hide some files
    mUserHiddenColumn = c.getColumnIndex(VideoStore.Video.VideoColumns.ARCHOS_HIDDEN_BY_USER);
}
 
Example 17
Project: TextReader   File: ScanLocalBookActivity.java   View Source Code Vote up 4 votes
private void queryFiles() {
    String[] projection = new String[]{MediaStore.Files.FileColumns._ID,
            MediaStore.Files.FileColumns.DATA,
            MediaStore.Files.FileColumns.SIZE
    };

    // cache
    String bookpath = FileUtils.createRootPath(AppUtils.getAppContext());

    // 查询后缀名为txt与pdf,并且不位于项目缓存中的文档
    Cursor cursor = getContentResolver().query(
            Uri.parse("content://media/external/file"),
            projection,
            MediaStore.Files.FileColumns.DATA + " not like ? and ("
                    + MediaStore.Files.FileColumns.DATA + " like ? or "
                    + MediaStore.Files.FileColumns.DATA + " like ? or "
                    + MediaStore.Files.FileColumns.DATA + " like ? or "
                    + MediaStore.Files.FileColumns.DATA + " like ? )",
            new String[]{"%" + bookpath + "%",
                    "%" + Constant.SUFFIX_TXT,
                    "%" + Constant.SUFFIX_PDF,
                    "%" + Constant.SUFFIX_EPUB,
                    "%" + Constant.SUFFIX_CHM}, null);

    if (cursor != null && cursor.moveToFirst()) {
        int idindex = cursor.getColumnIndex(MediaStore.Files.FileColumns._ID);
        int dataindex = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
        int sizeindex = cursor.getColumnIndex(MediaStore.Files.FileColumns.SIZE);
        List<Recommend.RecommendBooks> list = new ArrayList<>();


        do {
            String path = cursor.getString(dataindex);

            int dot = path.lastIndexOf("/");
            String name = path.substring(dot + 1);
            if (name.lastIndexOf(".") > 0)
                name = name.substring(0, name.lastIndexOf("."));

            Recommend.RecommendBooks books = new Recommend.RecommendBooks();
            books._id = name;
            books.path = path;
            books.title = name;
            books.isFromSD = true;
            books.lastChapter = FileUtils.formatFileSizeToString(cursor.getLong(sizeindex));

            list.add(books);
        } while (cursor.moveToNext());

        cursor.close();

        mAdapter.addAll(list);
    } else {
        mAdapter.clear();
    }
}
 
Example 18
Project: BlackList   File: ContactsAccessHelper.java   View Source Code Vote up 4 votes
private ContactNumberCursorWrapper(Cursor cursor) {
    super(cursor);
    cursor.moveToFirst();
    NUMBER = cursor.getColumnIndex(Phone.NUMBER);
}
 
Example 19
Project: androidtv-sample   File: Channel.java   View Source Code Vote up 4 votes
public static Channel fromCursor(Cursor cursor) {
    Builder builder = new Builder();
    int index = cursor.getColumnIndex(TvContract.Channels._ID);
    if (index >= 0 && !cursor.isNull(index)) {
        builder.setId(cursor.getLong(index));
    }
    index = cursor.getColumnIndex(TvContract.Channels.COLUMN_PACKAGE_NAME);
    if (index >= 0 && !cursor.isNull(index)) {
        builder.setPackageName(cursor.getString(index));
    }
    index = cursor.getColumnIndex(TvContract.Channels.COLUMN_INPUT_ID);
    if (index >= 0 && !cursor.isNull(index)) {
        builder.setInputId(cursor.getString(index));
    }
    index = cursor.getColumnIndex(TvContract.Channels.COLUMN_TYPE);
    if (index >= 0 && !cursor.isNull(index)) {
        builder.setType(cursor.getString(index));
    }
    index = cursor.getColumnIndex(TvContract.Channels.COLUMN_DISPLAY_NUMBER);
    if (index >= 0 && !cursor.isNull(index)) {
        builder.setDisplayNumber(cursor.getString(index));
    }
    index = cursor.getColumnIndex(TvContract.Channels.COLUMN_DISPLAY_NAME);
    if (index >= 0 && !cursor.isNull(index)) {
        builder.setDisplayName(cursor.getString(index));
    }
    index = cursor.getColumnIndex(TvContract.Channels.COLUMN_DESCRIPTION);
    if (index >= 0 && !cursor.isNull(index)) {
        builder.setDescription(cursor.getString(index));
    }
    index = cursor.getColumnIndex(TvContract.Channels.COLUMN_VIDEO_FORMAT);
    if (index >= 0 && !cursor.isNull(index)) {
        builder.setVideoFormat(cursor.getString(index));
    }
    index = cursor.getColumnIndex(TvContract.Channels.COLUMN_ORIGINAL_NETWORK_ID);
    if (index >= 0 && !cursor.isNull(index)) {
        builder.setOriginalNetworkId(cursor.getInt(index));
    }
    index = cursor.getColumnIndex(TvContract.Channels.COLUMN_TRANSPORT_STREAM_ID);
    if (index >= 0 && !cursor.isNull(index)) {
        builder.setTransportStreamId(cursor.getInt(index));
    }
    index = cursor.getColumnIndex(TvContract.Channels.COLUMN_SERVICE_ID);
    if (index >= 0 && !cursor.isNull(index)) {
        builder.setServiceId(cursor.getInt(index));
    }

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
        index = cursor.getColumnIndex(TvContract.Channels.COLUMN_APP_LINK_TEXT);
        if (index >= 0 && !cursor.isNull(index)) {
            builder.setAppLinkText(cursor.getString(index));
        }
        index = cursor.getColumnIndex(TvContract.Channels.COLUMN_APP_LINK_COLOR);
        if (index >= 0 && !cursor.isNull(index)) {
            builder.setAppLinkColor(cursor.getInt(index));
        }
        index = cursor.getColumnIndex(TvContract.Channels.COLUMN_APP_LINK_ICON_URI);
        if (index >= 0 && !cursor.isNull(index)) {
            builder.setAppLinkIconUri(cursor.getString(index));
        }
        index = cursor.getColumnIndex(TvContract.Channels.COLUMN_APP_LINK_POSTER_ART_URI);
        if (index >= 0 && !cursor.isNull(index)) {
            builder.setAppLinkPosterArtUri(cursor.getString(index));
        }
        index = cursor.getColumnIndex(TvContract.Channels.COLUMN_APP_LINK_INTENT_URI);
        if (index >= 0 && !cursor.isNull(index)) {
            builder.setAppLinkIntentUri(cursor.getString(index));
        }
    }
    return builder.build();
}
 
Example 20
Project: Perfect-Day   File: UpdateProgressTasks.java   View Source Code Vote up 4 votes
private static void updateFirebaseDatabase(Context context) {
    Cursor cursor;
    try {
        cursor = context.getContentResolver().query(TaskItemsContract.TaskItemsColumns.CONTENT_URI,
                null,
                null,
                null,
                null);
    } catch (Exception e) {
        Log.e(TAG, "Failed to asynchronously load data.");
        e.printStackTrace();
        return;
    }
    if (null == cursor) {
        return;
    }
    DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("users");
    Map<String, TaskItem> usersTask = new HashMap<String, TaskItem>();//
    FirebaseAuth auth = FirebaseAuth.getInstance();
    FirebaseUser user = auth.getCurrentUser();
    if (null == user) {
        return;
    }
    DatabaseReference userId = mDatabase.child(user.getUid()).child(TaskItemsContract.PATH_TASK_ITEMS);
    while (cursor.moveToNext()) {
        int idIndex = cursor.getColumnIndex(TaskItemsContract.TaskItemsColumns._ID);
        int itemDescriptionIndex = cursor.getColumnIndex(TaskItemsContract.TaskItemsColumns.COLUMN_NAME_DESCRIPTION);
        int colorIndex = cursor.getColumnIndex(TaskItemsContract.TaskItemsColumns.COLUMN_NAME_COLOR);
        int isFinishedIndex = cursor.getColumnIndex(TaskItemsContract.TaskItemsColumns.COLUMN_NAME_IS_FINISHED);
        int isTodayIndex = cursor.getColumnIndex(TaskItemsContract.TaskItemsColumns.COLUMN_NAME_IS_TODAY);
        int createdOn = cursor.getColumnIndex(TaskItemsContract.TaskItemsColumns.COLUMN_NAME_CREATED_AT);
        int streak = cursor.getColumnIndex(TaskItemsContract.TaskItemsColumns.COLUMN_NAME_STREAK);
        int dateList = cursor.getColumnIndex(TaskItemsContract.TaskItemsColumns.COLUMN_NAME_COMPLETED_DATES);
        TaskItem taskItem = new TaskItem();
        taskItem.setColor(cursor.getInt(colorIndex));
        taskItem.setDescription(cursor.getString(itemDescriptionIndex));
        taskItem.setIsFinished(cursor.getInt(isFinishedIndex));
        taskItem.setIsToday(cursor.getInt(isTodayIndex));
        taskItem.setCreatedOn(cursor.getString(createdOn));
        taskItem.setStreak(cursor.getInt(streak));
        taskItem.setListDates(cursor.getString(dateList));
        usersTask.put(cursor.getString(idIndex), taskItem);
    }
    cursor.close();
    userId.setValue(usersTask);
    Log.e(TAG, "fire_update");
}