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

The following are Jave code examples for showing how to use getString() 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: IslamicLibraryAndroid   File: DownloadInfo.java   Source Code and License Vote up 6 votes
public DownloadInfo(Cursor cursor) {
    int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
    status = cursor.getInt(columnIndex);

    int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
    reason = cursor.getInt(columnReason);

    int columnBytesDownloadedSoFar = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
    bytesDownloadedSoFar = cursor.getLong(columnBytesDownloadedSoFar);

    int columnId = cursor.getColumnIndex(DownloadManager.COLUMN_ID);
    enquId = cursor.getLong(columnId);

    int columnTitlle = cursor.getColumnIndex(DownloadManager.COLUMN_TITLE);
    title = cursor.getString(columnTitlle);

    int columnTimeStamp = cursor.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP);
    lastModifiedTimestamp = cursor.getLong(columnTimeStamp);

    int columnTotlalSize = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
    totalSizeBytes = cursor.getLong(columnTotlalSize);

}
 
Example 2
Project: MyAnimeViewer   File: CroperinoFileUtil.java   Source Code and License Vote up 6 votes
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };
    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}
 
Example 3
Project: FuelFriend   File: DatabaseHelper.java   Source Code and License Vote up 6 votes
/**
 * use this function to get the Fuel price of current day
 * @param context context of this is running in
 * @param towncode towncode of town you want to get fuel price
 * @param isDiesel <code>true</code> if you want to know diesel price else <code>false</code>
 *                for petrol price
 * @param columnName name of column from which you want to retrieve data
 *                    pass null to get the data from column containing price of current day.
 * @return <code>isDiesel?currentDieselPrice:currentPetrolPrice</code>
 */
public static String getCurrentFuelPriceForGiven(Context context, String towncode, boolean isDiesel,
                                                 String columnName) {
    if(columnName == null) {
        columnName = getCurrentDay();
    }
    SQLiteDatabase db = getReadableDatabase(context);
    String selectionArgs[] = {towncode};
    final String TABLE_NAME = isDiesel?HpclDieselPriceTable.NAME:HpclPetrolPriceTable.NAME;
    final String[] PROJECTION = {PriceBaseTable.COLUMN_TOWN_CODE, columnName};
    Cursor data = db.query(TABLE_NAME, PROJECTION, PriceBaseTable.COLUMN_TOWN_CODE
            + "=?", selectionArgs, null, null, null);
    if(data != null) {
        data.moveToFirst();
        String price = data.getString(1);
        data.close();
        return price; // magic number based on table projection
    }
    return null;
}
 
Example 4
Project: shareNote   File: NoteActivity.java   Source Code and License Vote up 6 votes
public void selectDB() {
    noteList = new ArrayList<>();
    Cursor cursor = mDatabase.query(NoteDB.TABLE_NAME, null, null, null, null, null, sortOrder);
    while (cursor.moveToNext()) {
        String title = cursor.getString(cursor.getColumnIndex("title"));
        String content = cursor.getString(cursor.getColumnIndex("content"));
        Long time = cursor.getLong(cursor.getColumnIndex("time"));
        int id = cursor.getInt(cursor.getColumnIndex("id"));
        Post note = new Post(title, content, time, id);
        noteList.add(note);
    }
    noteAdapter = new NoteAdapter(this, noteList);
    mMenuRecyclerView.setLayoutManager(new LinearLayoutManager(this));//布局管理器
    mMenuRecyclerView.addItemDecoration(new ListViewDecoration(this));//添加分割线
    mMenuRecyclerView.setSwipeMenuCreator(swipeMenuCreator);
    //设置菜单item点击监听
    mMenuRecyclerView.setSwipeMenuItemClickListener(mOnSwipeMenuItemClickListener);
    noteAdapter.setOnItemClickListener(mOnItemClickListener);
    mMenuRecyclerView.setAdapter(noteAdapter);
    cursor.close();
}
 
Example 5
Project: UbiBike-client   File: MyDBHandler.java   Source Code and License Vote up 6 votes
/**
 * Get a list of all stations
 */
