SQLite游标条件出错 - 需要第二双眼睛

时间:2014-04-20 21:55:38

标签: java android sqlite

所以这就是我的问题 - 代码应该很简单,但这不起作用,我不知道为什么。下面是我为一个名为NEXT的按钮设置的代码,用户在填写日期和锻炼信息后点击该按钮。如果输入的日期已经在数据库中,则应使用Toast消息提醒他们,并且不允许进入下一页。但是,正在发生的事情是输入日期的数据库查询显然是失败的,或者条件设置是以某种方式阻止执行,或者我对Cursor做错了。 / p>

请注意主要问题中的条件 - if(date_matches.getCount()&gt; 0&amp;&amp; date_matches!= null){//告诉用户输入新日期或修改MODIFY标签中的旧日期} < / p>

我现在已经使用&amp;&amp;&amp;,这导致现有和未来的日期都进入下一个活动。如果我将其更改为||,则执行永远不会到达&#39; else&#39;阻止,即使数据库中尚不存在日期。

在这个讨厌的小问题上,任何正确方向的推动都会受到赞赏!

button.setOnClickListener(new View.OnClickListener() {
         @Override
            public void onClick(View arg0){

            String date = date_entry.getText().toString();              
            String exercise = date_entry.getText().toString(); //this is not required -- can modify day to add later

            //If date field left empty but NEXT button pressed, issue a toast message telling user to enter one
            if (date == null || date.length() == 0){
                CharSequence message = "No date given. Please enter one before pressing NEXT";
                Toast toast = Toast.makeText(context, message, duration);
                toast.show();}

            //If exercise left empty but NEXT button pressed, will just fill exercise with 'none', which can be 
            //later modified if user exercises after they create their new date
            if (exercise == null || exercise.length() == 0){
                exercise = "None";
            }

            String query = "SELECT * FROM food_entries WHERE date = "+date;

            Cursor date_matches = mDbHelper.getData(query);

            //There is a problem with this conditional -- even when there should be no matching rows for
            //a new date, this is coming up with some sort of result and letting it pass
            if (date_matches.getCount() > 0 && date_matches != null){
                //Matching date in food_entries, meaning foods for that date already inputted
                CharSequence message = "Information for "+date+" already exists. Add/modify in MODIFY tab";
                Toast toast = Toast.makeText(context, message, duration);}

            else{
                //No matching dates; can add new date
                Intent intent = new Intent(context, AddFoodsActivity.class);
                intent.putExtra("date_key", date);
                intent.putExtra("exercise_key", exercise);
                    startActivity(intent);} 

            }});        

2 个答案:

答案 0 :(得分:2)

您的getData功能可能会调用queryrawQuery。 这些函数永远不会返回null;当他们什么都没找到时,他们返回一个零项目的有效游标。 (只有内容提供商可能会返回null而不是空游标。)

只需删除date_matches != null支票。

答案 1 :(得分:1)

Ack,所以这是修复:

String query = "SELECT * FROM food_entries WHERE date = '"+date+"'";

是的,没错。所有这些悲伤都是因为缺少一套单引号。当我试图用cursor.getString(cursor.getColumnIndex("date"))查看光标结果时,让我感到惊讶的是什么。有一个错误说找到了一个int但是需要一个字符串 - 然后我知道查询本身有些问题,而不是我的条件。