Java Code Examples for android.database.Cursor#moveToPrevious()

The following examples show how to use android.database.Cursor#moveToPrevious() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LocationService.java    From Androzic with GNU General Public License v3.0 6 votes vote down vote up
public Track getTrack(long limit)
{
	if (trackDB == null)
		openDatabase();
	Track track = new Track();
	if (trackDB == null)
		return track;
	String limitStr = limit > 0 ? " LIMIT " + limit : "";
	Cursor cursor = trackDB.rawQuery("SELECT * FROM track ORDER BY _id DESC" + limitStr, null);
	for (boolean hasItem = cursor.moveToLast(); hasItem; hasItem = cursor.moveToPrevious())
	{
		double latitude = cursor.getDouble(cursor.getColumnIndex("latitude"));
		double longitude = cursor.getDouble(cursor.getColumnIndex("longitude"));
		double elevation = cursor.getDouble(cursor.getColumnIndex("elevation"));
		double speed = cursor.getDouble(cursor.getColumnIndex("speed"));
		double bearing = cursor.getDouble(cursor.getColumnIndex("track"));
		double accuracy = cursor.getDouble(cursor.getColumnIndex("accuracy"));
		int code = cursor.getInt(cursor.getColumnIndex("code"));
		long time = cursor.getLong(cursor.getColumnIndex("datetime"));
		track.addPoint(code == 0, latitude, longitude, elevation, speed, bearing, accuracy, time);
	}
	cursor.close();
	return track;
}
 
Example 2
Source File: LocationService.java    From trekarta with GNU General Public License v3.0 6 votes vote down vote up
public Track getTrack(long start, long end) {
    if (mTrackDB == null)
        openDatabase();
    Track track = new Track();
    if (mTrackDB == null)
        return track;
    Cursor cursor = mTrackDB.rawQuery("SELECT * FROM track WHERE datetime >= ? AND datetime <= ? ORDER BY _id DESC", new String[]{String.valueOf(start), String.valueOf(end)});
    for (boolean hasItem = cursor.moveToLast(); hasItem; hasItem = cursor.moveToPrevious()) {
        int latitudeE6 = cursor.getInt(cursor.getColumnIndex("latitude"));
        int longitudeE6 = cursor.getInt(cursor.getColumnIndex("longitude"));
        float elevation = cursor.getFloat(cursor.getColumnIndex("elevation"));
        float speed = cursor.getFloat(cursor.getColumnIndex("speed"));
        float bearing = cursor.getFloat(cursor.getColumnIndex("track"));
        float accuracy = cursor.getFloat(cursor.getColumnIndex("accuracy"));
        int code = cursor.getInt(cursor.getColumnIndex("code"));
        long time = cursor.getLong(cursor.getColumnIndex("datetime"));
        track.addPoint(code == 0, latitudeE6, longitudeE6, elevation, speed, bearing, accuracy, time);
    }
    cursor.close();
    return track;
}
 
Example 3
Source File: DataItemRecord.java    From android_packages_apps_GmsCore with Apache License 2.0 6 votes vote down vote up
public static DataItemRecord fromCursor(Cursor cursor) {
    DataItemRecord record = new DataItemRecord();
    record.packageName = cursor.getString(1);
    record.signatureDigest = cursor.getString(2);
    record.dataItem = new DataItemInternal(cursor.getString(3), cursor.getString(4));
    record.seqId = cursor.getLong(5);
    record.deleted = cursor.getLong(6) > 0;
    record.source = cursor.getString(7);
    record.dataItem.data = cursor.getBlob(8);
    record.lastModified = cursor.getLong(9);
    record.assetsAreReady = cursor.getLong(10) > 0;
    if (cursor.getString(11) != null) {
        record.dataItem.addAsset(cursor.getString(11), Asset.createFromRef(cursor.getString(12)));
        while (cursor.moveToNext()) {
            if (cursor.getLong(5) == record.seqId) {
                record.dataItem.addAsset(cursor.getString(11), Asset.createFromRef(cursor.getString(12)));
            }
        }
        cursor.moveToPrevious();
    }
    return record;
}
 