public List<Station> getAllStations() {
    List<Station> listOfAllStations = new ArrayList<Station>();

    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_STATIONS;
    Cursor c = db.rawQuery(query, null);
    while(c.moveToNext()) {
        Station entry = new Station(
                c.getString(c.getColumnIndex(COLUMN_ID_SERVER)),
                c.getString(c.getColumnIndex(COLUMN_NAME)),
                c.getString(c.getColumnIndex(COLUMN_LOCATION)),
                c.getInt(c.getColumnIndex(COLUMN_BIKESAVAILABLE)),
                c.getFloat(c.getColumnIndex(COLUMN_LATITUDE)),
                c.getFloat(c.getColumnIndex(COLUMN_LONGITUDE)),
                c.getFloat(c.getColumnIndex(COLUMN_CLIENT_DISTANCE))
        );
        listOfAllStations.add(entry);
    }

    db.close();
    c.close();
    return listOfAllStations;
}
 
Example 6
Project: MovieGuide   File: TestDB.java   Source Code and License Vote up 6 votes
/**
 * Tests that the database exists and the quotes table has the correct columns.
 */
@Test
public void testCreateDb() throws Exception {
    // build a HashSet of all of the table names we wish to look for
    // Note that there will be another table in the DB that stores the
    // Android metadata (db version information)
    final HashSet<String> tableNameHashSet = new HashSet<>();
    tableNameHashSet.add(FavoritesContract.FavoriteColumns.FAVORITE_MOVIES_TBL);
    tableNameHashSet.add(FavoritesContract.FavoriteColumns.FAVORITE_TV_SHOWS_TBL);
    tableNameHashSet.add(FavoritesContract.FavoriteColumns.FAVORITE_PERSON_TBL);

    Context appContext = InstrumentationRegistry.getTargetContext();
    appContext.deleteDatabase(FavoritesDbHelper.DATABASE_NAME);
    SQLiteDatabase db = new FavoritesDbHelper(appContext).getWritableDatabase();
    assertEquals(true, db.isOpen());

    // have we created the tables we want?
    Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);

    assertTrue("Error: This means that the database has not been created correctly",
            c.moveToFirst());

    // verify that the tables have been created
    do {
        tableNameHashSet.remove(c.getString(0));
    } while( c.moveToNext() );

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

    // now, do our tables contain the correct columns?
    c = db.rawQuery("PRAGMA table_info(" + FavoritesContract.FavoriteColumns.FAVORITE_MOVIES_TBL + ")", null);
    assertTrue("Error: This means that we were unable to query the database for table information.",
            c.moveToFirst());

    // Build a HashSet of all of the column names we want to look for
    final HashSet<String> locationColumnHashSet = new HashSet<>();
    locationColumnHashSet.add(FavoritesContract.FavoriteColumns._ID);
    locationColumnHashSet.add(FavoritesContract.FavoriteColumns.COLUMN_MOVIE_ID);
    locationColumnHashSet.add(FavoritesContract.FavoriteColumns.COLUMN_TITLE);
    locationColumnHashSet.add(FavoritesContract.FavoriteColumns.COLUMN_PLOT);
    locationColumnHashSet.add(FavoritesContract.FavoriteColumns.COLUMN_POSTER_PATH);
    locationColumnHashSet.add(FavoritesContract.FavoriteColumns.COLUMN_YEAR);
    locationColumnHashSet.add(FavoritesContract.FavoriteColumns.COLUMN_DURATION);
    locationColumnHashSet.add(FavoritesContract.FavoriteColumns.COLUMN_VOTE_AVERAGE);
    locationColumnHashSet.add(FavoritesContract.FavoriteColumns.COLUMN_VOTE_COUNT);
    locationColumnHashSet.add(FavoritesContract.FavoriteColumns.COLUMN_BACKGROUND_PATH);
    locationColumnHashSet.add(FavoritesContract.FavoriteColumns.COLUMN_ORIGINAL_LANGUAGE);
    locationColumnHashSet.add(FavoritesContract.FavoriteColumns.COLUMN_STATUS);
    locationColumnHashSet.add(FavoritesContract.FavoriteColumns.COLUMN_IMDB_ID);
    locationColumnHashSet.add(FavoritesContract.FavoriteColumns.COLUMN_BUDGET);
    locationColumnHashSet.add(FavoritesContract.FavoriteColumns.COLUMN_REVENUE);
    locationColumnHashSet.add(FavoritesContract.FavoriteColumns.COLUMN_HOMEPAGE);

    int columnNameIndex = c.getColumnIndex("name");
    do {
        String columnName = c.getString(columnNameIndex);
        locationColumnHashSet.remove(columnName);
    } while(c.moveToNext());

    c.close();
    // if this fails, it means that your database doesn't contain all of the required columns
    assertTrue("Error: The database doesn't contain all of the required columns",
            locationColumnHashSet.isEmpty());
    db.close();
}
 
