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

The following are Jave code examples for showing how to use moveToNext() 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.
Example 1
Project: Musicoco   File: MediaManager.java   Source Code and License Vote up 6 votes
private synchronized String getAlbumArtPicPath(Context context, String albumId) {

        // 小米应用商店检测crash ,错误信息:[31188,0,com.duan.musicoco,13155908,java.lang.IllegalStateException,Unknown URL: content://media/external/audio/albums/null,Parcel.java,1548]
        if (!StringUtils.isReal(albumId)) {
            return null;
        }

        String[] projection = {MediaStore.Audio.Albums.ALBUM_ART};
        String imagePath = null;
        Uri uri = Uri.parse("content://media" + MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI.getPath() + "/" + albumId);

        Cursor cur = context.getContentResolver().query(uri, projection, null, null, null);
        if (cur == null) {
            return null;
        }

        if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
            cur.moveToNext();
            imagePath = cur.getString(0);
        }
        cur.close();


        return imagePath;
    }
 
Example 2
Project: schulcloud-mobile-android   File: CalendarContentUtil.java   Source Code and License Vote up 6 votes
public String getCalendarIdForName(String calendarName) {
    String selection = "(" + CalendarContract.Calendars.NAME + " = ?)";
    String[] selectionArgs = new String[] {calendarName};
    Cursor cursor = contentResolver.query(CALENDAR_URI, FIELDS, selection, selectionArgs, null);

    try {
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                String id = cursor.getString(0);
                return id;
            }
        }
    } catch (AssertionError ex) { /*TODO: log exception and bail*/ }

    return "";
}
 
Example 3
Project: My-Day   File: DatabaseHandler.java   Source Code and License Vote up 6 votes
public ArrayList<DayTask> getAllUndoneTasks(){
    SQLiteDatabase db = this.getReadableDatabase();
    ArrayList<DayTask> tasks = new ArrayList<>();
    String query = "SELECT * FROM " + VARS.TABLE_NAME + " WHERE " + VARS.STATUS + " = 'false'";
    Cursor cursor = db.rawQuery(query, null);
    cursor.moveToFirst();
    while(!cursor.isAfterLast()){
        DayTask dayTask = new DayTask(cursor.getInt(cursor.getColumnIndex(VARS.ID_NAME)), cursor.getString(cursor.getColumnIndex(VARS.STATUS)),
                cursor.getString(cursor.getColumnIndex(VARS.TITLE)), cursor.getString(cursor.getColumnIndex(VARS.DESCRIPTION)),
                cursor.getString(cursor.getColumnIndex(VARS.DATE)), cursor.getString(cursor.getColumnIndex(VARS.TIME)));
        tasks.add(dayTask);
        cursor.moveToNext();
    }
    cursor.close();
    db.close();
    return tasks;
}
 
Example 4
Project: FlashCards   File: DBHandler.java   Source Code and License Vote up 6 votes
public ArrayList<Deck> getDecks(int courseID){
    ArrayList<Deck> deckList = new ArrayList<Deck>();
    String selectQuery = "SELECT * FROM " + TABLE_DECK_DETAIL + " WHERE " + COURSE_ID + "=" + courseID;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    cursor.moveToFirst();
    System.out.println("DBHandler courseID in getDecks: " + courseID);
    //loop through all rows to return
    while(!cursor.isAfterLast()){
        Deck deck = new Deck(Integer.parseInt(cursor.getString(0)), courseID,
                cursor.getString(2), Integer.parseInt(cursor.getString(3)));
        deck.set_deckId(courseID);
        deckList.add(deck);

        //Log.i(TAG, "HERE WE ARE CourseID: " + courseID);
        cursor.moveToNext();
    }

    Log.i(TAG, "Return All Deck Names");
    db.close();

    return deckList;
}
 
