SDcard上的android SQLite数据库,无需使用SQLiteOpenHelper即可插入数据和获取结果

时间:2014-01-07 11:33:44

标签: android sqlite android-sqlite

以下是在SD卡上创建数据库的代码 我没有使用默认的SQLiteOpenHelper,这里使用了构造函数。在Main类中将使用handler类进行实例化。

public class DatabaseHandler {
     private static final String TAG     = "DatabaseHelper";
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "contactsManagerDB";
    private static final String TABLE_CONTACTS = "contacts";
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";
    public SQLiteDatabase      database;
   File file_str      = Environment.getExternalStorageDirectory();
   String DATABASE_FILE_PATH = file_str.toString();

   public DatabaseHandler(Context context) {
         try
            {
             Log.i(TAG, "donedddddd");
            database = SQLiteDatabase.openOrCreateDatabase(DATABASE_FILE_PATH
                    + File.separator + DATABASE_NAME, null);
            }
            catch (SQLiteException ex)
            {
                String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                        + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                        + KEY_PH_NO + " TEXT" + ")";
                database.execSQL(CREATE_CONTACTS_TABLE);

            }
            finally
            {
           database.close();
            }

    }
    // Adding new contact
    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
    }

    private SQLiteDatabase getWritableDatabase() {
         database = SQLiteDatabase.openDatabase(DATABASE_FILE_PATH
                    + File.separator + DATABASE_NAME, null,
                    SQLiteDatabase.OPEN_READONLY);
            return database;
    }

    private SQLiteDatabase getReadableDatabase() {
          database = SQLiteDatabase.openDatabase(DATABASE_FILE_PATH
                    + File.separator + DATABASE_NAME, null,
                    SQLiteDatabase.OPEN_READWRITE);
            return database;
    }

    // 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();
    }
}
//////////

编辑:感谢 @Vigbyor 提供的广泛帮助。我在测试后意识到这是有问题的代码。当我尝试添加时,它会崩溃。任何解决方案?

     // Adding new contact
       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
    }

编辑编号2: 最后我能够插入。但是获取结果是个问题。这是在DatabaseHandler类中获取联系计数的方法。

    // 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();
    }

如果我尝试DatabaseHandler db = new DatabaseHandler(this);

,请在MainClass中

//insertion code here, which works//

db.getContactsCount(); //this line fails, even If I catch it in integer variable.

感谢。

修改编号3 : 最后,在 user2953017 vigbyor 的建议之后,我能够插入和获取结果。以下是修改后的代码:

    public int getContactsCount() {
        int count=0;
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        while (cursor.moveToNext()) {
           count++;
         }
        cursor.close();
        db.close();
        // return count
        return count;
    }

,在MainClass中,

    DatabaseHandler db = new DatabaseHandler(this);
    Integer c;

        db.addContact(new Contact("Sandeep", "1234567"));
        db.addContact(new Contact("Pareek", "12345678"));

        Log.e(TAG, "ADD SUCCESS");   

    c= db.getContactsCount();
 //Toast just to make sure the number of records are returned.
    Toast.makeText(getApplicationContext(), c.toString() , Toast.LENGTH_SHORT).show();

希望它也可以帮助别人。 感谢

2 个答案:

答案 0 :(得分:1)

为什么要在catch块中插入数据?

    catch (SQLiteException ex)
        {
            String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                    + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                    + KEY_PH_NO + " TEXT" + ")";
            database.execSQL(CREATE_CONTACTS_TABLE);

        }

您应该在下面的try块中编写这些代码,

    try
    {
        Log.i(TAG, "donedddddd");
        database = SQLiteDatabase.openOrCreateDatabase(DATABASE_FILE_PATH
                + File.separator + DATABASE_NAME, null);
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_PH_NO + " TEXT" + ")";
        database.execSQL(CREATE_CONTACTS_TABLE);
    }
    catch (SQLiteException ex)
    {
        ex.printStackTrace();
    }
    finally
    {
        database.close();
    }

答案 1 :(得分:1)

我认为应用程序正在崩溃,因为db值为null。  试试这段代码

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

        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
    }
else 
Log.d("db is null");
}

或者你可以将上面的代码放在try catch块

编辑: 你正在调用cursor.close() 这意味着它关闭Cursor,释放所有资源并使其完全无效。 一旦在方法中检索了该特定对象的值,就可以关闭光标。

将您的代码更改为:

public int getContactsCount() {
        int count;
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        if (cursor != null) {
            count = cursor.getCount();
            cursor.close();
         }

        // return count
        return count();
    }