Example 7
Project: q-mail   File: MigrationTo51.java   Source Code and License Vote up 6 votes
private static MimeHeader loadHeaderFromHeadersTable(SQLiteDatabase db, long messageId) {
    Cursor headersCursor = db.query("headers",
            new String[] { "name", "value" },
            "message_id = ?", new String[] { Long.toString(messageId) }, null, null, null);
    try {
        MimeHeader mimeHeader = new MimeHeader();
        while (headersCursor.moveToNext()) {
            String name = headersCursor.getString(0);
            String value = headersCursor.getString(1);
            mimeHeader.addHeader(name, value);
        }
        return mimeHeader;
    } finally {
        headersCursor.close();
    }
}
 
Example 8
Project: Android-Music-Player   File: artitstBtns.java   Source Code and License Vote up 6 votes
String getFirstPath(){

        String searchString = MediaStore.Audio.Media.IS_MUSIC + "=?" + "AND " + MediaStore.Audio.Media.ARTIST_ID + " = " + data[1];
        String[] searchPram = new String[]{"1"};
        String[] cols = new String[] {MediaStore.Audio.Media.DATA};
        Cursor cursor = Ui.ef.getBaseContext().getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,cols, searchString  ,searchPram,null);



        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            return  cursor.getString(0);
        }
        cursor.close();
        return  null;

    }
 
Example 9
Project: GitHub   File: AlbumTask.java   Source Code and License Vote up 6 votes
/**
 * get the cover and count
 *
 * @param buckId album id
 */
private void buildAlbumCover(ContentResolver cr, String buckId, AlbumEntity album) {
    String[] photoColumn = new String[]{Media._ID, Media.DATA};
    Cursor coverCursor = cr.query(Media.EXTERNAL_CONTENT_URI, photoColumn, SELECTION_ID,
            new String[]{buckId, "image/jpeg", "image/png", "image/jpg", "image/gif"}, Media.DATE_MODIFIED + " desc");
    try {
        if (coverCursor != null && coverCursor.moveToFirst()) {
            String picPath = coverCursor.getString(coverCursor.getColumnIndex(Media.DATA));
            String id = coverCursor.getString(coverCursor.getColumnIndex(Media._ID));
            album.mCount = coverCursor.getCount();
            album.mImageList.add(new ImageMedia(id, picPath));
            if (album.mImageList.size() > 0) {
                mBucketMap.put(buckId, album);
            }
        }
    } finally {
        if (coverCursor != null) {
            coverCursor.close();
        }
    }
}
 
Example 10
Project: aos-Video   File: AutoScraperActivity.java   Source Code and License Vote up 6 votes
private void rejectScraperInfos(int position) {
    if (position >= 0) {
        // Get the path corresponding to the item
        Cursor cursor = mActivityFileCursor;
        cursor.moveToPosition(position);
        String path = cursor.getString(mDataIndex);

        // Makie sure this item is processed and that scraper infos have been found
        FileProperties itemProperties = mFileProperties.get(path);
        if (itemProperties.status == ITEM_STATUS_SUCCESS) {
            // Set this item as rejected
            itemProperties.status = ITEM_STATUS_REJECTED;
            Log.d(TAG, "onClick : reject infos for " + path);

            // Reset the scraper fields for this item in the medialib (set them to -1 so
            // that this file will skipped when launching the automated process again)
            // this also removes data from the scraper database
            updateScraperInfoInMediaLib(path, -1, -1);

            // Update the display
            invalidateItem(position);
        }
    }
}
 