Example 5
Project: TrainAppTFG   File: DatabaseAdapter.java   Source Code and License Vote up 6 votes
public List<ActivityDataTransfer> listarActividadesSistema(){
    List<ActivityDataTransfer> retList = new ArrayList<>();

    String query = "SELECT * FROM " + TABLA_ACTIVIDADES;
    Cursor c = db.rawQuery(query, null);

    while(c.moveToNext()){
        int id = c.getInt(c.getColumnIndex(KEY_ID));
        String actividad = c.getString(c.getColumnIndex(KEY_ACTIVIDAD));
        Date fCreacion = getDateFromSqlite(c.getString(c.getColumnIndex(KEY_FECHACREACION)));
        String url = c.getString(c.getColumnIndex(KEY_URL_IMAGE));

        ActivityDataTransfer activityDataTransfer = new ActivityDataTransfer(id, actividad, fCreacion, url);
        retList.add(activityDataTransfer);
    }

    return retList;
}
 
Example 6
Project: Matisse   File: AlbumLoader.java   Source Code and License Vote up 6 votes
@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});
}
 
Example 7
Project: Phoenicia   File: QuerySet.java   Source Code and License Vote up 5 votes
private List<T> createObjects(Cursor c) {
	List<T> items = new ArrayList<T>();
	
	while(c.moveToNext()) {
		T object = Model.createObject(mClass, c);
		
		if(object != null) {
			items.add(object);
		}
	}
	
	return items;
}
 
Example 8
Project: Orin   File: PlaylistSongLoader.java   Source Code and License Vote up 5 votes
@NonNull
public static ArrayList<PlaylistSong> getPlaylistSongList(@NonNull final Context context, final int playlistId) {
    ArrayList<PlaylistSong> songs = new ArrayList<>();
    Cursor cursor = makePlaylistSongCursor(context, playlistId);

    if (cursor != null && cursor.moveToFirst()) {
        do {
            songs.add(getPlaylistSongFromCursorImpl(cursor, playlistId));
        } while (cursor.moveToNext());
    }
    if (cursor != null) {
        cursor.close();
    }
    return songs;
}
 
Example 9
Project: SmartOrnament   File: SosContacterDAO.java   Source Code and License Vote up 5 votes
public SosContacter query(){
    Cursor cursor=db.rawQuery("select * from tb_sos where ischecked=1",null);
    if(cursor.moveToNext()){
        return  new SosContacter(cursor.getInt(cursor.getColumnIndex("_id")),cursor.getString(cursor.getColumnIndex("name")),
                cursor.getString(cursor.getColumnIndex("relation")),cursor.getString(cursor.getColumnIndex("phone")),
                cursor.getString(cursor.getColumnIndex("content")),cursor.getInt(cursor.getColumnIndex("ischecked")));
    }
    return null;
}
 
Example 10
Project: XERUNG   File: GroupDb.java   Source Code and License Vote up 5 votes
public ArrayList<ContactBean> getGroupMemberLimit(int pageSkip, int maxCount, String table) {

        ArrayList<ContactBean> gbList = new ArrayList<ContactBean>();
        try {
            String selectQuery = "SELECT " + MEMBER_NAME + ", " + MEMBER_PHONE + ", " + MEMBER_SEARCHKEY + ", " + MEMBER_UID + ", " + MEMBER_FLAG + ", " + MEMBER_ORG_NAME + ", "
                    + MEMBER_PH_BOK_NAME + ", " + MEMBER_ISMY_CONTACT + ", " + MEMBER_BLOOD_GROUP + ", " + MEMBER_ADMIN_FLAG + ", " + MEMBER_CREATED_DATE + " FROM " + table + " Order by " + MEMBER_CREATED_DATE + " " + "LIMIT " + pageSkip + ", " + maxCount;

            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);
            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    ContactBean contact = new ContactBean();
                    contact.setName(cursor.getString(0));
                    contact.setNumber(cursor.getString(1));
                    contact.setSearchKey(cursor.getString(2));
                    contact.setUID(cursor.getString(3));
                    contact.setRequestFlag(cursor.getString(4));
                    contact.setOrignalName(cursor.getString(5));
                    contact.setMyPhoneBookName(cursor.getString(6));
                    contact.setIsMyContact(cursor.getInt(7));
                    contact.setmBloodGroup(cursor.getString(8));
                    contact.setAdminFlag(cursor.getString(9));
                    contact.setmCreatedDate(cursor.getString(10));
                    gbList.add(contact);
                } while (cursor.moveToNext());
            }
            if (cursor != null)
                cursor.close();
            db.close();
        } catch (Exception e) {
            // TODO: handle exception
            //Log.e("GroupDBErro", "FetchAllDB " + e.getMessage());
            e.printStackTrace();
        }
        return gbList;
    }
 