Example 4
Source File: FavoriteDatabase.java    From PkRSS with Apache License 2.0 6 votes vote down vote up
/**
 * @return A backwards Article ArrayList ordered from last added to end.
 */
public List<Article> getAll() {
	// Init List & Build Query
	List<Article> articleList = new ArrayList<Article>();
	String selectQuery = "SELECT  * FROM " + TABLE_ARTICLES;

	// Get Write Access & Execute Query
	SQLiteDatabase db = this.getWritableDatabase();
	Cursor cursor = db.rawQuery(selectQuery, null);

	// Read the query backwards
	if (cursor.moveToLast()) {
		do {
			articleList.add(new Article(null, Arrays.asList(cursor.getString(0).split("_PCX_")), Article.MediaContent.fromByteArray(cursor.getBlob(1)), Uri.parse(cursor.getString(2)),
			                            Uri.parse(cursor.getString(3)), cursor.getString(4), cursor.getString(5), cursor.getString(6),
			                            cursor.getString(7), cursor.getString(8), cursor.getLong(9), cursor.getInt(10)));
		} while (cursor.moveToPrevious());
	}
	cursor.close();
	db.close();

	return articleList;
}
 
Example 5
Source File: TasksManagerDemoActivity.java    From FileDownloader with Apache License 2.0 6 votes vote down vote up
public List<TasksManagerModel> getAllTasks() {
    final Cursor c = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);

    final List<TasksManagerModel> list = new ArrayList<>();
    try {
        if (!c.moveToLast()) {
            return list;
        }

        do {
            TasksManagerModel model = new TasksManagerModel();
            model.setId(c.getInt(c.getColumnIndex(TasksManagerModel.ID)));
            model.setName(c.getString(c.getColumnIndex(TasksManagerModel.NAME)));
            model.setUrl(c.getString(c.getColumnIndex(TasksManagerModel.URL)));
            model.setPath(c.getString(c.getColumnIndex(TasksManagerModel.PATH)));
            list.add(model);
        } while (c.moveToPrevious());
    } finally {
        if (c != null) {
            c.close();
        }
    }

    return list;
}
 
Example 6
Source File: LocationService.java    From trekarta with GNU General Public License v3.0 6 votes vote down vote up
public Track getTrack(long limit) {
    if (mTrackDB == null)
        openDatabase();
    Track track = new Track(getString(R.string.currentTrack), true);
    if (mTrackDB == null)
        return track;
    String limitStr = limit > 0 ? " LIMIT " + limit : "";
    Cursor cursor = mTrackDB.rawQuery("SELECT * FROM track ORDER BY _id DESC" + limitStr, null);
    for (boolean hasItem = cursor.moveToLast(); hasItem; hasItem = cursor.moveToPrevious()) {
        int latitudeE6 = cursor.getInt(cursor.getColumnIndex("latitude"));
        int longitudeE6 = cursor.getInt(cursor.getColumnIndex("longitude"));
        float elevation = cursor.getFloat(cursor.getColumnIndex("elevation"));
        float speed = cursor.getFloat(cursor.getColumnIndex("speed"));
        float bearing = cursor.getFloat(cursor.getColumnIndex("track"));
        float accuracy = cursor.getFloat(cursor.getColumnIndex("accuracy"));
        int code = cursor.getInt(cursor.getColumnIndex("code"));
        long time = cursor.getLong(cursor.getColumnIndex("datetime"));
        track.addPoint(code == 0, latitudeE6, longitudeE6, elevation, speed, bearing, accuracy, time);
    }
    cursor.close();
    return track;
}
 