Example 11
Project: fast_face_android   File: MainActivity.java   Source Code and License Vote up 6 votes
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        // When an Image is picked
        if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
            // Get the Image from data
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            // Get the cursor
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            mTestImgPath = cursor.getString(columnIndex);
            cursor.close();
            if (mTestImgPath != null) {
                runDetectAsync(mTestImgPath);
                //Toast.makeText(this, "Img Path:" + mTestImgPath, Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "You haven't picked Image", Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
    }
}
 
Example 12
Project: localcloud_fe   File: FileHelper.java   Source Code and License Vote up 6 votes
/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 * @author paulburke
 */
public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {

            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } catch (Exception e) {
        return null;
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}
 
Example 13
Project: Cluttr   File: Util.java   Source Code and License Vote up 6 votes
/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context       The context.
 * @param uri           The Uri to query.
 * @param selection     (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}
 
Example 14
Project: OpenHub   File: TraceUserDao.java   Source Code and License Vote up 5 votes
@Override
public TraceUser readEntity(Cursor cursor, int offset) {
    TraceUser entity = new TraceUser( //
        cursor.getString(offset + 0), // login
        cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // name
        cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // avatarUrl
        cursor.isNull(offset + 3) ? null : cursor.getInt(offset + 3), // followers
        cursor.isNull(offset + 4) ? null : cursor.getInt(offset + 4), // following
        cursor.isNull(offset + 5) ? null : new java.util.Date(cursor.getLong(offset + 5)), // startTime
        cursor.isNull(offset + 6) ? null : new java.util.Date(cursor.getLong(offset + 6)), // latestTime
        cursor.isNull(offset + 7) ? null : cursor.getInt(offset + 7) // traceNum
    );
    return entity;
}
 
Example 15
Project: DoList   File: Festival.java   Source Code and License Vote up 5 votes
public void setalarm() {

		if ((!database.isOpen()) || database == null) {
			database = openOrCreateDatabase("db.db", MODE_PRIVATE, null);// 打开数据库
		}
		int requestCode = 0;
		// ------------------------------获取数据
		String table = "festival";
		String[] columns = { "name", "date", "flag", "dataid" };
		String selection = null;
		String[] selectionArgs = null;
		Cursor cursor = database.query(table, columns, selection,
				selectionArgs, null, null, null);
		cursor.moveToPosition(cursor.getCount() - 1);// 移动到最后一行
		int idColumnIndex = cursor.getColumnIndex("dataid");
		int idValue = cursor.getInt(idColumnIndex); // 得到最后一行的id
		int contentColumnIndex = cursor.getColumnIndex("name");
		String contentValue = cursor.getString(contentColumnIndex); // 得到最后一行的内容
		int alarmColumnIndex = cursor.getColumnIndex("date");
		String alarmValue = cursor.getString(alarmColumnIndex); // 得到最后一行的闹铃时间
		requestCode = idValue;
		// ---------------------------------------------------------------------
		alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
		Intent intent = new Intent(Festival.this, FestivalClockActivity.class);
		intent.putExtra("content", contentValue);// 传递内容
		intent.putExtra("alarmtime", alarmValue);// 传递闹铃时间
		pi = PendingIntent.getActivity(Festival.this, requestCode, intent,
				PendingIntent.FLAG_CANCEL_CURRENT); // 根据id设置不同的闹钟
		Calendar alarmTime = Calendar.getInstance();
		long alarmdatetime = changedatetime(alarmValue); // 将时间转换为long型
		alarmManager.set(AlarmManager.RTC_WAKEUP, alarmdatetime, pi);
		Toast.makeText(getApplicationContext(), "闹钟设置好了", Toast.LENGTH_LONG)
				.show();
		database.close();// 关闭数据库连接
	}
 