Example 11
Project: AndroidDownloader   File: DefaultDownloadDBController.java   Source Code and License Vote up 5 votes
@SuppressWarnings("No problem")
@Override
public List<DownloadInfo> findAllDownloading() {
  Cursor cursor = readableDatabase.query(DefaultDownloadHelper.TABLE_NAME_DOWNLOAD_INFO,
      DOWNLOAD_INFO_COLUMNS, "status!=?", new String[]{
          String.valueOf(STATUS_COMPLETED)}, null, null, "createAt desc");

  List<DownloadInfo> downloads = new ArrayList<>();
  Cursor downloadCursor;
  while (cursor.moveToNext()) {
    DownloadInfo downloadInfo = new DownloadInfo();
    downloads.add(downloadInfo);

    inflateDownloadInfo(cursor, downloadInfo);

    //query download thread info
    downloadCursor = readableDatabase.query(DefaultDownloadHelper.TABLE_NAME_DOWNLOAD_THREAD_INFO,
        DOWNLOAD_THREAD_INFO_COLUMNS, "downloadInfoId=?", new String[]{
            String.valueOf(downloadInfo.getId())}, null, null, null);
    List<DownloadThreadInfo> downloadThreads = new ArrayList<>();
    while (downloadCursor.moveToNext()) {
      DownloadThreadInfo downloadThreadInfo = new DownloadThreadInfo();
      downloadThreads.add(downloadThreadInfo);
      inflateDownloadThreadInfo(downloadCursor, downloadThreadInfo);
    }

    downloadInfo.setDownloadThreadInfos(downloadThreads);

  }
  return downloads;
}
 
Example 12
Project: historian   File: HistorianTest.java   Source Code and License Vote up 5 votes
@Test
public void log_queue_over_logLevel() throws InterruptedException {
  historian.initialize();

  historian.log(Log.INFO, TAG, "this is info1");
  historian.log(Log.DEBUG, TAG, "this is debug1");
  historian.log(Log.INFO, TAG, "this is info2");
  historian.log(Log.WARN, TAG, "this is warn1");
  historian.log(Log.ERROR, TAG, "this is error1");

  Thread.sleep(500);

  Cursor cursor = getAllLogs(historian);

  assertEquals(4, cursor.getCount());

  cursor.moveToFirst();
  assertEquals("INFO", Cursors.getString(cursor, "priority"));
  assertEquals(TAG, Cursors.getString(cursor, "tag"));
  assertEquals("this is info1", Cursors.getString(cursor, "message"));

  cursor.moveToNext();
  assertEquals("INFO", Cursors.getString(cursor, "priority"));
  assertEquals(TAG, Cursors.getString(cursor, "tag"));
  assertEquals("this is info2", Cursors.getString(cursor, "message"));

  cursor.moveToNext();
  assertEquals("WARN", Cursors.getString(cursor, "priority"));
  assertEquals(TAG, Cursors.getString(cursor, "tag"));
  assertEquals("this is warn1", Cursors.getString(cursor, "message"));

  cursor.moveToNext();
  assertEquals("ERROR", Cursors.getString(cursor, "priority"));
  assertEquals(TAG, Cursors.getString(cursor, "tag"));
  assertEquals("this is error1", Cursors.getString(cursor, "message"));

  cursor.close();
}
 
