从SQL android获取项目数

时间:2015-11-02 14:54:58

标签: android sqlite count android-sqlite

我的应用程序上有一个SQL数据库。

正如标题所说,我怎样才能计算物品数量?

我的应用程序从用户获取输入并存储在数据库中,并显示它。

MainActivity.java

String task = inputField.getText().toString();
Log.d("MainActivity",task);

helper = new TaskDBHelperHome(MainActivity.this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();

values.clear();
values.put(TaskContractHome.Columns.TASK, task);

db.insertWithOnConflict(TaskContractHome.TABLE, null, values,
        SQLiteDatabase.CONFLICT_IGNORE);
updateUI();

TaskDBHelperHome.java

public class TaskDBHelperHome extends SQLiteOpenHelper {

    public TaskDBHelperHome(Context context) {
        super(context, TaskContractHome.DB_NAME, null, TaskContractHome.DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqlDB) {
        String sqlQuery =
                String.format("CREATE TABLE %s (" +
                                "_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                                "%s TEXT)", TaskContractHome.TABLE,
                        TaskContractHome.Columns.TASK);

        Log.d("TaskDBHelper","Query to form table: "+sqlQuery);
        sqlDB.execSQL(sqlQuery);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqlDB, int i, int i2) {
        sqlDB.execSQL("DROP TABLE IF EXISTS "+TaskContractHome.TABLE);
        onCreate(sqlDB);
    }
}

TaskContractHome.java

import android.provider.BaseColumns;

public class TaskContractHome {
    public static final String DB_NAME = "home";
    public static final int DB_VERSION = 1;
    public static final String TABLE = "tasks";

    public class Columns {
        public static final String TASK = "task";
        public static final String _ID = BaseColumns._ID;
    }
}

我想知道如何计算数据库中的项目。 (我的意思是编程)谢谢。

2 个答案:

答案 0 :(得分:0)

就像喝水一样简单!只需执行以下SQL语句。

SELECT COUNT(*)
    FROM [table_name]
Cursor count= db.rawQuery(sql_string, null);
count.moveToFirst();
int itemsCount= count.getInt(0);
count.close();

答案 1 :(得分:0)

试试这个:

SQLiteDatabase db = this.getReadableDatabase();
    int totalCount = 0;
    String query = "select COUNT(*) from apartments";
    Cursor cursor = db.rawQuery(query, null);

    if (cursor.moveToNext()) {
        totalCount = cursor.getInt(0);
    }

    return totalCount;