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

时间:2018-09-23 11:10:03

标签: android sqlite listview android-cursoradapter

我想使用游标适配器更改从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个这样的textview的listview中,并尝试了这种方式:

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

但是它不起作用。我该怎么做到。

2 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

您可以使用:-

在查询本身中执行此操作
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中完成的,因此相应地命名了列。