Example 13
Project: KomaMusic   File: ArtistsPresenter.java   Source Code and License Vote up 5 votes
public static List<Artist> getAllArtists() {
    List<Artist> artistList = new ArrayList<>();
    Cursor cursor = makeArtistCursor(MusicApplication.getContext());
    // Gather the data
    if (cursor != null && cursor.moveToFirst()) {
        do {
            // Copy the artist id
            final long id = cursor.getLong(0);

            // Copy the artist name
            final String artistName = cursor.getString(1);

            // Copy the number of albums
            final int albumCount = cursor.getInt(2);

            // Copy the number of songs
            final int songCount = cursor.getInt(3);

            // as per designer's request, don't show unknown artist
            if (MediaStore.UNKNOWN_STRING.equals(artistName)) {
                continue;
            }

            // Create a new artist
            final Artist artist = new Artist(id, artistName, songCount, albumCount);
            artistList.add(artist);
        } while (cursor.moveToNext());
    }
    // Close the cursor
    if (cursor != null) {
        cursor.close();
        cursor = null;
    }
    return artistList;
}
 
Example 14
Project: editor-sql   File: ExportTool.java   Source Code and License Vote up 5 votes
private static void exportSingleIndex(SQLiteDatabase db, String tableName, BufferedWriter writer) throws IOException {
    String sql = "SELECT sql FROM sqlite_master WHERE type = 'index' AND tbl_name='" + tableName + "'";
    Cursor cursor = db.rawQuery(sql, null);
    if (cursor == null) return;

    while (cursor.moveToNext()) {
        if (cursor.getString(0) == null)
            continue;

        writer.write(cursor.getString(0) + ";" + NL + NL);
    }
    cursor.close();
}
 
Example 15
Project: RoadLab-Pro   File: RecordDetailsDAO.java   Source Code and License Vote up 5 votes
public List<RecordDetailsModel> getAllRecordDetails() {
    final List<RecordDetailsModel> listRecordDetails = new ArrayList<>();

    final Cursor cursor = getDatabase().query(DataBaseHelper.TABLE_RECORDS_DETAILS,
            allColumns, null, null, null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        RecordDetailsModel recordDetailsModel = cursorToRecordDetails(cursor);
        listRecordDetails.add(recordDetailsModel);
        cursor.moveToNext();
    }
    cursor.close();
    return listRecordDetails;
}
 
Example 16
Project: Android_watch_magpie   File: MeasuresRepository.java   Source Code and License Vote up 5 votes
/**
 * this methode will return the last measure stored in the database of each category, and then
 * sorted them alphabetically
 * @return lastMeasure
 */
public HashMap<String,Measure> getLastMeasure()
{
    String SQL_DISTINCT_ENAME = "SELECT max("+MeasureDao.Properties.TimeStamp.columnName+"),"
            +MeasureDao.Properties.Id.columnName+","
            +MeasureDao.Properties.Value1.columnName+","
            +MeasureDao.Properties.Value2.columnName+","
            +MeasureDao.Properties.Category.columnName
            +" FROM "+MeasureDao.TABLENAME
            +" GROUP BY  "+MeasureDao.Properties.Category.columnName
            +" ORDER BY "+MeasureDao.Properties.Category.columnName;


    HashMap<String,Measure> result = new HashMap<String, Measure>();
    Cursor c = Core.getInstance().getDaoSession().getDatabase().rawQuery(SQL_DISTINCT_ENAME, null);
    try{
        if (c.moveToFirst()) {
            do {
                Measure measure=new Measure();
                measure.setTimeStamp(c.getLong(0));
                measure.setId(c.getLong(1));
                measure.setValue1(c.getDouble(2));
                measure.setValue2(c.getDouble(3));
                measure.setCategory(c.getString(4));
                result.put(measure.getCategory(),measure);
            } while (c.moveToNext());
        }
    } finally {
        c.close();

        return result;
    }
}
 
