数据库Android列的Sum int值

时间:2014-08-08 13:57:55

标签: java android sql

我想要对列的整数值求和。  我的代码用来总结:

public int getTotal() {
    // TODO Auto-generated method stub
    int sum=0;
    Cursor cursor = database.rawQuery("SELECT SUM(name) FROM "+dbHelper.getTableName(), null);
    if(cursor.moveToFirst()) {
        sum=cursor.getInt(0);
    }
    return sum;
}

我试过的其他方式:

public int sum() {      
    x=0;
    for (int i =list.size(); i>0 ; i--) {
        Log.e("sumprice","");
        x = x +list.get(i).getName(); 
    }
    return x;
}

DATABASE HELPER

public class DatabaseHelper extends SQLiteOpenHelper {

private final String TAG = "DatabaseHelper";
private static final String DATABASE_NAME = "db";   
private static final String TABLE_NAME    = "contacts";
private static final String COLUMN_ID     = "_id";
private static final String COLUMN_NAME   = "name";
private static final String COLUMN_VALUE  = "value";
private static final String COLUMN_NUM  = "num";
private static final String COLUMN_TYPE  = "type";
private static final String COLUMN_CODE  = "CODE";
public static final String COLUMN_ESME  = "ESME";
private static final String CREATE_TABLE  = "CREATE TABLE " + TABLE_NAME + " (" + 
    COLUMN_ID + " INTEGER PRIMARY KEY," +
    COLUMN_NAME + "INTEGER," +
    COLUMN_VALUE + "INTEGER," +
    COLUMN_NUM + " TEXT," +
    COLUMN_TYPE + " TEXT," +
    COLUMN_CODE + " TEXT," +
    COLUMN_ESME + " TEXT" +
    ");";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null,8);

    Log.i(TAG, "Object created.");
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w(DatabaseHelper.class.getName(), "Upgrading database from version "
            + oldVersion + " to " + newVersion + ", which will destroy all old data");
    db.execSQL("Drop table if exists " + TABLE_NAME);
    onCreate(db);
}

public String getTableName() {
    return TABLE_NAME;
}

public String getRowIdName() {
    return COLUMN_ID;
}
}

DATABASE处理程序

public class DatabaseHandler {

private final String TAG     = "DatabaseHandler";
static final  String NAME    = "name";
static final  String VALUE   = "value";
static final  String NUM    = "num";
static final  String TYPE   = " type";
static final  String CODE    = "code";
static final  String ESME   = "esme";

private DatabaseHelper dbHelper;
private SQLiteDatabase database;

public DatabaseHandler(Context context) {
    dbHelper = new DatabaseHelper(context);
    Log.i(TAG, "Object created.");
}

public void open() throws SQLException {
    database = dbHelper.getWritableDatabase();
}

public void close() {
    dbHelper.close();
}

public void insertContact(contac contacts) {
    database = dbHelper.getWritableDatabase();

    ContentValues cv = new ContentValues();
    Log.e("D","1.1");

    cv.put(NAME,contacts.getName());
    cv.put(VALUE,contacts.getPhoneNumber());
    cv.put(NUM,contacts.getNUM());
    cv.put(TYPE,contacts.getTYPE());
    cv.put(CODE,contacts.getCODE());
    cv.put(ESME,contacts.getESME());

    Log.e("D","1.2");

//  Log.e("",cv);

    database.insert(dbHelper.getTableName(), NAME, cv);
    Log.e("","1.8");
    Log.i(TAG, "Contact added successfully.");
    Log.e("","1.9");
}

public void deleteContact(long id) {
    database.delete(dbHelper.getTableName(), dbHelper.getRowIdName() + "=" + id, null);
}

public void updateContact(long id) {
    ContentValues cv = new ContentValues();

    cv.put(NAME,  3123123);
    cv.put(VALUE,  "12345");    
    cv.put(NUM, "123543");
    cv.put(TYPE, "benzini");
    cv.put(CODE, "123543");
    cv.put(ESME, "benzini");    
    database.update(dbHelper.getTableName(), cv, dbHelper.getRowIdName() + "=" + id, null);
}

public List<contac> getAllContacts() {
SQLiteDatabase database = dbHelper.getWritableDatabase();
Log.e("D","1.9");
    List<contac> contacts = new ArrayList<contac>();
    Log.e("D","1.9");
    Cursor cursor = database.query(dbHelper.getTableName(),null, null, null, null, null, null);
    Log.e("D","1.9");
    cursor.moveToFirst();
    Log.e("D","1.9");
    while (!cursor.isAfterLast()) {     
        Log.e("D","1.9");
        contac contact= cursorTocontac(cursor);
        Log.e("D","1.9");
        contacts.add(contact);
        Log.e("D","1.9");
        cursor.moveToNext();
    }
    // Make sure to close the cursor
    cursor.close();
    return contacts;
}

private contac cursorTocontac(Cursor cursor) {
    contac contacts = new contac(0, 0, 0, TAG, TAG, TAG, TAG);
    Log.e("","2");
    contacts.setId(cursor.getLong(0));
    contacts.setName(cursor.getInt(1));
    contacts.setPhoneNumber(cursor.getInt(2));
    contacts.setNUM(cursor.getString(3));
    contacts.setTYPE(cursor.getString(4));
    contacts.setCODE(cursor.getString(5));
    contacts.setESME(cursor.getString(6));
    Log.e("","2.1");
    return contacts;
}
public void clearTable() {
    SQLiteDatabase database = dbHelper.getWritableDatabase();
        database.delete(dbHelper.getTableName(), null, null);
         // helper is object extends SQLiteOpenHelper
    }

public long getNAMESum() {
    database = dbHelper.getWritableDatabase();
    Log.e("F","1.9");
    long result = 0;
    Log.e("F","1.9.1");
    Cursor cur = database.rawQuery("SELECT SUM(COLUMN_NAME) FROM myTable", null);
    Log.e("F","1.9.2");
    if(cur.moveToFirst())
    {
        return cur.getInt(0);
    }
    cur.close();
    return result;
}
public int getTotal() {
    // TODO Auto-generated method stub
    int sum=0;
    Cursor cursor = database.rawQuery("SELECT SUM(name) FROM "+dbHelper.getTableName(), null);
        if(cursor.moveToFirst()) {
            sum=cursor.getInt(0);
        }
        return sum;
       }

public void delete(String id)
{
    database = dbHelper.getWritableDatabase();
    database.delete(dbHelper.getTableName(), "_id=?", new String[]{id});
    database.close();
}
}

