there is a function, how to make it return the value of the query?

public void getMyMoney() throws SQLException { open(); String strSQL = "select SUM(operat_sum) as Costs from operations"; database.execSQL(strSQL); close(); } 

here are the open() & close methods

 public void open() throws SQLException { database = dbHelper.getWritableDatabase(); } public void close() { dbHelper.close(); } 

so changed and throws out the java.lang.IllegalStateException error

  public int getMyMoney2() throws SQLException { open(); int myMoney = 0; String strSQL = "select SUM(operat_sum) as Costs from operations"; Cursor c = database.rawQuery(strSQL, null); if (c.moveToFirst()) { // определяем номера столбцов по имени в выборке int idColIndex = c.getColumnIndex("operat_sum"); do { // получаем значения по номерам столбцов myMoney = c.getInt(idColIndex); Log.d(LOG_TAG, "COLUMN_OPERAT_SUM = " + c.getInt(idColIndex)); } while (c.moveToNext()); } close(); return myMoney; } 
  • Need c.getColumnIndex("Costs") - temq
  • @temq, thank you very much, inattention - java

1 answer 1

You need to get a Cursor, the cursor returns the query, rawQuery, it should work, something like this

 public List<OurObject> getMyMoney() throws SQLException { open(); List<OurObject> ourObjectList = new ArrayList<OurObject>(); String strSQL = "select SUM(operat_sum) as Costs from operations"; Cursor c = database.rawQuery(strSQL, null); if (c.moveToFirst()) { // определяем номера столбцов по имени в выборке int idColIndex = c.getColumnIndex("id"); int nameColIndex = c.getColumnIndex("name"); int emailColIndex = c.getColumnIndex("email"); do { // получаем значения по номерам столбцов OurObject ourObject = new OurObject(); ourObject.id = c.getInt(idColIndex); ourObject.name = c.getInt(nameColIndex); ourObject.email = c.getInt(emailColIndex); ourObjectList.add(ourObject); } while (c.moveToNext()); } close(); return ourObjectList; } 
  • I changed your method a bit and the java.lang.IllegalStateException error fell out java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it. java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it. - java