在数据库中搜索特定记录时出错

时间:2016-12-30 07:22:59

标签: android android-sqlite android-cursor

我有一个名为TABLE_CONTENTS的SQLite数据库表,由contact类型的对象组成。每个contact都有2个变量:int idString name。我想在SQLite数据库表中搜索特定的id。为此,我在类isPresent()中创建了DatabaseHandler方法。它需要int个ID并搜索表中是否存在id的对象,并相应地返回truefalse

以下代码创建了一个数据库,并使用id s 12向其中添加了2个对象。然后,它会尝试使用id=3搜索isPresent()。这应该返回false,导致文本id 3 is absent显示。但是,它返回true,显示的文字为id 3 is present

此代码有什么问题? isPresent()的正确代码是什么?

MainActivity.java

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity
{

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

    DatabaseHandler db = new DatabaseHandler(this);

    // Inserting Contacts
    db.addContact(new Contact(1, "one"));
    db.addContact(new Contact(2, "two"));



    TextView text=(TextView) findViewById(R.id.text);
    text.setText(db.isPresent(3) ? "id 3 is present" : "id 3 is absent");


}

DatabaseHandler.java

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHandler extends SQLiteOpenHelper
{
 private static final int DATABASE_VERSION=1;
 private static final String DATABASE_NAME="contactsManager";
 private static final String TABLE_CONTACTS="contacts";
 private static final String KEY_ID="id";
 private static final String KEY_NAME="name";

public DatabaseHandler(Context context)
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);}

@Override
public void onCreate(SQLiteDatabase db)
{
    String CREATE_CONTACTS_TABLE="CREATE TABLE "+TABLE_CONTACTS+"("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_NAME+" TEXT "+")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
 db.execSQL("DROP TABLE IF EXISTS"+TABLE_CONTACTS);
    onCreate(db);
}

void addContact(Contact contact)
{
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.name);
    values.put(KEY_ID, contact.id);

    // Inserting Row
    db.insert(TABLE_CONTACTS, null, values);
    //2nd argument is String containing nullColumnHack
    db.close(); // Closing database connection
}


// not working properly..always returning true
public boolean isPresent(int id)
{
    SQLiteDatabase sqldb = this.getReadableDatabase();
    String Query = "Select * from " + TABLE_CONTACTS ;
    Cursor cursor = sqldb.rawQuery(Query, null);
    cursor.moveToLast(); //if you not place this cursor.getCount() always give same integer (1) or current position of cursor.

    if(cursor.getCount()<=0)
    {
        return false;
    }

    return true;
}




Contact getContact(int id)
{
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                    KEY_NAME}, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1));
    // return contact
    return contact;
}

public int updateContact(Contact contact)
{
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.name);


    // updating row
    return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.id) });
}


}






}

联系课程

public class Contact
{
public String name;
public int id;

Contact(int id, String name)
{
    this.id=id;
    this.name=name;
}


}

2 个答案:

答案 0 :(得分:0)

尝试,

我看到你没有添加任何条件来选择特定的行。所以,就像所有未被选中的一样。因此, cursor.getCount()&lt; = 0 始终为 false ,因为您已添加了2条记录。

在isPresent(int id)方法中,如下所示更新查询并尝试一次,

String Query = "Select * from " + TABLE_CONTACTS + " WHERE " + KEY_ID + "='"+ id + "'";

答案 1 :(得分:0)

未在查询中添加任何WHERE子句以根据ID 搜索记录,因此它始终从数据库中选择所有将始终返回计数> 0的行,这就是你的代码无效的原因。

您必须修改您的Select查询以在其中包含WHERE子句。

.state('app.settings', {
        url: '/settings',
        cache: false,
        views: {
            'viewContent': {
                templateUrl: 'templates/views/settings.html',
                controller: 'SettingsController'
            }
        }
    })