Q:

Unable to save and retrieve String data using Sqlite in android

Right now im trying to save and retrieve one string data(say String str="xyz data") using Sqlite database in android.
But im getting these things on my logcat.
Can anyone please help me to overcome this issue?
Please find my sources for reference
thanks for your precious time!..
MainActivity.java
public class MainActivity extends Activity 
{
String str_value = "Sample string data";
Contact cn;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    DatabaseHandler db = new DatabaseHandler(this);

    // Inserting Contacts
    Log.d("Insert: ", "Inserting ..");
    db.addContact(new Contact( str_value));
    db.addContact(new Contact( "Manickaprabhakaran"));

    // Reading all contacts
    db.getAllContacts();

    String str_log = cn.getName();

    // Writing Contacts to log
    System.out.println(">>--  SAVED Data  :    "+str_log);
    }
}

DatabaseHandler.java
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_NAME = "contacts";

// Contacts Table Columns names
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);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " 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_NAME);

    // Create tables again
    onCreate(db);
}

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

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

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

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

    Cursor cursor = db.query(TABLE_NAME, 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 void getAllContacts()
{

    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_NAME;

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

    Contact contact = new Contact();
    contact.setID(Integer.parseInt(cursor.getString(0)));
    contact.setName(cursor.getString(1));

    // Adding contact to list
    add(contact);

}

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

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

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

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

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

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

Contact.java
public class Contact {

//private variables
int _id;
String _name;

// Empty constructor
public Contact(){

}
// constructor
public Contact(int id, String name){
    this._id = id;
    this._name = name;
}

// constructor
public Contact(String name){
    this._name = name;
}
// getting ID
public int getID(){
    return this._id;
}

// setting id
public void setID(int id){
    this._id = id;
}

// getting name
public String getName(){
    return this._name;
}

// setting name
public void setName(String name){
    this._name = name;
}}

LOGCATE
05-09 09:42:05.750: E/AndroidRuntime(666): FATAL EXCEPTION: main
05-09 09:42:05.750: E/AndroidRuntime(666): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sqlite_sample/com.example.sqlite_sample.MainActivity}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 10
05-09 09:42:05.750: E/AndroidRuntime(666):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
05-09 09:42:05.750: E/AndroidRuntime(666):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
05-09 09:42:05.750: E/AndroidRuntime(666):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
05-09 09:42:05.750: E/AndroidRuntime(666):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
05-09 09:42:05.750: E/AndroidRuntime(666):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-09 09:42:05.750: E/AndroidRuntime(666):  at android.os.Looper.loop(Looper.java:123)
05-09 09:42:05.750: E/AndroidRuntime(666):  at android.app.ActivityThread.main(ActivityThread.java:3683)
05-09 09:42:05.750: E/AndroidRuntime(666):  at java.lang.reflect.Method.invokeNative(Native Method)
05-09 09:42:05.750: E/AndroidRuntime(666):  at java.lang.reflect.Method.invoke(Method.java:507)
05-09 09:42:05.750: E/AndroidRuntime(666):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)  
05-09 09:42:05.750: E/AndroidRuntime(666):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-09 09:42:05.750: E/AndroidRuntime(666):  at dalvik.system.NativeStart.main(Native Method)
05-09 09:42:05.750: E/AndroidRuntime(666): Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 10
05-09 09:42:05.750: E/AndroidRuntime(666):  at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
05-09 09:42:05.750: E/AndroidRuntime(666):  at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
05-09 09:42:05.750: E/AndroidRuntime(666):  at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
05-09 09:42:05.750: E/AndroidRuntime(666):  at com.example.sqlite_sample.DatabaseHandler.getAllContacts(DatabaseHandler.java:95)
05-09 09:42:05.750: E/AndroidRuntime(666):  at com.example.sqlite_sample.MainActivity.onCreate(MainActivity.java:35)
05-09 09:42:05.750: E/AndroidRuntime(666):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-09 09:42:05.750: E/AndroidRuntime(666):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
05-09 09:42:05.750: E/AndroidRuntime(666):  ... 11 more

A:

You need to move the Cursor to a valid row before trying to access column values with get...().
Add
if (cursor.moveToFirst()) {
    // cursor.get...()
}

around the cursor access.
In case you want all result rows, add a loop, too:
if (cursor.moveToFirst()) {
    do {
        // cursor.get...()
    } while (cursor.moveToNext());
}

This specific stacktrace is from getAllContacts() but getContact() has similar problem - you have moveToFirst() but fail to check if it succeeds.
Additionally getContactsCount() is broken, too. You shouldn't access the count of a closed cursor.

