Search code examples
androidsqlitelistviewandroid-cursoradapter

Change String from sqlite columns retrieved


I would like to change the strings that are fetched from sqlite with cursor adapter

I'm using this to fetch data:

    String query = "SELECT _id, month, year, SUM(valor) AS valor, SUM(total_valor) AS total_valor FROM records GROUP BY month";
    Cursor cursor = db.rawQuery(query, null);

    String month_st = cursor.getString(1);
    String year_st = cursor.getString(2);
    String valor_st= cursor.getString(3);
    String total_valor_st = cursor.getString(4);

    String date = month_st + " - " +year_st;
    String valor_st_final = valor_st+ "(" +total_valor_st +")";

I have a custom list that I load into listview with 2 textviews that are like this, and tried this way:

    ListAdapter adapter = new SimpleCursorAdapter(ReportMes.this,
            R.layout.report_mes,
            cursor,
            new String[] {"date", "valor_st_final"},
            new int[] {R.id.data_mes, R.id.total_valor});


    listview.setAdapter(adapter);

But it doesn't work. How can I achieve this.


Solution

  • You can do this in the query itself using :-

    String query = "SELECT _id, month, year, month||' - '||year AS date, SUM(valor) AS valor, SUM(total_valor) AS total_valor, SUM(valor)||'('||SUM(total_valor)||')' AS valor_st_final FROM records GROUP BY month";
    

    Or just :-

    String query = "SELECT _id, month||' - '||year AS date, SUM(valor)||'('||SUM(total_valor)||')' AS valor_st_final FROM records GROUP BY month";
    

    You'd not need :-

    String month_st = cursor.getString(1);
    String year_st = cursor.getString(2);
    String valor_st= cursor.getString(3);
    String total_valor_st = cursor.getString(4);
    
    String date = month_st + " - " +year_st;
    String valor_st_final = valor_st+ "(" +total_valor_st +")";
    

    As all the work is done in SELECT SQL and the columns are named accordingly.