Android 数据库按时间条件进行查询

2018-10-31  本文已影响0人  橘子你个凹瑞汁

因为项目需要,需要按时间进行查询数据


Android 数据库按时间条件进行查询

这里要是用数据库select*from进行条件判断
点击Edittext输入时间格式yyyy-mm-dd

SQLiteDatabase sqliteDatabase=helper.getReadableDatabase();
        String ss="select*from heart where heartdata>? and heartdata<?";  //查询条件
        Date s=getDate(startEdittext.getText().toString());
        Date e=getDate(endEdittext.getText().toString());
        Calendar cal = Calendar.getInstance();
        cal.setTime(s);
        Long startTime=cal.getTimeInMillis();
        Calendar cals = Calendar.getInstance();
        cals.setTime(e);
        Long endTime=cals.getTimeInMillis();
        
        String first="1970-01-03";
        Date j=getDate(first);
        Calendar cass=Calendar.getInstance();
        cass.setTime(j);
        Long firsTtime=cass.getTimeInMillis();
        
        String second="1970-01-02";
        Date h=getDate(second);
        Calendar calh=Calendar.getInstance();
        calh.setTime(h);
        Long secondTime=calh.getTimeInMillis();
        
        //Long thirdTime=firsTtime-secondTime;
        Long thirdTime=endTime+(firsTtime-secondTime);
        Toast.makeText(SearchActivity.this,thirdTime+"-",Toast.LENGTH_LONG).show();
        Cursor cursor = sqliteDatabase.rawQuery(ss,new String[] { String.valueOf(startTime), String.valueOf(thirdTime) });
        if(cursor.moveToLast()){
            do{

                Long hd=cursor.getLong(cursor.getColumnIndex("heartdata"));
                String heart_num=cursor.getString(cursor.getColumnIndex("heartnum"));
                SimpleDateFormat dq=new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss ");
                String hdd=dq.format(hd);
                traceList.add(new Trace(hdd,heart_num));
                //Toast.makeText(SearchActivity.this,hdd,Toast.LENGTH_SHORT).show();
            }while(cursor.moveToPrevious());
            aapter = new TraceListAdapter(this, traceList);
            lv.setAdapter(aapter);
            aapter.notifyDataSetChanged();
            cursor.close();
        }
    }

代码中的getDate()函数,是将字符串转化为日期的函数,
将日期转化为毫秒,例如一天转化为毫秒是24×3600×1000
起始时间是从“1970-01-01 08:00:00”开始算起的,所以我要得到一天的毫秒数,就要用1970-01-03减去1970-01-02
我的代码不够精简,大致思路就是这样。


Android 数据库按时间条件进行查询
上一篇下一篇

猜你喜欢

热点阅读