列表适配器

public class ListAdapter extends ArrayAdapter<contac> {
private final String TAG = "*** ListAdapter ***";
Context context;
 LayoutInflater myInflater;
 List<contac> list;
    CheckBox checkBox6;
    int x;
public ListAdapter(Context context, int resource,
        List<contac> list) {
    super(context, resource, list);
        this.context = context;
        this.list = list;
    myInflater = LayoutInflater.from(context);
    this.context = context;
    Log.i(TAG, "Adapter setuped successfully.");
}

public void setData(List<contac> list) {
    this.list = list;

    Log.i(TAG, "Data passed to the adapter.");
}
public void clear(List<contac> list) {
    list.clear();       
    Log.i(TAG, "Data passed to the adapter.");
}
@Override
public int getCount() {
    return list.size();
}
public void remove(contac contac) {
    list.remove(contac);
    updateList(list);
    setData(list);
    }


@Override
public long getItemId(int position) {
    return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    final ViewHolder holder;        

    if (convertView == null) {
        convertView     = myInflater.inflate(R.layout.list_adapter, null);
        holder          = new ViewHolder();
    //  holder.tvId     = (TextView) convertView.findViewById(R.id.tvId);
        holder.tvName   = (TextView) convertView.findViewById(R.id.tvName);
        holder.tvPhone  = (TextView) convertView.findViewById(R.id.tvPhone);
        holder.tvnum    = (TextView) convertView.findViewById(R.id.tvnum);
        holder.tvtype   = (TextView) convertView.findViewById(R.id.tvtype);
        holder.tvcode   = (TextView) convertView.findViewById(R.id.tvcode);
        holder.tvesme   = (TextView) convertView.findViewById(R.id.tvesme);
        holder.checkBox6    =  (CheckBox)convertView.findViewById(R.id.checkBox6);  
        holder.checkBox6
          .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
              contac element = (contac) holder.checkBox6.getTag();
              element.setSelected(buttonView.isChecked());
            }
          });
        convertView.setTag(holder);
        holder.checkBox6.setTag(list.get(position));

    } else {
        holder = (ViewHolder) convertView.getTag();
        ((ViewHolder) convertView.getTag()).checkBox6.setTag(list.get(position));
    }
//  ViewHolder  holder = (ViewHolder) convertView.getTag();
    NumberFormat format = NumberFormat.getCurrencyInstance();
//  holder.tvId.setTag(list.get(position).getIdInString());
//  holder.tvId.setText(list.get(position).getIdInString());
    holder.tvName.setText(format.format(list.get(position).getName()));
    holder.tvPhone.setText(format.format(list.get(position).getPhoneNumber()));
    holder.tvnum.setText(list.get(position).getNUM());  
    holder.tvtype.setText(list.get(position).getTYPE());
    holder.tvcode.setText(list.get(position).getCODE());
    holder.tvesme.setText(list.get(position).getESME());
    holder.checkBox6.setChecked(list.get(position).isSelected());       
    return convertView;
}
static class ViewHolder {
//  TextView tvId;
    TextView tvName;
    TextView tvPhone;
    TextView tvnum;
    TextView tvtype;
    TextView tvcode;
    TextView tvesme;
    CheckBox checkBox6;
}
public int sum() {      
 x=0;
    for (int i =list.size(); i>0 ; i--) {
        Log.e("sumprice","");
         x = x +list.get(i).getName(); 
        }
    return x;
}
public List<contac> getcontac() {
    return list;
}   
    public void updateList(List<contac> list) {

        this.list = list;
        notifyDataSetChanged();

    }
}

和我在文本视图中设置的代码

int sum=dbHandler.getTotal();
txtsumprice = (TextView) view.findViewById(R.id.sumprice);
NumberFormat format = NumberFormat.getCurrencyInstance();
txtsumprice.setText(""+format.format(sum));

可以解决我的问题我非常努力但没有工作

1 个答案:

答案 0 :(得分:0)

您有SQL语法错误(...myTotalFROM...):

Cursor cursor = database.rawQuery("SELECT Sum(name)myTotalFROM "+dbHelper.getTableName(), null); 

应该是:

Cursor cursor = database.rawQuery("SELECT Sum(name) AS myTotal FROM "+dbHelper.getTableName(), null); 
相关问题