Example 17
Project: TherapyGuide   File: DiaryServiceApiImpl.java   Source Code and License Vote up 4 votes
@Override
public void getDiaryEntry(long timestamp, DiaryServiceCallback<DiaryEntry> callback) {

    SQLiteDatabase db = mDbHelper.getReadableDatabase();

    // The columns that will be used
    String[] projection = {
            DiaryReaderContract.DiaryDbEntry.COLUMN_NAME_TIMESTAMP,
            DiaryReaderContract.DiaryDbEntry.COLUMN_NAME_TEXT,
            DiaryReaderContract.DiaryDbEntry.COLUMN_NAME_TEXT2,
            DiaryReaderContract.DiaryDbEntry.COLUMN_NAME_TEXT3,
            DiaryReaderContract.DiaryDbEntry.COLUMN_NAME_TEXT4,
            DiaryReaderContract.DiaryDbEntry.COLUMN_NAME_TEXT5
    };

    // The value to search for
    ContentValues values = new ContentValues();
    values.put(DiaryReaderContract.DiaryDbEntry.COLUMN_NAME_TIMESTAMP, String.valueOf(timestamp));

    // Sort results, newest first
    String sortOrder =
            DiaryReaderContract.DiaryDbEntry.COLUMN_NAME_TIMESTAMP + " DESC";

    Cursor cursor = db.query(
            DiaryReaderContract.DiaryDbEntry.TABLE_NAME,// The table to query
            projection,                                 // The columns to return
            DiaryReaderContract.DiaryDbEntry.COLUMN_NAME_TIMESTAMP + "='" + timestamp + "'", // The columns for the WHERE clause
            null,                                       // The values for the WHERE clause
            null,                                       // don't group the rows
            null,                                       // don't filter by row groups
            sortOrder                                   // The sort order
    );

    DiaryEntry loadedEntry = null;
    if( cursor.getCount() == 1) {
        cursor.moveToNext();
        String text1 = cursor.getString(
                cursor.getColumnIndexOrThrow(DiaryReaderContract.DiaryDbEntry.COLUMN_NAME_TEXT));
        String text2 = cursor.getString(
                cursor.getColumnIndexOrThrow(DiaryReaderContract.DiaryDbEntry.COLUMN_NAME_TEXT2));
        String text3 = cursor.getString(
                cursor.getColumnIndexOrThrow(DiaryReaderContract.DiaryDbEntry.COLUMN_NAME_TEXT3));
        String text4 = cursor.getString(
                cursor.getColumnIndexOrThrow(DiaryReaderContract.DiaryDbEntry.COLUMN_NAME_TEXT4));
        String text5 = cursor.getString(
                cursor.getColumnIndexOrThrow(DiaryReaderContract.DiaryDbEntry.COLUMN_NAME_TEXT5));
        loadedEntry = new DiaryEntry(timestamp, text1, text2, text3, text4, text5);
    }
    cursor.close();
    callback.onLoaded(loadedEntry);
}
 
