Отображение значения суммы запроса SQLite в текстовом представлении - PullRequest
0 голосов
/ 06 июля 2018

Я строю базу данных бюджета, и я могу получить все транзакции в виде списка и отобразить на экране. Я создал текстовое представление для хранения суммы всех значений транзакции, но не могу понять, как его отобразить в текстовом представлении. Я получаю следующую ошибку:

Попытка вызвать виртуальный метод «android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase (java.lang.String, int, android.database.sqlite.SQLiteDatabase $ CursorFactory) 'на нуле ссылка на объект.

Вот код, который я пытаюсь заставить работать:

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 cmIncomeSumTextView = (TextView) findViewById(R.id.cm_income_sum_text_view);
    cmIncomeSumTextView.setText(sum);

а вот и вся активность:

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);
    }

}

Я просмотрел здесь много разных постов, и ни один из них не помог.
Пожалуйста, помогите!

Ответы [ 2 ]

0 голосов
/ 06 июля 2018

например, я хочу показать имя символов этого семейства "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));
            }
        }

этот ответ может не совсем то, что вы хотите сделать, но я надеюсь помочь вам

0 голосов
/ 06 июля 2018

Вы не инициализировали mDbHelper в CMIncomeTransactionsActivity классе, поэтому инициализируйте mDbHelper в onCreate и попробуйте.

...