草庐IT

Android获取数据库列的总和

coder 2023-12-25 原文

我需要帮助来汇总我数据库中一列(金额)中的所有值。我可以得到一个特定的值。 .但我需要特定列的总和,有人告诉我我做错了什么

这是我的代码

    Button button3 = (Button) findViewById(R.id.button3);
    button3.setOnClickListener(new OnClickListener() {          
       public void onClick(View v) {                
          DatabaseAdapter databaseAdapter = new DatabaseAdapter(getApplicationContext());
          databaseAdapter.open();
          ArrayList<String> records = databaseAdapter.fetchAllRecords();
          if (records.size() > 0) {
              et.setText(records.get(0));
          }
          databaseAdapter.close();
      }
   });

    //Create our database by opening it and closing it
    DatabaseAdapter databaseAdapter = new DatabaseAdapter(getApplicationContext());
    databaseAdapter.open();
    databaseAdapter.close();
} 

private Object append(CharSequence text) {
    // TODO Auto-generated method stub
    return null;
}

/** Create a new dialog for date picker */
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
       case DATE_DIALOG_ID:
         return new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
    }
    return null;
}
}

这是数据库部分 DatabaseAdapter.java

package com.example.androidtablayout;

import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.text.Editable;

public class DatabaseAdapter {

    private Context context;
    private SQLiteDatabase database;
    private DatabaseOpenHelper dbHelper;

    public DatabaseAdapter(Context context) {
       this.context = context;
    }

    public DatabaseAdapter open() throws SQLException {
       dbHelper = new DatabaseOpenHelper(context);
       database = dbHelper.getWritableDatabase();
       return this;
    }

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


    public long createRecord(String text,int j,String text1,String text2) {
        ContentValues contentValue = new ContentValues();       
        contentValue.put("date", text);     
        contentValue.put("amount", j);  
        contentValue.put("des", text1);
        contentValue.put("category", text2);
        return database.insert("Extable", null, contentValue);
    }

    public boolean updateRecord(long rowId,String text,int j,String text1,String text2) {
        ContentValues contentValue = new ContentValues();
        contentValue.put("date", text);     
        contentValue.put("amount", j);  
        contentValue.put("des", text1);
        contentValue.put("category", text2);
        return database.update("Extable", contentValue, "_id =" + rowId, null) > 0;
    }

    public boolean deleteRecord(long rowId) {
        return database.delete("Extable", "_id =" + rowId, null) > 0;
    }

    public ArrayList<String> fetchAllRecords() {
        Cursor cursor = database.query("Extable", new String[] { "_id", "date", "amount", "des", "category"},
                null, null, null, null, null);      
        ArrayList<String> records = new ArrayList<String>();        
        cursor.moveToFirst();
        for (int i = 0; i < cursor.getCount(); i++) {           
            records.add(cursor.getString(1));       
            cursor.moveToNext();
        }
        cursor.close();
        return records;
    }

    public String fetchRecord(long rowId) throws SQLException {
        Cursor mCursor = database.query(true, "Extable", new String[] { "_id",
                        "date","amount", "des","category" }, "_id ="+ rowId, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
            return (mCursor.getString(1));
        }
        return null;
    }

    public Cursor rawQuery(String string, Object object) {
        // TODO Auto-generated method stub
        return null;
    }

请任何人帮助我。 谢谢你

最佳答案

这样做:

Cursor cur = db.rawQuery("SELECT SUM(myColumn) FROM myTable", null);
if(cur.moveToFirst())
{
    return cur.getInt(0);
}

关于Android获取数据库列的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20582320/

有关Android获取数据库列的总和的更多相关文章

  1. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  2. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  3. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  4. ruby - 从 Ruby 中的主机名获取 IP 地址 - 2

    我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge

  5. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

  6. ruby-on-rails - 获取 inf-ruby 以使用 ruby​​ 版本管理器 (rvm) - 2

    我安装了ruby​​版本管理器,并将RVM安装的ruby​​实现设置为默认值,这样'哪个ruby'显示'~/.rvm/ruby-1.8.6-p383/bin/ruby'但是当我在emacs中打开inf-ruby缓冲区时,它使用安装在/usr/bin中的ruby​​。有没有办法让emacs像shell一样尊重ruby​​的路径?谢谢! 最佳答案 我创建了一个emacs扩展来将rvm集成到emacs中。如果您有兴趣,可以在这里获取:http://github.com/senny/rvm.el

  7. Ruby 从大范围中获取第 n 个项目 - 2

    假设我有这个范围:("aaaaa".."zzzzz")如何在不事先/每次生成整个项目的情况下从范围中获取第N个项目? 最佳答案 一种快速简便的方法:("aaaaa".."zzzzz").first(42).last#==>"aaabp"如果出于某种原因你不得不一遍又一遍地这样做,或者如果你需要避免为前N个元素构建中间数组,你可以这样写:moduleEnumerabledefskip(n)returnto_enum:skip,nunlessblock_given?each_with_indexdo|item,index|yieldit

  8. ruby - Net::HTTP 获取源代码和状态 - 2

    我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur

  9. ruby-on-rails - 使用 ruby​​ 将多个实例变量转换为散列的更好方法? - 2

    我收到格式为的回复#我需要将其转换为哈希值(针对活跃商家)。目前我正在遍历变量并执行此操作:response.instance_variables.eachdo|r|my_hash.merge!(r.to_s.delete("@").intern=>response.instance_eval(r.to_s.delete("@")))end这有效,它将生成{:first="charlie",:last=>"kelly"},但它似乎有点hacky和不稳定。有更好的方法吗?编辑:我刚刚意识到我可以使用instance_variable_get作为该等式的第二部分,但这仍然是主要问题。

  10. ruby - 没有类方法获取 Ruby 类名 - 2

    如何在Ruby中获取BasicObject实例的类名?例如,假设我有这个:classMyObjectSystem我怎样才能使这段代码成功?编辑:我发现Object的实例方法class被定义为returnrb_class_real(CLASS_OF(obj));。有什么方法可以从Ruby中使用它? 最佳答案 我花了一些时间研究irb并想出了这个:classBasicObjectdefclassklass=class这将为任何从BasicObject继承的对象提供一个#class您可以调用的方法。编辑评论中要求的进一步解释:假设你有对象

随机推荐