android studio(sqlite数据库)列中所有值的总和

时间:2016-09-22 22:35:43

标签: android sqlite

我想在"已销售"上添加所有值列和文本视图显示,,,我是新的Android,需要你的帮助吗?

SQLiteOpenHelper.java

公共类SQLiteHelper扩展了SQLiteOpenHelper {

static String DATABASE_NAME="DemoDataBase";

public static final String KEY_ID="id";

public static final String TABLE_NAME="demoTable";

public static final String KEY_Name="name";

public static final String KEY_Sold="sold";

public static final String KEY_Subject="subject";

public SQLiteHelper(Context context) {

    super(context, DATABASE_NAME, null, 1);

}

@Override
public void onCreate(SQLiteDatabase database) {

    String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_Name+" VARCHAR, "+KEY_Sold+" VARCHAR, "+KEY_Subject+" VARCHAR)";
    database.execSQL(CREATE_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);

}

}

2 个答案:

答案 0 :(得分:3)

你的意思是这样的吗?

public String Sum() {
        String[] columns = new String[] {"SUM("+KEY_CONTENT2+")" };
        Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,null,null,null,null,null);
        String result = "";
        int index_SUM = cursor.getColumnIndex("SUM("+KEY_CONTENT2+")");
        for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
            result = result + cursor.getString(index_SUM)  + "\n";
        }
        return result;
}

答案 1 :(得分:0)

试试这个

static String DATABASE_NAME="DemoDataBase";

public static final String KEY_ID="id";

public static final String TABLE_NAME="demoTable";

public static final String KEY_Name="name";

public static final String KEY_Sold="sold";

public static final String KEY_Subject="subject";

public SQLiteHelper(Context context) {

super(context, DATABASE_NAME, null, 1);

}

@Override
public void onCreate(SQLiteDatabase database) {

String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_Name+" VARCHAR, "+KEY_Sold+" VARCHAR, "+KEY_Subject+" VARCHAR)";
database.execSQL(CREATE_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);

}

public int getSold(){
int sold = 0;
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.query(TABLE_NAME,null,null,null,null,null,null);
if(cursor.moveToFirst()){
     while(!cursor.isAfterLast()){
      sold += cursor.getString(cursor.getColumnIndex(KEY_Sold));
      cursor.moveToNext();
   }
  cursor.close();
  }
 database.close();
 return sold;
}

然后在您的活动中,文本视图存在

 String sold_count = getSold().toString();
 myTextView.setText(sold_count);

希望这有效