Example 7
Source File: ReelNoteActivity.java    From nono-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Cursor doInBackground(List<NoteReelItemArray>... params) {
	params[0].clear();
	NoteDBAdapter noteDBAdapter=new NoteDBAdapter(ReelNoteActivity.this);
	noteDBAdapter.open();
	Cursor cursor =noteDBAdapter.getTitleByReel(getIntent().getStringExtra("GroupName"));
	if(cursor.getCount()>0&&cursor.moveToLast()){
		do{
			params[0].add(new NoteReelItemArray(cursor.getString(cursor.getColumnIndex(NoteDBAdapter.KEY_TITLE))
					,cursor.getString(cursor.getColumnIndex(NoteDBAdapter.KEY_DATE)),cursor.getString(cursor.getColumnIndex(NoteDBAdapter.KEY_TIME))
					,cursor.getString(cursor.getColumnIndex(NoteDBAdapter.KEY_CONTENT))
					,cursor.getInt(cursor.getColumnIndex(NoteDBAdapter.KEY_ROWID))
			,cursor.getString(cursor.getColumnIndex(NoteDBAdapter.KEY_IS_ON_CLOUD)),
					cursor.getString(cursor.getColumnIndex(NoteDBAdapter.KEY_UUID)
					)));
		}while (cursor.moveToPrevious());
	}
	noteDBAdapter.close();
	return cursor;
}
 
Example 8
Source File: AlbumController.java    From umeng_community_android with MIT License 6 votes vote down vote up
/**
 * 获取最近使用的照片
 * 
 * @return
 */
public List<PhotoModel> getCurrent() {
    Cursor cursor = resolver.query(Media.EXTERNAL_CONTENT_URI, new String[] {
            ImageColumns.DATA,
            ImageColumns.DATE_ADDED, ImageColumns.SIZE
    }, null, null, ImageColumns.DATE_ADDED);
    if (cursor == null || !cursor.moveToNext())
        return new ArrayList<PhotoModel>();
    List<PhotoModel> photos = new ArrayList<PhotoModel>();
    cursor.moveToLast();
    do {
        if (cursor.getLong(cursor.getColumnIndex(ImageColumns.SIZE)) > 1024 * 10) {
            PhotoModel photoModel = new PhotoModel();
            photoModel.setOriginalPath(cursor.getString(cursor
                    .getColumnIndex(ImageColumns.DATA)));
            photos.add(photoModel);
        }
    } while (cursor.moveToPrevious());
    IOUtils.closeQuietly(cursor);
    return photos;
}
 
Example 9
Source File: PebbleKit.java    From pebble-android-sdk with MIT License 6 votes vote down vote up
/**
 * Query the Pebble ContentProvider - utility method for various PebbleKit helper methods
 *
 * This attempts first to query the Basalt app provider, then if that is non-existant or disconnected
 * queries the primary (i.e. original) provider authority
 */
private static Cursor queryProvider(final Context context) {
    Cursor c = context.getContentResolver().query(Constants.URI_CONTENT_BASALT, null, null, null, null);
    if (c != null) {
        if (c.moveToFirst()) {
            // If Basalt app is connected, talk to that (return the open cursor)
            if (c.getInt(KIT_STATE_COLUMN_CONNECTED) == 1) {
            	c.moveToPrevious();
                return c;
            }
        }
        // Else close the cursor and try the primary authority
        c.close();
    }

    c = context.getContentResolver().query(Constants.URI_CONTENT_PRIMARY, null, null, null, null);
    // Do nothing with this cursor - the calling method will check it for whatever it is looking for
    return c;
}
 
