无法在android中使用Sqlite保存和检索String数据

时间:2014-05-09 10:18:49

标签: android sqlite

现在我试图在android中使用Sqlite数据库保存并检索一个字符串数据(比如String str =“xyz data”)。 但我在我的logcat上得到这些东西。 有人可以帮我解决这个问题吗? 请找我的参考资料

感谢您宝贵的时间!..

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

1 个答案:

答案 0 :(得分:0)

在尝试使用Cursor访问列值之前,您需要将get...()移至有效行。

添加

if (cursor.moveToFirst()) {
    // cursor.get...()
}

在光标访问周围。

如果您想要所有结果行,也可以添加一个循环:

if (cursor.moveToFirst()) {
    do {
        // cursor.get...()
    } while (cursor.moveToNext());
}

此特定堆栈跟踪来自getAllContacts(),但getContact()有类似问题 - 您有moveToFirst()但无法检查是否成功。

另外getContactsCount()也被打破了。您不应该访问已关闭游标的计数。