如何使用求和查询在sqlite数据库适配器中构造getTotal方法?

时间:2014-12-04 13:40:43

标签: android sqlite

是否有人能够帮助我从以下sqlite db adapter java文件构造一个公共getTotal()方法?

我想使用此方法为“'金额”的总和返回单个值。添加所有记录的列。

构建我可以找到的选项的唯一方法是基于游标,它返回整行。我想要一个返回单个值的方法,然后可以在TextView中调用和显示该值。

非常感谢任何帮助!

 public static final String KEY_ROWID = "_id";
 public static final String KEY_NAME = "name";
 public static final String KEY_AMOUNT = "amount";
 public static final String KEY_EMAIL = "email";
 private static final String TAG = "CountriesDbAdapter";
 private DatabaseHelper mDbHelper;
 private SQLiteDatabase mDb;

//set name of database and table
private static final String DATABASE_NAME = "EventDB";
private static final String SQLITE_TABLE = "Donor";
private static final int DATABASE_VERSION = 1;

private final Context mCtx;

private static final String DATABASE_CREATE =
       "CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
               KEY_ROWID + " integer PRIMARY KEY autoincrement," +
               KEY_NAME + "," +
               KEY_AMOUNT + " numeric," +
               KEY_EMAIL + "," +
               " UNIQUE (" + KEY_EMAIL +"));";

private static class DatabaseHelper extends SQLiteOpenHelper {

  DatabaseHelper(Context context) {
     super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }


  @Override
  public void onCreate(SQLiteDatabase db) {
     Log.w(TAG, DATABASE_CREATE);
     db.execSQL(DATABASE_CREATE);
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
     Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
             + newVersion + ", which will destroy all old data");
     db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
     onCreate(db);
  }
  }

 public DonorsDbAdapter(Context ctx) {
  this.mCtx = ctx;
 }

public DonorsDbAdapter open() throws SQLException {
  mDbHelper = new DatabaseHelper(mCtx);
  mDb = mDbHelper.getWritableDatabase();
  return this;
}

public void close() {
  if (mDbHelper != null) {
     mDbHelper.close();
   }
 }

public long createDonor(String name, double amount,
                         String email) {

  ContentValues initialValues = new ContentValues();

  initialValues.put(KEY_NAME, name);
  initialValues.put(KEY_AMOUNT, amount);
  initialValues.put(KEY_EMAIL, email);

  return mDb.insert(SQLITE_TABLE, null, initialValues);
 }

2 个答案:

答案 0 :(得分:1)

您应该执行此查询并将table_name替换为您的表名。

 SELECT SUM(amount) FROM table_name;

答案 1 :(得分:1)

public int getTotalAmount() {
    int amount = 0;
    SQLiteDatabase db = getReadableDatabase();

    Cursor cursor = db.rawQuery("SELECT SUM(" + KEY_AMOUNT +") FROM " + SQLITE_TABLE , null);
    if (cursor.moveToFirst()) {
        amount = Integer.parseInt(cursor.getString(0));
    }
    db.close();
    return amount;
}