我试图在from和to日期之间获取数据。 我在sql lite上做过,它有效 我尝试在android编码部分,它不起作用,你们可以请帮助
protected void adddata1() throws ParseException {
Database db=new Database(Reportmonth.this);
SQLiteDatabase sb=db.getReadableDatabase();
String a=from.getText().toString();
String b=to.getText().toString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date a1=sdf.parse(a);//convert string to date
Date b1=sdf.parse(b);//convert string to date
Cursor cus=sb.rawQuery("select * from expenz where daty between '" + a1 +"' AND '"+b1+"'",null);
cus.moveToFirst();
for(int i=0;i<cus.getCount();i++)
{
if(cus!=null) //i think the error starts from this onwards.
{
soi.setText(cus.getString(0));
Log.i("",cus.getString(0));
desc.setText(cus.getString(3));
dat.setText(cus.getString(1));
woc.setText(cus.getString(2));
amount.setText(cus.getString(5));
adddata();
search.setClickable(false);
}
cus.moveToNext();
}
}
答案 0 :(得分:1)
不建议将date
作为varchar
存储在数据库中,就像处理像你这样的情况一样,这是一个真正的痛苦
还在下面我展示了一个解决方法,您可以从表中提取所有数据,将表格中的日期列从string
转换为Date
对象,然后进行比较。但是,当数据库中的行非常高时,这将会非常强烈地达到性能。
//For storing the rows that are in between the date range
ArrayList<HashMap<String, String>> rowList = new ArrayList<HashMap<String, String>>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//Important that the date should be in the same format as specified above
Date startDate = sdf.parse(a);//convert string to date
Date endDate = sdf.parse(b);//convert string to date
Cursor cus = sb.rawQuery("select * from expenz",null);
if (cursor.moveToFirst()) {
do {
try {
//Converting the database `varchar date` to `Date` object here
//Here cursor.getString(X) should be the column number of your daty column
//And also the date format in the database should also be same as "yyyy-MM-dd"
Date thisDate = sdf.parse(cursor.getString(X));
// Check if the database date is within the range
if (thisDate.after(startDate) && thisDate.before(endDate)) {
HashMap<String, String> map = new HashMap<String, String>();
//Here have the number of columns you want to have according to your database
map.put("column0", cursor.getString(0));
map.put("column1", cursor.getString(1));
map.put("column2", cursor.getString(2));
map.put("column3", cursor.getString(3));
map.put("column4", cursor.getString(4));
map.put("column5", cursor.getString(5));
rowList.add(map);
}
} catch (ParseException e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
}
// Now here the rowList will have the rows between the specified date range
您可以修改最内部if loop
以满足您的要求。
我希望它有所帮助!