sledge-hamster
sledge-hamster

Reputation: 77

Android SQLite rawQuery giving trouble

There's this method which i've created to know if a contact exists in my Sqlite database.

public Cursor doesContactExist(String name) 
{
    return db.rawQuery("select * from contacts where name = ?; ", new String[] {name});
}

But whenever it is called from another activity it crashes only at this point....

if(db.doesContactExist(name)==null){   <== crashes here
                     try {                       
                        db.open();      
                        db.insertContact(name,cNumber);//name and number are Strings
                        listItems.add(name);           //a List View array
                        db.close();
                        adapter.notifyDataSetChanged(); //adapter for ListView

                            } 
                     catch (Exception e) {
                    //some code                                               }
                    }

According to me the rawQuery is having some troulble, especially the sql String in it.

Any help please?

Upvotes: 1

Views: 656

Answers (2)

Ajay
Ajay

Reputation: 1189

I think it might help you..

db.open();
if(db.doesContactExist(name)==null)
{
     try
     {
          // Your Code Here..
     }
}

and in Database Class

public Cursor doesContactExist(String name) 
{
    return db.rawQuery("SELECT * FROM contacts WHERE name=?", new String[ {name.toString()});
}

use db.open() method before using any database function because it will open your connection with database.. and at last don't forget to close database like db.close() and if you are using Cursor anywhere in code please close this also. it not generates any error but it gives you warnings. :)

Upvotes: 1

nano_nano
nano_nano

Reputation: 12523

you try to make a select before your database is open:

if(db.doesContactExist(name)==null){   <== it is closed here
                 try {                       
                    db.open();      <== open the db here

change it to:

db.open();
if(db.doesContactExist(name)==null){
          try {                       

Upvotes: 1

Related Questions