Example 16
Project: yaacc-code   File: MusicGenresFolderBrowser.java   Source Code and License Vote up 5 votes
@Override
public List<Container> browseContainer(YaaccContentDirectory contentDirectory, String myId) {
	List<Container> result = new ArrayList<Container>();
	String[] projection = { MediaStore.Audio.Genres._ID, MediaStore.Audio.Genres.NAME };
	String selection = "";
	String[] selectionArgs = null;
       Map<String,MusicAlbum> folderMap= new HashMap<String,MusicAlbum>();
	Cursor mediaCursor = contentDirectory.getContext().getContentResolver().query(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, projection, selection,
			selectionArgs, MediaStore.Audio.Genres.NAME + " ASC");

	if (mediaCursor != null) {
		mediaCursor.moveToFirst();
		while (!mediaCursor.isAfterLast()) {
			String id = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Audio.Genres._ID));
			String name = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Audio.Genres.NAME));
			MusicAlbum musicAlbum = new MusicAlbum(ContentDirectoryIDs.MUSIC_GENRE_PREFIX.getId()+id, ContentDirectoryIDs.MUSIC_GENRES_FOLDER.getId(), name, "", 0);
               folderMap.put(id, musicAlbum);
			Log.d(getClass().getName(), "Genre Folder: " + id + " Name: " + name);
			mediaCursor.moveToNext();
		}
           mediaCursor.close();
           for(Map.Entry<String,MusicAlbum> entry : folderMap.entrySet()){
               entry.getValue().setChildCount(getMusicTrackSize(contentDirectory, entry.getKey()));
               result.add(entry.getValue());
           }
       } else {
           Log.d(getClass().getName(), "System media store is empty.");
       }
	Collections.sort(result, new Comparator<Container>() {

		@Override
		public int compare(Container lhs, Container rhs) {
			return lhs.getTitle().compareTo(rhs.getTitle());
		}
	});

	return result;
}
 
Example 17
Project: Kasumi   File: Database.java   Source Code and License Vote up 5 votes
public Account findAccountByUser(String user, String serverCode) {
    if (user.length() == 0) {
        return null;
    }
    KRFAM.log("Database > findAccountByUser");
    try {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String selection = Accounts.cUser + "=? AND " + Accounts.cServer + "=?";
        String[] selectionArgs = {user, serverCode};
        Cursor c = db.query(Accounts.tName, null, selection, selectionArgs, null, null, null, "1");
        if (c.moveToFirst()) {
            Account a = new Account();
            a.id = c.getLong(c.getColumnIndex(Accounts._ID));
            a.name = c.getString(c.getColumnIndex(Accounts.cName));
            a.server = c.getString(c.getColumnIndex(Accounts.cServer));
            a.locked = true;
            a.loaded = 0;
            a.isFolder = false;
            a.u_UUID = c.getString(c.getColumnIndex(Accounts.cUser));
            a.u_Code = c.getString(c.getColumnIndex(Accounts.cCode));
            a.u_Pass = c.getString(c.getColumnIndex(Accounts.cPass));
            c.close();
            db.close();
            return a;
        }
    } catch (Exception e) {
        KRFAM.log(e);
    }
    return null;
}
 
Example 18
Project: aos-MediaLib   File: VideoStoreImportImpl.java   Source Code and License Vote up 5 votes
/** helper to get a comma separated list of all ids */
private static String getRemoteIdList (ContentResolver cr) {
    Cursor c = cr.query(MediaStore.Files.getContentUri("external"), REMOTE_LIST_PROJECTION, null, null, null);
    String result = null;
    if (c != null) {
        if (c.moveToFirst()) {
            result = c.getString(0);
        }
        c.close();
    }
    return TextUtils.isEmpty(result) ? "" : result;
}
 
Example 19
Project: keepass2android   File: UserBigramDictionary.java   Source Code and License Vote up 5 votes
/** Prune any old data if the database is getting too big. */
private void checkPruneData(SQLiteDatabase db) {
    db.execSQL("PRAGMA foreign_keys = ON;");
    Cursor c = db.query(FREQ_TABLE_NAME, new String[] { FREQ_COLUMN_PAIR_ID },
            null, null, null, null, null);
    try {
        int totalRowCount = c.getCount();
        // prune out old data if we have too much data
        if (totalRowCount > sMaxUserBigrams) {
            int numDeleteRows = (totalRowCount - sMaxUserBigrams) + sDeleteUserBigrams;
            int pairIdColumnId = c.getColumnIndex(FREQ_COLUMN_PAIR_ID);
            c.moveToFirst();
            int count = 0;
            while (count < numDeleteRows && !c.isAfterLast()) {
                String pairId = c.getString(pairIdColumnId);
                // Deleting from MAIN table will delete the frequencies
                // due to FOREIGN KEY .. ON DELETE CASCADE
                db.delete(MAIN_TABLE_NAME, MAIN_COLUMN_ID + "=?",
                    new String[] { pairId });
                c.moveToNext();
                count++;
            }
        }
    } finally {
        c.close();
    }
}
 
