简体   繁体   中英

SQLite updating certain columns of a table with a click of a "add" button error and crashes

My app is suppose to have the users enter an amount and click the "add" button to add transactions into the "transactions" table and the amount that the user entered will also update the amount of the specified category (a certain column/field) in the "spendings" table.

The code for the add button is below :

public void AddTransactions (final int temp_position) {
        button_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int temp_id = 0;

                Cursor transactionlatestid = myDb.getLatestTransactionID(temp_position);
                if (transactionlatestid.getCount() == 0) {
                    temp_id = 1;
                } else {
                    transactionlatestid.moveToFirst();
                    temp_id = transactionlatestid.getInt(0);
                    temp_id += 1;
                }

                String transaction_id = String.valueOf(temp_id);

                String flightposition_id = String.valueOf(temp_position);

                boolean isInserted = myDb.insertTransactionData(amount.getText().toString(), category, note.getText().toString(), transaction_id, flightposition_id);


                if (isInserted = true) {
                    Toast.makeText(AddExpenses.this, "Transaction Inserted !", Toast.LENGTH_LONG).show();
                    clearText();
                    temp += 1;
                    getLatestAmount(temp_position, category);
                }
                else {
                    Toast.makeText(AddExpenses.this, "Transaction not Inserted !", Toast.LENGTH_LONG).show();
                }


            }
        });
    }

The method "getLatestAmount" is called when a transaction is successfully added. This method is to get the amount of the specified category that is currently already existing in the "spendings" table. For example, if the category is "Food and Drinks", this method will return the value in that column "foodndrinks" from the "spendings" table and then the "updateAddTotalExpenses" is called later.

The code is below :

public void getLatestAmount (int temp_position, String category) {
        temp_position += 1;
        String id = String.valueOf(temp_position);
        String temp_category = "";
        double amountfromdb = 5.00 ;

        if (category == "Food and Drinks")
        {
            temp_category = "foodndrinks";
        }
        else if (category == "Travel")
        {
            temp_category = "travel";
        }
        else if (category == "Shopping")
        {
            temp_category = "shopping";
        }
        else if (category == "Entertainment")
        {
            temp_category = "entertainment";
        }
        else if (category == "Others")
        {
            temp_category = "others";
        }

        Cursor latestamount = myDb.getLatestAmount(id, temp_category);
        if (latestamount.getCount() == 0) {
            Toast.makeText(AddExpenses.this, "No amount found !", Toast.LENGTH_LONG).show();
        } else {
            latestamount.moveToFirst();
            amountfromdb = latestamount.getDouble(0);
            updateAddTotalExpenses(id ,temp_category, amountfromdb);
        }
    }

This method "updateAddTotalExpenses" is used to add the sum of amount that is in the "spendings" table of the specified category and the amount that is entered by the user, and then update the newest amount into the specified "category" in the "spendings" table.

    public void updateAddTotalExpenses(String temp_position,String temp_category, double newestamount) {

        double amount_tobeadded = Double.parseDouble(amount.getText().toString());
        newestamount += amount_tobeadded;

        if (category == "Food and Drinks") {
            myDb.updateFnDData(temp_position, temp_category, newestamount);
        }

        sTracker.RefreshAllSpendings();
    }

The "spending" table code in my DatabaseHelper.class which extends SQLiteOpenHelper :-

    private static final String SPENDING_TABLE = "spendings";
    private static final String ID_SPENDING = "id";
    private static final String BUDGET = "budget";
    private static final String TOTAL_EXPENSES = "total_expenses";
    private static final String FOODNDRINKS = "foodndrinks";
    private static final String TRAVEL = "travel";
    private static final String SHOPPING = "shopping";
    private static final String ENTERTAINMENT = "entertainment";
    private static final String OTHERS = "others";
    private static final String BALANCE = "balance";

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + SPENDING_TABLE + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, BUDGET DOUBLE, TOTAL_EXPENSES DOUBLE, FOODNDRINKS DOUBLE, TRAVEL DOUBLE, SHOPPING DOUBLE, ENTERTAINMENT DOUBLE, OTHERS DOUBLE, BALANCE DOUBLE)");

        db.execSQL("CREATE TABLE " + TRANSACTION_TABLE + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, AMOUNT DOUBLE NOT NULL, CATEGORY TEXT NOT NULL, NOTE TEXT, TRANSACTION_ID TEXT NOT NULL, FLIGHT_ID INTEGER NOT NULL, FOREIGN KEY (FLIGHT_ID) REFERENCES FLIGHT_TABLE(id) )");
    }

The method below is in the DatabaseHelper.class which is called from the Main class to get the amount of the specified category in the "spendings" table.

    public Cursor getLatestAmount(String id, String category) {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor latestamount = db.rawQuery("SELECT "+category+" FROM spendings WHERE id =" +id , null);
        return latestamount;
    }

The method below "updateFnDData" is in the DatabaseHelper.class which is called from the Main class to update the amount of the specified category with the newestamount (old amount + new amount entered by user)

***Note : For now I only have a single method to update a column in the "spendings" table which is the "foodndrinks" column as I just want to test whether my concept and code is correct before I add more.

    public boolean updateFnDData(String id, String category, double newamount) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues contentValues = new ContentValues();

        db.update(SPENDING_TABLE, contentValues, "id = ?"+"category = ?", new String[] {id});

        return true;

    }

Below is the logcat which appears when I try to click the "add" button after entering an amount into the EditText box, the transaction is successfully added into the "transactions" table but the amount in the "spendings" table of the specified category is not updated.especially this two methods "getLatestAmount" and "updateFnDData" in the DatabaseHelper.class .

   --------- beginning of crash
10-23 22:07:23.419 4070-4070/project.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: project.myapplication, PID: 4070
    java.lang.NumberFormatException: empty String
        at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
        at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
        at java.lang.Double.parseDouble(Double.java:539)
        at project.myapplication.AddExpenses.updateAddTotalExpenses(AddExpenses.java:231)
        at project.myapplication.AddExpenses.getLatestAmount(AddExpenses.java:225)
        at project.myapplication.AddExpenses$3.onClick(AddExpenses.java:155)
        at android.view.View.performClick(View.java:6294)
        at android.view.View$PerformClick.run(View.java:24770)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

In these lines of updateFnDData() :

ContentValues contentValues = new ContentValues();
db.update(SPENDING_TABLE, contentValues, "id = ?"+"category = ?", new String[] {id});

you pass empty contentValues to the update() method.

Before db.update() set the contentValues like this:
contentValues.put(columnname, newamount);
replace columnname with the name of the column to be updated.
Edit in SPENDING_TABLE where you want the update there is no category column. Maybe you should change the WHERE part of the update() method to something like:
"id = ? AND something = ?"

Edit2 change to this in updateFnDData() :

ContentValues contentValues = new ContentValues();
contentValues.put("foodndrinks", newamount);
db.update(SPENDING_TABLE, contentValues, "id = ?", new String[] {id});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM