-1

Ok so I'm looking to incorporate a database into an app project I'm working on but have run into a problem here...below is code for a database handler class (taken from androidhive.info I believe)

package apps.sqlitetest;

import java.util.ArrayList;
import java.util.List;

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 
{

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "contactsManager";

// Contacts table name
private static final String TABLE_CONTACTS = "contacts";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";

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

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

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

    // Create tables again
    onCreate(db);
}

/**
 * All CRUD(Create, Read, Update, Delete) Operations
 */

// Adding new contact
public void addContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName()); // Contact Name
    values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone

    // Inserting Row
    db.insert(TABLE_CONTACTS, null, values);
    db.close(); // Closing database connection
}

// Getting single contact
public Contact getContact(int id) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
            KEY_NAME, KEY_PH_NO }, 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), cursor.getString(2));
    // return contact
    return contact;
}

// Getting All Contacts
public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setID(Integer.parseInt(cursor.getString(0)));
            contact.setName(cursor.getString(1));
            contact.setPhoneNumber(cursor.getString(2));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }

    // return contact list
    return contactList;
}

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

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName());
    values.put(KEY_PH_NO, contact.getPhoneNumber());

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

// Deleting single contact
public void deleteContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
    db.close();
}

// Getting contacts Count
public int getContactsCount() 
{
    String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    // return count
    return cursor.getCount();
}

}

So, this seems all well and good alright...but here's the thing, I have this line in my MainActivity trying to test reading the database by displaying the (single) result in a TextView:

text.setText(db.getContact(9100).toString()) ;

I guess I'll mention now the Contact class is something from the androidhive tutorial too; just a simple representation of a contact (like an entry in a phone) with fields id (int), name, phone number (both string). There IS a previous set of lines in the main activity inserting some contacts and one does have the id "9100". However, this setText line seems to be throwing the following errors onto logcat, and consequently stopping the app when it runs:

02-22 15:04:37.682: E/AndroidRuntime(847): java.lang.RuntimeException: 
Unable to start activity 
ComponentInfo{apps.sqlitetest/apps.sqlitetest.MainActivity}:    
android.database.CursorIndexOutOfBoundsException: 
Index 0 requested, with a size of 0
02-22 15:04:37.682: E/AndroidRuntime(847):  
at apps.sqlitetest.DatabaseHandler.getContact(DatabaseHandler.java:81)
02-22 15:04:37.682: E/AndroidRuntime(847):  
at apps.sqlitetest.MainActivity.onCreate(MainActivity.java:40)

Can someone tell me what's wrong here please?

1 Answer 1

1

One problem is in getContact(). You are never checking that the cursor actually contains any data. Firstly, remove this check:

if (cursor != null)

as cursor can never be null.

Instead, check for the result returned from cursor.moveToFirst(). A false value means the cursor was empty. Only if you get a true result there should you proceed to read the fields from the cursor and build the Contact.

Once you correctly handle this situation where the cursor contains no data, then you can set about finding out why your query isn't retrieving the expected data.

4
  • I'm kind of new this so could you explain a little more? I more or less understand what you're saying but like, what should I be doing if cursor.moveToFirst() returns false? Feb 22, 2013 at 15:52
  • Return null from getContact(), or throw an exception, for example. Whatever you think is the best way of handling that situation. Feb 22, 2013 at 15:53
  • The code for getContact is now as shown here: pastebin.com/hdngaugb Is this what you meant? The exception that can be thrown by it is caught in my MainActivity in which case an error message is supposed to be fed to the TextView...but it's not working at all; When I click the "Run" icon up top in eclipse, it launches the emulator and all that but it eventually says in the android console "Failed to install AppSQLiteTest.apk on device 'emulator-5554!" Feb 23, 2013 at 14:12
  • @GrahamBorland, if you're around still, I've been tryng a little more to fix this but stil no luck...it seems now even tho android console says installation failed it actually didn't but nonetheless all that's happening now is the app shows the error i set it to display if it can't retrieve the contact. Feb 24, 2013 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.