从检索到的 sqlite 列中更改字符串

Change String from sqlite columns retrieved

我想更改使用游标适配器从 sqlite 获取的字符串

我正在使用它来获取数据:

    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 +")";

我有一个自定义列表,我将它加载到列表视图中,其中包含 2 个类似这样的文本视图,并尝试了这种方式:

    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);

但是没用。我怎样才能做到这一点。

您可以告诉数据库 return 所需格式的值:

SELECT _id,
       month || ' - ' || year AS date,
       SUM(valor) || ' (' || SUM(total_valor) || ')' AS valor_final
FROM records
GROUP BY month;

如果您无法控制光标,您可以改用自定义 ViewBinder class 来重新格式化值。

您可以在查询中使用 :-

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";

或者只是:-

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

你不需要:-

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 +")";

因为所有工作都在 SELECT SQL 中完成,并且相应地命名了列。