Search code examples
androidsqlitereturnandroid-sqlite

Two return statements in SQLite helper class not permitted


To understand my question we need to explain the project design. We have a simple MVP concept with a DB that has 3 columns id name cost(int) The DBHelper and Model Classes are used and a ListActivity that is backed by a RecyclerAdapter as well as a DetailsActivity that displays all the elements from the DB when an item in the ListActivity is selected. The launch activity MainActivity will permit the user to run a number of queries standard fair show all the data in the ArrayList that is populated in the DBHelper after a call from the ListActivity Here is the important part the DBHelper has this statement to send the dbList back to ListActivity "return modelList" So we decided to create a query that SUMS the values in the cost column and RETURN the sum to the MainActivity. DBHelper is quite unhappy with TWO RETURN statements. Because the call to the DBHelper is made from the ListActivity we tried to bypass this by making a direct call from MainActivity NO Way DBHelper says one RETURN statement. My question is how to return the sum value from DBHelper? The query works and we will post the code that is called from Main below.

    public sumALL(){
    Cursor cursorA =null;
    db = this.getWritableDatabase();
    String q = "SELECT SUM(cost) FROM " + TABLE_INFO;
    cursorA = db.rawQuery(q,null);
    if(cursorA.moveToFirst()){

        totalPrice = cursorA.getInt(0);
    }

    cursorA.close();
    db.close();
    return totalPrice;

Solution

  • For any one who looks at the first two answers YES they work and both do not address the question, Nor did the commentators and yours truly look closely at the construction of the method in the DBHelper Class this public sumALL(){ is so wrong it should be public int sumALL(){ so making a call from the MainActivity code will be posted and the properly constructed sumALL method for the DBHelper will be posted

    Call code from MainActivity

            helper = new DBHelper(this);
            helper.summALL();
            etLineTwo.setText(String.valueOf(totalPrice));
            DecimalFormat df = new DecimalFormat("#.00"); // Set your desired format here.
            String dollarSIGN = df.format(totalPrice/100.0);
            etLineTwo.setText(String.valueOf("of Gas   $"+dollarSIGN));
    

    Code for DBHelper method with the return

        public int summALL(){
        Cursor cursor = null;
        db = this.getWritableDatabase();
        String query = "SELECT SUM(cost) FROM " + TABLE_INFO;
        cursor = db.rawQuery(query,null);
        if(cursor.moveToFirst()){
    
            totalPrice = cursor.getInt(0);
        }
        db.close();
        cursor.close();
        return totalPrice;
    }