Adam Katz Adam Katz - 2 months ago 12
Android Question

android sqlite where value can be any value

I have a function which takes in a month and year parameter and returns all values from the DB where month and year match, now I need to make a query to the db where year matches a variable but month can be any month, i want to use the same function rather than create a new function, so with what values do I call this function.

Current call looks like this

ArrayList<PaymentHistory> allPayment = dataSource.findfiltered("Transactions", yearToGet, monthToGet);


and then function looks like this

public ArrayList<PaymentHistory> findfiltered(String dbName, String year, String month){
//this needs to be done still
String whereClause = DBOpenHelper.YEAR + " = ? AND "+ DBOpenHelper.STATUS + " = ? AND " + DBOpenHelper.MONTH + " = ?";
String[] whereArgs = new String[] {
year,
"paid", //we only want successful transactions
month
};
Cursor cursor = database.query(dbName, allColumns, whereClause, whereArgs, null, null, null); //must sort this

ArrayList<PaymentHistory> paymentHistories = getListDatas(cursor);
cursor.close();
return paymentHistories;
}

Answer

Make the following changes in your method.

public ArrayList<PaymentHistory> findfiltered(String dbName, String year,  String month){
        //this needs to be done still
        String whereClause = DBOpenHelper.YEAR + " = ? AND "+ DBOpenHelper.STATUS + " = ? AND "  + DBOpenHelper.MONTH + " = ?";
        String[] whereArgs = new String[] {
                year,
                "paid", //we only want successful transactions
                month
        };
        if(month == null) {
                whereClause = DBOpenHelper.YEAR + " = ? AND "+ DBOpenHelper.STATUS + " = ?";
                String[] whereArgs = new String[] {
                        year,
                        "paid"                        
                };
        }


        Cursor cursor = database.query(dbName, allColumns, whereClause, whereArgs, null, null, null); //must sort this

        ArrayList<PaymentHistory> paymentHistories = getListDatas(cursor);
        cursor.close();
        return paymentHistories;
}

Now when you need to get result regardless of the month, just pass a null at month's place.

ArrayList<PaymentHistory> allPayment = dataSource.findfiltered("Transactions", yearToGet, null);