Example 20
Project: financisto1-holo   File: TransactionsListAdapter.java   Source Code and License Vote up 4 votes
@Override
protected void bindView(BlotterViewHolder v, Context context, Cursor cursor) {
    long toAccountId = cursor.getLong(BlotterColumns.to_account_id.ordinal());
    String payee = cursor.getString(BlotterColumns.payee.ordinal());
    String note = cursor.getString(BlotterColumns.note.ordinal());
    long locationId = cursor.getLong(BlotterColumns.location_id.ordinal());
    String location = "";
    if (locationId > 0) {
        location = cursor.getString(BlotterColumns.location.ordinal());
    }
    String toAccount = cursor.getString(BlotterColumns.to_account_title.ordinal());
    long fromAmount = cursor.getLong(BlotterColumns.from_amount.ordinal());
    if (toAccountId > 0) {
        v.topView.setText(R.string.transfer);
        if (fromAmount > 0) {
            note = toAccount+" \u00BB";
        } else {
            note = "\u00AB "+toAccount;
        }
        u.setTransferTextColor(v.centerView);
    } else {
        String title = cursor.getString(BlotterColumns.from_account_title.ordinal());
        v.topView.setText(title);
        v.centerView.setTextColor(Color.WHITE);
    }

    long categoryId = cursor.getLong(BlotterColumns.category_id.ordinal());
    String category = "";
    if (categoryId != 0) {
        category = cursor.getString(BlotterColumns.category_title.ordinal());
    }
    String text = generateTransactionTitle(sb, payee, note, location, categoryId, category);
    v.centerView.setText(text);
    sb.setLength(0);

    long currencyId = cursor.getLong(BlotterColumns.from_account_currency_id.ordinal());
    Currency c = CurrencyCache.getCurrency(em, currencyId);
    long originalCurrencyId = cursor.getLong(BlotterColumns.original_currency_id.ordinal());
    if (originalCurrencyId > 0) {
        Currency originalCurrency = CurrencyCache.getCurrency(em, originalCurrencyId);
        long originalAmount = cursor.getLong(BlotterColumns.original_from_amount.ordinal());
        u.setAmountText(sb, v.rightCenterView, originalCurrency, originalAmount, c, fromAmount, true);
    } else {
        u.setAmountText(v.rightCenterView, c, fromAmount, true);
    }
    if (fromAmount > 0) {
        v.iconView.setImageDrawable(icBlotterIncome);
    } else if (fromAmount < 0) {
        v.iconView.setImageDrawable(icBlotterExpense);
    }

    long date = cursor.getLong(BlotterColumns.datetime.ordinal());
    v.bottomView.setText(DateUtils.formatDateTime(context, date,
            DateUtils.FORMAT_SHOW_DATE|DateUtils.FORMAT_SHOW_WEEKDAY|DateUtils.FORMAT_ABBREV_WEEKDAY|DateUtils.FORMAT_SHOW_TIME|DateUtils.FORMAT_ABBREV_MONTH));
    if (date > System.currentTimeMillis()) {
        u.setFutureTextColor(v.bottomView);
    } else {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(date);
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == Calendar.SUNDAY || dayOfWeek == Calendar.SATURDAY) {
            v.bottomView.setTextColor(Color.rgb(224, 112, 112));
        } else {
            v.bottomView.setTextColor(v.topView.getTextColors().getDefaultColor());
        }
    }

    long balance = cursor.getLong(BlotterColumns.from_account_balance.ordinal());
    v.rightView.setText(Utils.amountToString(c, balance, false));
    removeRightViewIfNeeded(v);
    setIndicatorColor(v, cursor);
}