从一个活动打开另一个活动中的数据库



我正在尝试重用我在主要活动中创建的数据库。但是我无法让第二个活动引用数据库。

主要活动代码:

public class StoreAccount extends AppCompatActivity {
static final int READ_BLOCK_SIZE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_store_account);

    final AccountDB db1 = new AccountDB(this);

    Button buttonSave = (Button) findViewById(R.id.buttonSave);
    buttonSave.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            EditText account = (EditText) findViewById(R.id.editTextAccount);
            String acc = account.getText().toString();
            EditText username = (EditText) findViewById(R.id.editTextUsername);
            String user = username.getText().toString();
            EditText password = (EditText) findViewById(R.id.editTextPassword);
            String pass = password.getText().toString();
            EditText days = (EditText) findViewById(R.id.editTextDays);
            int expiry = Integer.parseInt(days.getText().toString());
            /**
             * CRUD Operations
             * */
            // add Accounts
            db1.addAccount(new Account(acc, user, pass, expiry));
            //db.addBook(new Book("Android Programming: The Big Nerd Ranch Guide", "Bill Phillips and Brian Hardy"));
            //db.addBook(new Book("Learn Android App Development", "Wallace Jackson"));

            // get all accounts
            List<Account> list1 = db1.getAllAccounts();
            // delete one account
            db1.deleteAccount(list1.get(0));
            // get all accounts
            db1.getAllAccounts();
        }
    });
}

第二项活动

public class AccountView extends StoreAccount {
//@Override
protected void onCreate(Bundle savedInstanceState, SQLiteDatabase db) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_account_view);
    Context context = getApplicationContext();
    context.getDatabasePath(AccountDb.AccountDb);
    //AccountDB db1 = new AccountDB(this);
    List<Account> list1 = db1.getAllAccounts();
}

}

数据库代码

public class AccountDB extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "AccountDB";
public AccountDB(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
    // SQL statement to create account table
    String CREATE_ACCOUNT_TABLE = "CREATE TABLE accounts ( " +
            "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
            "account TEXT, " +
            "username TEXT, " +
            "password TEXT, " +
            "expiry INTEGER )";
    // create accounts table
    db.execSQL(CREATE_ACCOUNT_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older accounts table if existed
    db.execSQL("DROP TABLE IF EXISTS accounts");
    // create fresh accounts table
    this.onCreate(db);
}
//---------------------------------------------------------------------
/**
 * CRUD operations (create "add", read "get", update, delete) account + get all accounts + delete all accounts
 */
// Accounts table name
private static final String TABLE_ACCOUNTS = "accounts";
// Accounts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_ACCOUNT = "account";
private static final String KEY_USERNAME = "username";
private static final String KEY_PASSWORD = "password";
private static final String KEY_DAYS = "expiry";
private static final String[] COLUMNS = {KEY_ID, KEY_ACCOUNT, KEY_USERNAME, KEY_PASSWORD, KEY_DAYS};
public void addAccount(Account account) {
    Log.d("addAccount", account.toString());
    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();
    // 2. create ContentValues to add key "column"/value
    ContentValues values = new ContentValues();
    values.put(KEY_ACCOUNT, account.getAccount()); // get account
    values.put(KEY_USERNAME, account.getUsername()); // get username
    values.put(KEY_PASSWORD, account.getPassword()); // get password
    values.put(KEY_DAYS, account.getDays()); // get expiry
    // 3. insert
    db.insert(TABLE_ACCOUNTS, // table
            null, //nullColumnHack
            values); // key/value -> keys = column names/ values = column values
    // 4. close
    db.close();
}
public Account getAccount(int id) {
    // 1. get reference to readable DB
    SQLiteDatabase db = this.getReadableDatabase();
    // 2. build query
    Cursor cursor =
            db.query(TABLE_ACCOUNTS, // a. table
                    COLUMNS, // b. column names
                    " id = ?", // c. selections
                    new String[]{String.valueOf(id)}, // d. selections args
                    null, // e. group by
                    null, // f. having
                    null, // g. order by
                    null); // h. limit
    // 3. if we got results get the first one
    if (cursor != null)
        cursor.moveToFirst();
    // 4. build account object
    Account account = new Account();
    account.setId(Integer.parseInt(cursor.getString(0)));
    account.setAccount(cursor.getString(1));
    account.setUsername(cursor.getString(2));
    account.setPassword(cursor.getString(3));
    account.setDays(Integer.parseInt(cursor.getString(4)));
    Log.d("getAccount(" + id + ")", account.toString());
    // 5. return account
    return account;
}
// Get All Accounts
public List<Account> getAllAccounts() {
    List<Account> accounts = new LinkedList<Account>();
    // 1. build the query
    String query = "SELECT  * FROM " + TABLE_ACCOUNTS;
    // 2. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);
    // 3. go over each row, build account and add it to list
    Account account = null;
    if (cursor.moveToFirst()) {
        do {
            account = new Account();
            account.setId(Integer.parseInt(cursor.getString(0)));
            account.setAccount(cursor.getString(1));
            //account.setUsername(cursor.getString(2));
            //account.setPassword(cursor.getString(3));
            //account.setDays(Integer.parseInt(cursor.getString(4)));
            // Add account to accounts
            accounts.add(account);
        } while (cursor.moveToNext());
    }
    Log.d("getAllAccounts()", accounts.toString());
    // return accounts
    return accounts;
}
// Updating single account
public int updateAccount(Account account) {
    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();
    // 2. create ContentValues to add key "column"/value
    ContentValues values = new ContentValues();
    values.put("account", account.getAccount()); // get account
    values.put("username", account.getUsername()); // get username
    values.put("password", account.getPassword()); // get password
    values.put("expiry", account.getDays()); // get expiry
    // 3. updating row
    int i = db.update(TABLE_ACCOUNTS, //table
            values, // column/value
            KEY_ID + " = ?", // selections
            new String[]{String.valueOf(account.getId())}); //selection args
    // 4. close
    db.close();
    return i;
}
// Deleting single account
public void deleteAccount(Account account) {
    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();
    // 2. delete
    db.delete(TABLE_ACCOUNTS,
            KEY_ID + " = ?",
            new String[]{String.valueOf(account.getId())});
    // 3. close
    db.close();
    Log.d("deleteAccount", account.toString());
}
public int getRowCount() {
    String countQuery = "SELECT  * FROM " + TABLE_ACCOUNTS;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int cnt = cursor.getCount();
    cursor.close();
    return cnt;

 }

}

在 AccountView 活动中创建数据库类的对象并访问数据库类方法

AccountDB accountdb = new AccountDB(this);
List<Account> list1 = accountdb.getAllAccounts();

最新更新