Example 10
Source File: OCursorListAdapter.java    From framework with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void notifyDataSetChanged() {
    super.notifyDataSetChanged();
    if (hasIndexers && mIndexerColumn != null) {
        Cursor cr = getCursor();
        if (cr.getCount() > 0) {
            int pos = cr.getCount() - 1;
            if (cr.moveToLast()) {
                List<String> keys = new ArrayList<>();
                do {
                    int index = cr.getColumnIndex(mIndexerColumn);
                    if (index > -1) {
                        String colValue = cr.getString(index);
                        azIndexers.put(colValue.substring(0, 1), pos);
                        keys.add(colValue.substring(0, 1));
                    }
                    pos--;
                } while (cr.moveToPrevious());
                Collections.sort(keys);
                sections = keys.toArray(new String[keys.size()]);
            }
        }
    }
}
 
Example 11
Source File: TasksManagerDBController.java    From YCAudioPlayer with Apache License 2.0 6 votes vote down vote up
List<TasksManagerModel> getAllTasks() {
    final Cursor c = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
    final List<TasksManagerModel> list = new ArrayList<>();
    try {
        if (!c.moveToLast()) {
            return list;
        }
        do {
            TasksManagerModel model = new TasksManagerModel();
            model.setId(c.getInt(c.getColumnIndex(TasksManagerModel.ID)));
            model.setName(c.getString(c.getColumnIndex(TasksManagerModel.NAME)));
            model.setUrl(c.getString(c.getColumnIndex(TasksManagerModel.URL)));
            model.setPath(c.getString(c.getColumnIndex(TasksManagerModel.PATH)));
            list.add(model);
        } while (c.moveToPrevious());
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return list;
}
 
Example 12
Source File: FavAdapter.java    From CSipSimple with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onClick(View view) {
    ContactInfo ci = (ContactInfo) view.getTag();
    List<String> phones = ContactsWrapper.getInstance().getCSipPhonesContact(mContext, ci.contactId);
    boolean useCSip = true;
    String toCall = null;
    if(phones != null && phones.size() > 0) {
        toCall = phones.get(0);
    }else {
        List<Phone> cPhones = ContactsWrapper.getInstance().getPhoneNumbers(mContext, ci.contactId, ContactsWrapper.URI_ALLS);
        if(cPhones != null && cPhones.size() > 0) {
            toCall = cPhones.get(0).getNumber();
            useCSip = false;
        }
    }
    
    if(!TextUtils.isEmpty(toCall) ) {
        Cursor c = (Cursor) getItem((Integer) ci.userData);
        Long profileId = null;
        while(c.moveToPrevious()) {
            int cTypeIdx = c.getColumnIndex(ContactsWrapper.FIELD_TYPE);
            int cAccIdx = c.getColumnIndex(BaseColumns._ID);
            if(cTypeIdx >= 0 && cAccIdx >= 0) {
                if(c.getInt(cTypeIdx) == ContactsWrapper.TYPE_GROUP) {
                    profileId = c.getLong(cAccIdx);
                    break;
                }
            }
        }
        
        Intent it = new Intent(Intent.ACTION_CALL);
        it.setData(SipUri.forgeSipUri(useCSip ? SipManager.PROTOCOL_CSIP : SipManager.PROTOCOL_SIP, toCall));
        it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if(profileId != null) {
            it.putExtra(SipProfile.FIELD_ACC_ID, profileId);
        }
        mContext.startActivity(it);
    }
}
 
Example 13
Source File: NoteReelsDBHelper.java    From nono-android with GNU General Public License v3.0 5 votes vote down vote up
public List<String> getReels() {
    List<String> list= new ArrayList<>();
    synchronized (adapter){
        adapter.open();
        Cursor cur = adapter.getReels();
        if(cur!=null && cur.moveToLast()){
            do{
                list.add(cur.getString(cur.getColumnIndex(NoteReelsDBAdapter.KEY_REAL)));
            }while(cur.moveToPrevious());
        }
        adapter.close();
    }
    return list;
}
 
Example 14
Source File: NoteLabelDBHelper.java    From nono-android with GNU General Public License v3.0 5 votes vote down vote up
public List<NoteAllArray>  getNoteArrayByTag(String tag){
    List<Long >  noteIdList = new ArrayList<>();
    List<NoteAllArray> noteAllArrayList = new ArrayList<>();
    synchronized (dbAdapter){
        dbAdapter.open();
        Cursor cr = dbAdapter.getAll();
        if (cr != null && cr.moveToLast() && cr.getCount() > 0) {
            int group_json_index = cr.getColumnIndex(NoteLabelListDBAdapter.KEY_GROUPJSON);
            int note_id_index = cr.getColumnIndex(NoteLabelListDBAdapter.KEY_NOTEID);
            do{
                String groupJson = cr.getString(group_json_index);
                if(groupJson.contains(tag)){
                    noteIdList.add(cr.getLong(note_id_index));
                }
            }while (cr.moveToPrevious());
        }
        dbAdapter.close();
    }
    for (long noteId:
            noteIdList) {
        noteAllArrayList.add(

                NoteDBHelper.getInstance().getNoteById(noteId)
        );
    }
    return noteAllArrayList;
}
 
Example 15
Source File: GalleryTask.java    From PictureChooseLib with Apache License 2.0 5 votes vote down vote up
private static List<GalleryListModel> getGalleryListPath(ContentResolver mContentResolver) {
    Uri EXTERNAL_CONTENT_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    String MIME_TYPE = MediaStore.Images.Media.MIME_TYPE;
    String DATA = MediaStore.Images.Media.DATA;
    Cursor cursor = mContentResolver.query(EXTERNAL_CONTENT_URI, new String[]{DATA},
            MIME_TYPE + "=? or " + MIME_TYPE + "=? or " + MIME_TYPE + "=?",
            new String[]{"image/jpg", "image/jpeg", "image/png"},
            MediaStore.Images.Media.DATE_MODIFIED);
    if(cursor == null){
        return null;
    }
    ArrayList<GalleryListModel> list = new ArrayList<>();
    HashSet<String> cachePath = new HashSet<String>();
    if (cursor.moveToLast()) {
        while (true) {
            String picturePath = cursor.getString(0);
            File parentFile = new File(picturePath).getParentFile();
            String parentPath = parentFile.getAbsolutePath();
            if (Utils.isPicture(picturePath) && !cachePath.contains(parentPath)) {
                String picture = getFrontPicture(parentFile);
                if(!TextUtils.isEmpty(picture)){
                    list.add(new GalleryListModel(parentPath, getPictureCount(parentFile),picture));
                    cachePath.add(parentPath);
                }
            }
            if (!cursor.moveToPrevious()) {
                break;
            }
        }
    }
    cachePath.clear();
    Utils.closeQuietly(cursor);
    return list;
}
 
Example 16
Source File: AlbumController.java    From umeng_community_android with MIT License 5 votes vote down vote up
/**
 * 获取所有相册
 * 
 * @return
 */
public List<AlbumModel> getAlbums() {
    List<AlbumModel> albums = new ArrayList<AlbumModel>();
    Map<String, AlbumModel> map = new HashMap<String, AlbumModel>();
    Cursor cursor = resolver.query(Media.EXTERNAL_CONTENT_URI, new String[] {
            ImageColumns.DATA,
            ImageColumns.BUCKET_DISPLAY_NAME, ImageColumns.SIZE
    }, null, null, null);
    if (cursor == null || !cursor.moveToNext())
        return new ArrayList<AlbumModel>();
    cursor.moveToLast();
    AlbumModel current = new AlbumModel(ResFinder.getString("umeng_comm_recent_photos"), 0,
            cursor.getString(cursor.getColumnIndex(ImageColumns.DATA)), true); // 最近的照片
    albums.add(current);
    do {
        if (cursor.getInt(cursor.getColumnIndex(ImageColumns.SIZE)) < 1024 * 10) {
            continue;
        }

        current.increaseCount();
        String name = cursor.getString(cursor.getColumnIndex(ImageColumns.BUCKET_DISPLAY_NAME));
        if (map.keySet().contains(name))
            map.get(name).increaseCount();
        else {
            AlbumModel album = new AlbumModel(name, 1, cursor.getString(cursor
                    .getColumnIndex(ImageColumns.DATA)));
            map.put(name, album);
            albums.add(album);
        }
    } while (cursor.moveToPrevious());
    IOUtils.closeQuietly(cursor);
    return albums;
}
 
Example 17
Source File: LogAdapter.java    From budget-envelopes with GNU General Public License v3.0 4 votes vote down vote up
private void fillCardContents(Context cntx, CardContents contents, Cursor csr) {
    long time = csr.getLong(csr.getColumnIndexOrThrow("time"));
    int color = cntx.getResources().getColor(
        time > System.currentTimeMillis()
        ? android.R.color.holo_blue_dark
        : android.R.color.black
    );
    contents.name.setText(csr.getString(
        csr.getColumnIndexOrThrow("description")
    ));
    contents.name.setTextColor(color);
    long cents = csr.getLong(csr.getColumnIndexOrThrow("cents"));
    StringBuilder money = contents.money;
    money.delete(0, money.length());
    if (cents > 0) {
        money.append("+");
    }
    contents.value.setText(
        EditMoney.toMoneyBuilder(cents, money).toString()
    );
    contents.value.setTextColor(color);
    Date timeD = new Date(time);
    String formattedDate = mDate.format(timeD);
    contents.time.setText(formattedDate);
    contents.time.setTextColor(color);
    if (csr.getColumnIndex("envelope") != -1) {
        String previousEnvelope;
        if (csr.getPosition() != 0) {
            csr.moveToPrevious();
            previousEnvelope = csr.getString(csr.getColumnIndexOrThrow("envelope"));
            csr.moveToNext();
        } else {
            previousEnvelope = "";
        }
        String currentEnvelope = csr.getString(csr.getColumnIndexOrThrow("envelope"));
        if (currentEnvelope.equals(previousEnvelope)) {
            contents.envelope.setVisibility(View.GONE);
        } else {
            contents.envelope.setVisibility(View.VISIBLE);
            contents.envelope.setText(currentEnvelope);
            contents.envelope.setBackgroundColor(csr.getInt(csr.getColumnIndexOrThrow("color")));
        }
    }
}
 
Example 18
Source File: DbMigration.java    From LibreTasks with Apache License 2.0 4 votes vote down vote up
/**
 * Modify the actions by replacing the username and password attributes into user account (this is
 * done for possible multi-account support and supporting different authentication methods like
 * OAuth). Also retrieves username and password from existing rules and the latest entry is used
 * if there are multiple actions that has username and password.
 * 
 * @param db
 *          the database instance to work with
 * @param appName
 *          the name of the application associated with the action
 * @param actionName
 *          the name of the action
 * @param usernameParamName
 *          the action's parameter name for username
 * @param passwordParamName
 *          the action's parameter name for password
 * @param userAccountParamName
 *          the action's parameter name for user account
 * @param dataTypeIdAccount
 *          primary key id for UserAccount datatype
 */
private static void modifyActionToSupportUserAccount(SQLiteDatabase db, String appName,
    String actionName, String usernameParamName, String passwordParamName,
    String userAccountParamName, long dataTypeIdAccount) {
  // Get the App ID
  RegisteredAppDbAdapter appDbAdapter = new RegisteredAppDbAdapter(db);
  Cursor cursor = appDbAdapter.fetchAll(appName, "", true);
  cursor.moveToFirst();
  long appID = CursorHelper.getLongFromCursor(cursor, RegisteredAppDbAdapter.KEY_APPID);
  cursor.close();

  // Get the Action ID
  RegisteredActionDbAdapter actionDbAdapter = new RegisteredActionDbAdapter(db);
  cursor = actionDbAdapter.fetchAll(actionName, appID);
  cursor.moveToFirst();
  long actionId = CursorHelper.getLongFromCursor(cursor, RegisteredActionDbAdapter.KEY_ACTIONID);
  cursor.close();

  RegisteredActionParameterDbAdapter actionParameterDbAdapter = new 
      RegisteredActionParameterDbAdapter(db);

  /*
   * Modify the username parameter to user account. Update was used instead of delete then insert
   * to have the user account parameter appear on the top position when {@code
   * FactoryActions.buildUIFromAction} is called.
   */
  cursor = actionParameterDbAdapter.fetchAll(usernameParamName, actionId, null);
  cursor.moveToFirst();
  long paramID = CursorHelper.getLongFromCursor(cursor,
      RegisteredActionParameterDbAdapter.KEY_ACTIONPARAMETERID);

  actionParameterDbAdapter.update(paramID, userAccountParamName, null, dataTypeIdAccount);
  cursor.close();

  /*
   * Get the username from existing rules and set it to the application. Use the last entry if
   * there are multiple actions in the database.
   */
  RuleActionParameterDbAdapter ruleActionParamDb = new RuleActionParameterDbAdapter(db);
  cursor = ruleActionParamDb.fetchAll(null, paramID, null);
  if (cursor.moveToLast()) {
    String username = CursorHelper.getStringFromCursor(cursor,
        RuleActionParameterDbAdapter.KEY_RULEACTIONPARAMETERDATA);

    appDbAdapter.update(appID, null, null, null, null, username, null);
  }
  // No need to delete since paramID is now user account
  cursor.close();

  // Remove the password parameter
  cursor = actionParameterDbAdapter.fetchAll(passwordParamName, actionId, null);
  cursor.moveToFirst();
  paramID = CursorHelper.getLongFromCursor(cursor,
      RegisteredActionParameterDbAdapter.KEY_ACTIONPARAMETERID);
  actionParameterDbAdapter.delete(paramID);
  cursor.close();

  /*
   * Get the password from existing rules and set it to the application. Use the last entry if
   * there are multiple gmail send actions in the database. And remove all rule action password
   * parameter entries.
   */
  cursor = ruleActionParamDb.fetchAll(null, paramID, null);
  if (cursor.moveToLast()) {
    String password = CursorHelper.getStringFromCursor(cursor,
        RuleActionParameterDbAdapter.KEY_RULEACTIONPARAMETERDATA);

    appDbAdapter.update(appID, null, null, null, null, null, password);

    do {
      ruleActionParamDb.delete(CursorHelper.getLongFromCursor(cursor,
          RuleActionParameterDbAdapter.KEY_RULEACTIONPARAMETERID));
    } while (cursor.moveToPrevious());
  }
  cursor.close();
}
 
Example 19
Source File: ContentProviderTest.java    From droitatedDB with Apache License 2.0 4 votes vote down vote up
@Test
public void cursorTest() {
    // create some data
    Single c1 = new Single("c1");
    Single c2 = new Single("c2");
    Single c3 = new Single("c3");
    ArrayList<Single> objects = newArrayList(c1, c2, c3);


    EntityService<Single> service = entityService(Single.class);
    service.save(objects);
    Cursor cursor = getSingleCursor();
    ObjectCursor<Single> objectCursor = CursorUtil.getObjectCursor(cursor);

    assertThat(objectCursor.size()).isEqualTo(3);
    assertThat(cursor.isBeforeFirst()).isTrue();
    assertThat(objectCursor.getCurrent()).isNotNull();
    assertThat(cursor.isFirst()).isTrue();
    assertThat(objectCursor.getLast()).isNotNull();
    assertThat(cursor.isLast()).isTrue();
    assertThat(objectCursor.getFirst()).isNotNull();
    assertThat(cursor.isFirst()).isTrue();

    assertThat(objectCursor.size()).isEqualTo(3);
    Collection<Single> all = newArrayList(objectCursor.getAll());
    assertThat(all).contains(c1, c2, c3);

    int i = 0;
    for (Single s : objectCursor) {
        assertThat(s).isIn(objects);
        i++;
    }
    assertThat(i).isEqualTo(3);

    cursor.moveToFirst();
    cursor.moveToPrevious();

    assertThat(objectCursor.hasNext()).isTrue();
    assertThat(objectCursor.hasPrevious()).isFalse();
    Single current = objectCursor.getCurrent();
    assertThat(current).isIn(objects);
    assertThat(objectCursor.getCurrent()).isEqualTo(current);
    assertThat(objectCursor.getNext()).isIn(objects);
    assertThat(objectCursor.hasNext()).isTrue();
    assertThat(objectCursor.hasPrevious()).isTrue();
    assertThat(objectCursor.getNext()).isIn(objects);
    assertThat(objectCursor.hasNext()).isFalse();
    assertThat(objectCursor.hasPrevious()).isTrue();
    assertThat(objectCursor.getPrevious()).isIn(objects);
    assertThat(objectCursor.hasNext()).isTrue();
    assertThat(objectCursor.hasPrevious()).isTrue();
    Collection<Single> previous5 = objectCursor.getPrevious(5);
    assertThat(previous5).contains(current);
    assertThat(previous5.size()).isEqualTo(1);
    Collection<Single> next5 = objectCursor.getNext(5);
    assertThat(next5).contains(c1, c2, c3);
    assertThat(next5.size()).isEqualTo(3);

}
 
Example 20
Source File: MessageSearchTask.java    From Pix-Art-Messenger with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void run() {
    long startTimestamp = SystemClock.elapsedRealtime();
    Cursor cursor = null;
    try {
        final HashMap<String, Conversational> conversationCache = new HashMap<>();
        final List<Message> result = new ArrayList<>();
        cursor = xmppConnectionService.databaseBackend.getMessageSearchCursor(term);
        long dbTimer = SystemClock.elapsedRealtime();
        if (isCancelled) {
            Log.d(Config.LOGTAG, "canceled search task");
            return;
        }
        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToLast();
            final int indexBody = cursor.getColumnIndex(Message.BODY);
            final int indexOob = cursor.getColumnIndex(Message.OOB);
            final int indexConversation = cursor.getColumnIndex(Message.CONVERSATION);
            final int indexAccount = cursor.getColumnIndex(Conversation.ACCOUNT);
            final int indexContact = cursor.getColumnIndex(Conversation.CONTACTJID);
            final int indexMode = cursor.getColumnIndex(Conversation.MODE);
            do {
                if (isCancelled) {
                    Log.d(Config.LOGTAG, "canceled search task");
                    return;
                }
                final String body = cursor.getString(indexBody);
                final boolean oob = cursor.getInt(indexOob) > 0;
                if (MessageUtils.treatAsDownloadable(body, oob)) {
                    continue;
                }
                final String conversationUuid = cursor.getString(indexConversation);
                Conversational conversation = conversationCache.get(conversationUuid);
                if (conversation == null) {
                    String accountUuid = cursor.getString(indexAccount);
                    String contactJid = cursor.getString(indexContact);
                    int mode = cursor.getInt(indexMode);
                    conversation = findOrGenerateStub(conversationUuid, accountUuid, contactJid, mode);
                    conversationCache.put(conversationUuid, conversation);
                }
                Message message = IndividualMessage.fromCursor(cursor, conversation);
                result.add(message);
            } while (cursor.moveToPrevious());
        }
        long stopTimestamp = SystemClock.elapsedRealtime();
        Log.d(Config.LOGTAG, "found " + result.size() + " messages in " + (stopTimestamp - startTimestamp) + "ms" + " (db was " + (dbTimer - startTimestamp) + "ms)");
        onSearchResultsAvailable.onSearchResultsAvailable(term, result);
    } catch (Exception e) {
        Log.d(Config.LOGTAG, "exception while searching ", e);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}