简体   繁体   中英

Using SQLite Query to put only unique values into ListView for a “history app”

I honestly had no idea how to name this question properly..

I have a sqlite db with these columns.

private final String createDb = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " ( "
        + C_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + DATE + " text, "
        + SUBCAT + " text, "
        + ITEM + " text, "
        + PRICE + " integer, "
        + QUANTITY + " integer, "
        + WEIGHT + " integer, "
        + VOLUME + " integer, "
        + SALE + " text, "
        + STORE + " text, "
        + EXTRA + " text) ";

and was trying use ViewBinder to call a SQL query like the one below.

public String avgPrice() {
        ourHelper = new DbHelper(ourContext);
        db = ourHelper.getReadableDatabase(); 
        String sql = "SELECT AVG(PRICE) as avgprice, ITEM FROM " + TABLE_NAME + " GROUP BY " + ITEM;
        Cursor d = db.rawQuery(sql, null);

I originally had a ListView with an XML that contains a textview for each column. That just pulls each column 1:1 off the db. That was easy with an adapter. I am trying to use ViewBinder to detect the avg price for each entered item (if there are duplicate instances eg different date) and have that show up for the item.

Essentially I want the ListView to show only each item once (with avg price) and when you select it, you can view each stored instance (like a history).

What would be the easiest way to do this from where I'm at? Assuming that the ViewBinder method (or the query) can be used above, how do I extract the ITEM and AVG(PRICE) to put in the appropriate views only once to achieve my "history" function?

Add the following to the creation string of your database:

+ "UNIQUE(" + COLUMN_NAME + ") ON CONFLICT REPLACE);";

That way you will have whatever column name you want in there to be unique, duplicates will not be allowed and will be replaced if entered into the database twice. I assume one of the columns you have can be unique. Like an item_id for example, so then only one of that item can be added at a time, it will show the most recent with ON CONFLICT REPLACE .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM