嵌入式sqlite数据库不起作用

时间:2016-07-07 10:54:28

标签: android sqlite

我尝试在我的应用程序中使用嵌入式sqlite数据库...但我终于看不到任何吐司...起初我在dbbrowser中创建了一个数据库然后将其粘贴到我项目中的assets文件夹中,最后我尝试了这些代码。我的问题在哪里?

mainactivity

           import android.database.Cursor;



public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    DBAdapter db = new DBAdapter(this);
    try {
        String desthpath = "/data/data/" + getPackageName() + "/databases2";
        File f = new File(desthpath);
        if (!f.exists()) {
            f.mkdir();
            f.createNewFile();
            CopyDB(getBaseContext().getAssets().open("mydb"),
                    new FileOutputStream(desthpath + "/MyDB"));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    db.open();
    Cursor c = db.getAllContacts();
    if (c.moveToFirst()) {
        do {
            DisplayContact(c);
        } while (c.moveToNext());
    }
    db.close();
}
public void CopyDB(InputStream inputStream,OutputStream outputStream)throws IOException{
    byte[] buffer = new byte[1024];
    int lenght;
    while ((lenght=inputStream.read(buffer))>0){
        outputStream.write(buffer,0,lenght);
    }
    inputStream.close();
    outputStream.close();
}

public void DisplayContact(Cursor c)
{
    Toast.makeText(this,"id:"+c.getString(0)+ "\n"+
    "Name: "+c.getString(1)+"\n"+
    "Email: "+c.getString(2),Toast.LENGTH_LONG).show();
}

}

将对DBAdapter

     public class DBAdapter {

private static final String TAG = "DBAdapter"; //used for logging database version changes

// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
public static final String KEY_TAG="DBAdapter";

public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_EMAIL};

// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_TASK = 1;
public static final int COL_DATE = 2;

// DataBase info:
public static final String DATABASE_NAME = "MyDB";
public static final String DATABASE_TABLE = "contacts";
public static final int DATABASE_VERSION = 1; // The version number must be incremented each time a change to DB structure occurs.

//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
        "CREATE TABLE " + DATABASE_TABLE
                + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + KEY_NAME + " TEXT NOT NULL, "
                + KEY_EMAIL + " TEXT NOT NULL"
                + ");";

private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;


public DBAdapter(Context ctx) {
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
}

private static class DatabaseHelper extends SQLiteOpenHelper
{
    DatabaseHelper(Context context)
    {
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
    }
    public void onCreate(SQLiteDatabase db)
    {
        try {
            db.execSQL(DATABASE_CREATE_SQL);
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
    public void onUpgrade(SQLiteDatabase db,int oldversion,int newversion)
    {
        Log.w(TAG,"upgradingdatabasefrom"+oldversion+"to"+newversion+"which will destroy all old data.");
        db.execSQL("DROP TABLE IF EXISTS contacts");
        onCreate(db);
    }
}

// Open the database connection.
public DBAdapter open() throws SQLException {
    db = DBHelper.getWritableDatabase();
    return this;
}

// Close the database connection.
public void close() {
    DBHelper.close();
}

// Add a new set of values to be inserted into the database.
public long insertContact(String name, String email) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_NAME, name);
    initialValues.put(KEY_EMAIL, email);

    // Insert the data into the database.
    return db.insert(DATABASE_TABLE, null, initialValues);
}

// Delete a row from the database, by rowId (primary key)
public boolean deleteContact(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    return db.delete(DATABASE_TABLE, where, null) != 0;
}

public void deleteAll() {
    Cursor c = getAllContacts();
    long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
    if (c.moveToFirst()) {
        do {
            deleteContact(c.getLong((int) rowId));
        } while (c.moveToNext());
    }
    c.close();
}

// Return all data in the database.
public Cursor getAllContacts() {
    String where = null;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Get a specific row (by rowId)
public Cursor getCotact(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS,
            where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Change an existing row to be equal to new data.
public boolean updateContact(long rowId, String name, String email) {
    String where = KEY_ROWID + "=" + rowId;
    ContentValues newValues = new ContentValues();
    newValues.put(KEY_NAME, name);
    newValues.put(KEY_EMAIL, email);
    // Insert it into the database.
    return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}

}

0 个答案:

没有答案