android - 在 TextView 中显示 SQLite 查询的总和值

标签 android sqlite android-sqlite

我正在构建一个预算数据库,我可以将所有交易记录放入 ListView 并显示在屏幕上。我创建了一个 textview 来保存所有交易值的总和,但无法弄清楚如何让它显示在 textview 中。我收到以下错误:

Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory)' on a null object reference.

这是我尝试开始工作的代码:

SQLiteDatabase database = mDbHelper.getReadableDatabase();
public int cmIncomeSum() {
    int total = 0;
    Cursor sumQuery = database.rawQuery("SELECT SUM(income) FROM transactions WHERE income >=0 AND expense ISNULL AND strftime('%m',date)=strftime('%m',date('now')) AND strftime('%Y',date)=strftime('%Y',date('now'))", null);
    if (sumQuery.moveToFirst()) {
        total = sumQuery.getInt(0);
    }
    return total;
}

和 TextView :

    TextView cmIncomeSumTextView = (TextView) findViewById(R.id.cm_income_sum_text_view);
    cmIncomeSumTextView.setText(sum);

这是整个 Activity :

public class CMIncomeTransactionsActivity extends AppCompatActivity implements
        LoaderManager.LoaderCallbacks<Cursor> {

    /** Identifier for the transaction data loader */
    private static final int TRANSACTION_LOADER = 0;

    /** Adapter for the ListView */
    IncomeCursorAdapter mCursorAdapter;

    // Database helper object //
    private BudgetDbHelper mDbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cm_income_transactions);

        // Setup FAB to open EditorActivity
        Button fab = (Button) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(CMIncomeTransactionsActivity.this, IncomeEditorActivity.class);
                startActivity(intent);
            }
        });

        // Find the ListView which will be populated with the transaction data
        ListView incomeListView = (ListView) findViewById(R.id.list);

        // Find and set empty view on the ListView, so that it only shows when the list has 0 items.
        View emptyView = findViewById(R.id.empty_view);
        incomeListView.setEmptyView(emptyView);

        // Setup an Adapter to create a list item for each row of transaction data in the Cursor.
        mCursorAdapter = new IncomeCursorAdapter(this, null);
        incomeListView.setAdapter(mCursorAdapter);

        // Setup the item click listener
        incomeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                // Create new intent to go to {@link EditorActivity}
                Intent intent = new Intent(CMIncomeTransactionsActivity.this, IncomeEditorActivity.class);

                // Form the content URI that represents the specific transaction that was clicked on,
                // by appending the "id" (passed as input to this method) onto the
                // {@link BudgetEntry#CONTENT_URI}.
                Uri currentTransactionUri = ContentUris.withAppendedId(BudgetEntry.CONTENT_URI, id);

                // Set the URI on the data field of the intent
                intent.setData(currentTransactionUri);

                // Launch the {@link EditorActivity} to display the data for the current transaction.
                startActivity(intent);
            }
        });

        // Kick off the loader
        getLoaderManager().initLoader(TRANSACTION_LOADER, null, this);

      // Define query for the SUM of the current month income and display it on the screen//

        TextView cmIncomeSumTextView = (TextView) findViewById(R.id.cm_income_sum_text_view);
        cmIncomeSumTextView.setText(cmIncomeSum());


    }

    SQLiteDatabase database = mDbHelper.getReadableDatabase();
    public int cmIncomeSum() {
        int total = 0;
        Cursor sumQuery = database.rawQuery("SELECT SUM(income) FROM transactions WHERE income >=0 AND expense ISNULL AND strftime('%m',date)=strftime('%m',date('now')) AND strftime('%Y',date)=strftime('%Y',date('now'))", null);
        if (sumQuery.moveToFirst()) {
            total = sumQuery.getInt(0);
        }
        return total;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu options from the res/menu/menu_catalog.xml file.
        // This adds menu items to the app bar.
        getMenuInflater().inflate(R.menu.menu_catalog, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        return super.onOptionsItemSelected(item);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {

        // Define a projection that specifies the columns from the table we care about.
        String[] projection = {
                BudgetEntry._ID,
                BudgetEntry.COLUMN_DATE,
                BudgetEntry.COLUMN_DESCRIPTION,
                BudgetEntry.COLUMN_INCOME,
                BudgetEntry.COLUMN_INCOME_CATEGORY,
                BudgetEntry.COLUMN_EXPENSE,
                BudgetEntry.COLUMN_STATUS};


        // Where clause to only display income transactions //
        String selection = "income >=0 AND expense ISNULL AND strftime('%m',date)=strftime('%m',date('now')) AND strftime('%Y',date)=strftime('%Y',date('now'))";

        // This loader will execute the ContentProvider's query method on a background thread
        return new CursorLoader(this,   // Parent activity context
                BudgetEntry.CONTENT_URI,   // Provider content URI to query
                projection,             // Columns to include in the resulting Cursor //
                selection,                  // Where selection clause /
                null,                   // selection arguments //
                BudgetEntry.COLUMN_DATE);                  // Default sort order //
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        // Update {@link IncomeCursorAdapter} with this new cursor containing updated transaction data
        mCursorAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        // Callback called when the data needs to be deleted
        mCursorAdapter.swapCursor(null);
    }

}

我在这里看了很多不同的帖子,但没有一个有用。
请帮忙!

最佳答案

例如,我想显示家族是“Heard”或“Carry”的角色的名字,或者你想要将谁保存在数据库中并将其保存在数组列表中的每个人: 在 MyDataBaseClass 的一种方法中:

public Cursor showName(String family){
        SQLiteDatabase db = this.getWritableDatabase();

        Cursor data = db.rawQuery(" SELECT Name FROM "+TBL_NAME+ " WHERE Family==?" , new String[]{family});

        return data;
    }

在主要范围内:

MyDataBaseClass db = new MyDataBaseClass();
Cursor res = db.showName("Heard");
        if (res.getCount() == 0) {
            //do nothing
        } else {
            ArrayList<String> list = new ArrayList<>();
            while (res.moveToNext()) {
                list.add(res.getString(0));
            }
        }

这个答案可能不完全是你想要做的,但我希望能帮助到你

关于android - 在 TextView 中显示 SQLite 查询的总和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51209162/

相关文章:

ios - FMDB 排队 - 如何正确实现此模式?

c - C语言编程中的Sqlite

android - 在 android 中执行 getwritabledatabase() 时出现错误

python - 使用 sqlite 在 Django 中进行查询过滤

android - 为离线应用程序创建备份的最佳方法?

android - 为我的应用程序指定最大 sqlite db 大小。如何处理数据库完全异常

android - 以编程方式更改约束布局中的高度?

android - 寻找 BackupAgent(用于 sqlite 数据库)示例

android - 如何在android中创建像windows输入键一样的编辑文本

android - 在手机硬件上运行机器学习模型的可行性?