【问题标题】:Sqlite query for date range in android?Sqlite查询android中的日期范围?
【发布时间】:2015-12-12 21:45:32
【问题描述】:

我在运行从数据库中检索给定时间段内数据的查询时遇到问题。
这个想法是用户选择 2 个不同的日期(从、到),然后使用从 SQLite 数据库检索到的数据填充 ListView - 该数据介于 fromto 日期之间。
没有WHERE 子句,查询可以完美运行,但是当我尝试设置日期范围时,它会失败。

我已将日期存储在 SQLite 中,格式为 M/d/yyyy 12:00:00 AM
当我以这种格式yyyy-MM-dd 将日期(参数)发送到SELECT 语句时。

我不知道如何处理。

这是我的代码:

    public class ProductionCommentsActivity extends Activity implements View.OnClickListener {
    private DBHandler dbHandler;
    private ListView listView;
    private Context context;
    private ArrayList<String> results = new ArrayList<String>();
    private ArrayAdapter adapter;
    private static String newline = System.getProperty("line.separator");
    private EditText editTextFrom, editTextTo;
    private DatePickerDialog datePickerDialogFrom, datePickerDialogTo;
    private SimpleDateFormat simpleDateFormat;
    private String fromDate,toDate ; // variables to store the chosen dates


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_production_comments);



        dbHandler = new DBHandler(this, dbHandler.DATABASE_NAME_PRODUCTION, null, 1);
        try {
            dbHandler.copyDataBase();
            Log.d("copydb", dbHandler.getDatabaseName());
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("copydb",e.getMessage());
        }

        //defining list view
        listView = (ListView) findViewById(R.id.listView);

        //defining edit texts properties
        editTextFrom = (EditText) findViewById(R.id.editTextFrom);
        editTextFrom.setInputType(InputType.TYPE_NULL);
        editTextFrom.requestFocus();

        editTextTo = (EditText) findViewById(R.id.editTextTo);
        editTextTo.setInputType(InputType.TYPE_NULL);

        //setting up the date format
        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
        setDateTimeField();
        context = this;
    }

    //method to handle the date pickers properties
    private void setDateTimeField() {
        editTextFrom.setOnClickListener((View.OnClickListener) ProductionCommentsActivity.this);
        editTextTo.setOnClickListener((View.OnClickListener) ProductionCommentsActivity.this);

        //creating a new instance of the calendar
        Calendar newCalendar = Calendar.getInstance();

        //creating a pop up date picker
        datePickerDialogFrom = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            //getting the chosen date and setting its format
            //and writing the chosen date in the edit text
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                editTextFrom.setText(simpleDateFormat.format(newDate.getTime()));
                fromDate = editTextFrom.getText().toString();
            }

        },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH),
                newCalendar.get(Calendar.DAY_OF_MONTH));

        datePickerDialogTo = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                editTextTo.setText(simpleDateFormat.format(newDate.getTime()));
                toDate = editTextTo.getText().toString();


            }

        },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH),
                newCalendar.get(Calendar.DAY_OF_MONTH));
    }

    // on click method to handle which edit text was touched
    // and show the appropriate pop up calendar
    @Override
    public void onClick(View view) {
        if(view == editTextFrom) {
            datePickerDialogFrom.show();
        } else if(view == editTextTo) {
            datePickerDialogTo.show();
        }
    }

    public void searchDates(View view){
        setDateTimeField();
        try {
           // getProductionComments(fromDate, toDate);
            getProductionComments(fromDate,toDate);

            adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results);
            listView.setAdapter(adapter);
        }catch(Exception ex){
            Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
        }


    }

    //get production comments data
    private void getProductionComments(String from, String to) {
        try {
            SQLiteDatabase db = dbHandler.getReadableDatabase();


            String query = "SELECT Date,Item,Comments FROM ProductionCommentData WHERE Date BETWEEN "+ from +
                    "AND "+ to+";";
            Cursor cursor = db.rawQuery(query,null);

            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    do {
                        String date = cursor.getString(cursor.getColumnIndex("Date"));
                        String item = cursor.getString(cursor.getColumnIndex("Item"));
                        String comments = cursor.getString(cursor.getColumnIndex("Comments"));

                        results.add("Date: " + date.substring(0, 9) + newline + newline  +
                                "Item: " + item + newline + newline  + "Comments: " + comments);
                    } while (cursor.moveToNext());
                }
            }
        } catch (SQLiteException se){
            Log.e(getClass().getSimpleName(), "Error retrieving data from database");
        }
    }

【问题讨论】:

  • I have dates stored in sqlite database file in this format M/d/yyyy 12:00:00 AM 但是你读过这个吗? SQLite TimeStrings

标签: android sqlite date date-range


【解决方案1】:

我可以建议的是:

  • 将表格导出为 CSV,
  • 将日期值更改为正确的SQLite TimeString
  • 删除原始表后重新导入 CSV。

然后,您可以运行如下查询:

SELECT * FROM Categories WHERE DateCreated BETWEEN '2012-03-11 00:00:00' AND '2015-05-12 23:59:59'

看这个answer,更好,因为它使用绑定参数

【讨论】:

    【解决方案2】:

    您应该将您的日期作为长值存储在数据库中。简单的new Date().getTime() 为您提供此值,new Date(long value) 将其返回。因此,您可以轻松地进行此类查询。

    【讨论】:

    • 我要告诉你一个好消息:不需要字符串比较。只需使用 SQLite 日期函数和/或 BETWEEN 子句。希望你学到了一些新东西。
    • @ViktorYakunin long 数据类型在 sqlite 中不存在! “长期价值”是什么意思?
    • @user3804193 我猜他的意思是整数。
    • @ViktorYakunin 我没有找到表示日期非常人类友好毫秒数。但是像这样的东西是:SELECT * FROM Categories WHERE DateCreated BETWEEN '2012-03-11 00:00:00' AND '2015-05-12 23:59:59'
    • @FrankN.Stein 同意这不友好,但如果您的列名类似于“timestamp”或“eventDate”,那么数字的含义就更清楚了。您的解决方案毫无疑问是有效的 - 将其发布为答案,我会投票支持它:)
    猜你喜欢
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多