Example 18
Project: android-dev-challenge   File: TestSunshineDatabase.java   Source Code and License Vote up 4 votes
/**
     * This method tests that our database contains all of the tables that we think it should
     * contain. Although in our case, we just have one table that we expect should be added
     * <p>
     * {@link com.example.android.sunshine.data.WeatherContract.WeatherEntry#TABLE_NAME}.
     * <p>
     * Despite only needing to check one table name in Sunshine, we set this method up so that
     * you can use it in other apps to test databases with more than one table.
     */
    @Test
    public void testCreateDb() {
        /*
         * Will contain the name of every table in our database. Even though in our case, we only
         * have only table, in many cases, there are multiple tables. Because of that, we are
         * showing you how to test that a database with multiple tables was created properly.
         */
        final HashSet<String> tableNameHashSet = new HashSet<>();

        /* Here, we add the name of our only table in this particular database */
        tableNameHashSet.add(REFLECTED_TABLE_NAME);
        /* Students, here is where you would add any other table names if you had them */
//        tableNameHashSet.add(MyAwesomeSuperCoolTableName);
//        tableNameHashSet.add(MyOtherCoolTableNameThatContainsOtherCoolData);

        /* We think the database is open, let's verify that here */
        String databaseIsNotOpen = "The database should be open and isn't";
        assertEquals(databaseIsNotOpen,
                true,
                database.isOpen());

        /* This Cursor will contain the names of each table in our database */
        Cursor tableNameCursor = database.rawQuery(
                "SELECT name FROM sqlite_master WHERE type='table'",
                null);

        /*
         * If tableNameCursor.moveToFirst returns false from this query, it means the database
         * wasn't created properly. In actuality, it means that your database contains no tables.
         */
        String errorInCreatingDatabase =
                "Error: This means that the database has not been created correctly";
        assertTrue(errorInCreatingDatabase,
                tableNameCursor.moveToFirst());

        /*
         * tableNameCursor contains the name of each table in this database. Here, we loop over
         * each table that was ACTUALLY created in the database and remove it from the
         * tableNameHashSet to keep track of the fact that was added. At the end of this loop, we
         * should have removed every table name that we thought we should have in our database.
         * If the tableNameHashSet isn't empty after this loop, there was a table that wasn't
         * created properly.
         */
        do {
            tableNameHashSet.remove(tableNameCursor.getString(0));
        } while (tableNameCursor.moveToNext());

        /* If this fails, it means that your database doesn't contain the expected table(s) */
        assertTrue("Error: Your database was created without the expected tables.",
                tableNameHashSet.isEmpty());

        /* Always close the cursor when you are finished with it */
        tableNameCursor.close();
    }
 
Example 19
Project: AndiCar   File: Utils.java   Source Code and License Vote up 4 votes
public static void setToDoNextRun(Context ctx) {
    try {
        String LogTag = "AndiCar";
        Log.d(LogTag, "========== ToDo setNextRun begin ==========");
        //@formatter:off
        String sql =
            " SELECT * " +
            " FROM " + DBAdapter.TABLE_NAME_TODO +
            " WHERE " +
                    DB.sqlConcatTableColumn(DBAdapter.TABLE_NAME_TODO, DBAdapter.COL_NAME_GEN_ISACTIVE) + "='Y' " + " AND " +
                    DB.sqlConcatTableColumn(DBAdapter.TABLE_NAME_TODO, DBAdapter.COL_NAME_TODO__ISDONE) + "='N' " + " AND " +
                    DB.sqlConcatTableColumn(DBAdapter.TABLE_NAME_TODO, DBAdapter.COL_NAME_TODO__NOTIFICATIONDATE) + " IS NOT NULL " +
            " ORDER BY " +
                    DB.sqlConcatTableColumn(DBAdapter.TABLE_NAME_TODO, DBAdapter.COL_NAME_TODO__NOTIFICATIONDATE) + " ASC ";
        //@formatter:on
        long currentSec = System.currentTimeMillis() / 1000;
        DBAdapter db = new DBAdapter(ctx);
        Cursor c = db.execSelectSql(sql, null);
        FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(ctx));
        Job fbJob;
        Bundle jobParams = new Bundle();
        long notificationDateInSeconds;

        while (c.moveToNext()) {
            notificationDateInSeconds = c.getLong(DBAdapter.COL_POS_TODO__NOTIFICATIONDATE);
            jobParams.putLong(ToDoNotificationJob.TODO_ID_KEY, c.getLong(DBAdapter.COL_POS_GEN_ROWID));
            jobParams.putLong(ToDoNotificationJob.CAR_ID_KEY, c.getLong(DBAdapter.COL_POS_TODO__CAR_ID));
            Log.d(LogTag,
                    "Current date: " + DateFormat.getDateFormat(ctx).format(currentSec * 1000) + " " + DateFormat.getTimeFormat(ctx).format(currentSec * 1000) +
                            " (currentSec: " + currentSec + "); " +
                            "Next run for to-do " + c.getString(DBAdapter.COL_POS_GEN_NAME) + " (" + c.getString(DBAdapter.COL_POS_GEN_ROWID) + "): " +
                            DateFormat.getDateFormat(ctx).format(notificationDateInSeconds * 1000) + " " + DateFormat.getTimeFormat(ctx).format(notificationDateInSeconds * 1000) +
                            " (notificationDateInSeconds: " + notificationDateInSeconds + "); " +
                            "Seconds left: " + (notificationDateInSeconds - currentSec));
            fbJob = dispatcher.newJobBuilder()
                    // the JobService that will be called
                    .setService(ToDoNotificationJob.class)
                    // uniquely identifies the job
                    .setTag(ToDoNotificationJob.TAG + c.getString(DBAdapter.COL_POS_GEN_ROWID))
                    // one-off job
                    .setRecurring(false)
                    .setLifetime(Lifetime.FOREVER)
                    // start between 0 and 30 seconds from now
                    .setTrigger(notificationDateInSeconds - currentSec <= 0 ? Trigger.NOW :
                            Trigger.executionWindow((int) (notificationDateInSeconds - currentSec), (int) (notificationDateInSeconds - currentSec) + 30))
                    // overwrite an existing job with the same tag
                    .setReplaceCurrent(true)
                    // retry with exponential backoff
                    .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
                    .setExtras(jobParams)
                    .build();
            dispatcher.mustSchedule(fbJob);
        }
        c.close();
        db.close();
        Log.d(LogTag, "========== setNextRun finished ==========");
    }
    catch (Exception e) {
        AndiCarCrashReporter.sendCrash(e);
    }
}
 
