如何根据给出的两个条件检索数据?

时间:2015-12-19 13:55:50

标签: android sqlite listview where-clause

在MainActivity中,我希望listView显示特定月份的数据。

 public void BuildList()
    {
        sqlcon.open(); // object of InfoAPI
        Calendar cal = Calendar.getInstance();
        int month = cal.get(Calendar.MONTH)+1;
        Toast.makeText(getApplicationContext(),month+"",Toast.LENGTH_LONG).show();
        Cursor cursor1=sqlcon.readData(month);
        String[] columns=new String[]{
        MyDatabaseHelper.Date,MyDatabaseHelper.TimeIn_Info,MyDatabaseHelper.TimeOut_Info
        };

        int[] to=new int[]
         {
           R.id.date,R.id.timeIn,R.id.timeOut
         };

        dataAdapter = new SimpleCursorAdapter(this, R.layout.retrieve_data,
                cursor1,
                columns,
                to,
                0);

        dataAdapter.setViewBinder(new ViewBinder());
        listView.setAdapter(dataAdapter);
    }

}

InfoAPI

public Cursor readData(int m)
    {
        Cursor c=database.rawQuery(" SELECT _id, Date,Weather,Status, TimeIn_Info, TimeOut_Info FROM " + MyDatabaseHelper.TABLE_INFO + 
                " WHERE Name = ? and strftime('%m',Date)= ?", 
                new String[]{"LCV"}, new String[]{String.valueOf(m)},null);

        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

错误

 Error:(54, 26) error: no suitable method found for rawQuery(String,String[],String[],<null>)
    method SQLiteDatabase.rawQuery(String,String[]) is not applicable
    (actual and formal argument lists differ in length)
    method SQLiteDatabase.rawQuery(String,String[],CancellationSignal) is not applicable
    (actual and formal argument lists differ in length)

Error:(106, 30) error: method readData in class InfoAPI cannot be applied to given types;
required: int
found: no arguments
reason: actual and formal argument lists differ in length

我在rawQuery中有点困惑。为了根据两个条件检索数据,写入的正确方法是什么?

被修改

 public Cursor readData(int m)
    {
        Cursor c=database.rawQuery(" SELECT _id, Date,Weather,Status, TimeIn_Info, TimeOut_Info FROM " + MyDatabaseHelper.TABLE_INFO +
                        " WHERE Name = ? and strftime('%m',Date)= ?",
                new String[]{ "LCV", String.valueOf(m) }, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

对于Date列,它包含日期格式19-12-2015。现在没有错误,但ListView上没有数据显示。

1 个答案:

答案 0 :(得分:0)

没有rawQuery方法需要两个单独的String[]。正如错误所指出的

no suitable method found for rawQuery(String,String[],String[],<null>)

而不是像这样查询

rawQuery(query, new String[]{"LCV"}, new String[]{String.valueOf(m)},null);

请改用此方法,WHERE语句的列位于同一String[]

rawQuery(query, new String[]{ "LCV", String.valueOf(m) }, null);

甚至只是因为你最后不需要null

rawQuery(query, new String[]{ "LCV", String.valueOf(m) });

由于您要使用零填充数字查询日期格式,因此请使用String.format("%02d",m)代替String.valueOf(m)