Example 20
Project: AndiCar   File: Utils.java   Source Code and License Vote up 4 votes
public static void initSpinner(DBAdapter dbAdapter, View pSpinner,
                               String tableName, String selection, long selectedId, boolean addEmptyValue) {
    try {
        Spinner spnCurrentSpinner = (Spinner) pSpinner;
        spnCurrentSpinner.setTag(ConstantValues.IS_INITIALIZATION_IN_PROGRESS_TAG);

        Cursor dbcRecordCursor;
        //@formatter:off
        if (addEmptyValue) {
            String selectSql =
                    "SELECT " +
                            "-1 AS " + DBAdapter.COL_NAME_GEN_ROWID + ", " +
                            "' ' AS " + DBAdapter.COL_NAME_GEN_NAME +
                    " UNION " +
                    " SELECT " +
                            DBAdapter.COL_NAME_GEN_ROWID +
                            ", " + DBAdapter.COL_NAME_GEN_NAME +
                    " FROM " + tableName +
                    " WHERE 1 = 1 ";
            if (selection != null && selection.length() > 0) {
                selectSql = selectSql + selection;
            }
            selectSql = selectSql + " ORDER BY " + DBAdapter.COL_NAME_GEN_NAME;

            dbcRecordCursor = dbAdapter.execSelectSql(selectSql, null);
        }
        else {
            dbcRecordCursor = dbAdapter.query(tableName, DBAdapter.COL_LIST_GEN_ROWID_NAME, "1 = 1 " + selection, null, DBAdapter.COL_NAME_GEN_NAME);
        }
        //@formatter:on

        if (dbcRecordCursor == null)
            return;

        List<String> recordsList = new ArrayList<>();
        while (dbcRecordCursor.moveToNext()) {
            recordsList.add(dbcRecordCursor.getString(1));
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<>(pSpinner.getContext(), R.layout.ui_element_spinner_item, recordsList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spnCurrentSpinner.setAdapter(adapter);

        if (selectedId >= 0) {
            //set the spinner to this id
            dbcRecordCursor.moveToFirst();
            for (int i = 0; i < dbcRecordCursor.getCount(); i++) {
                if (dbcRecordCursor.getLong(DBAdapter.COL_POS_GEN_ROWID) == selectedId) {
                    spnCurrentSpinner.setSelection(i);
                    break;
                }
                dbcRecordCursor.moveToNext();
            }
        }
        dbcRecordCursor.close();
    }
    catch (Exception e) {
        Utils.showReportableErrorDialog(pSpinner.getContext(), AndiCar.getAppResources().getString(R.string.error_sorry), e.getMessage(), e);
    }
}