我想列出從另一個類創建的數據庫中的項目。 但我不知道如何在不創建對象的情況下訪問它。下面的代碼:訪問從其他類創建的數據庫(Android/JAVA)
AddItemActivity:
public class AddItemActivity extends AppCompatActivity {
MyDBHandler dbHandler;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
dbHandler = new MyDBHandler(this, null, null, 1);
}
public void insertButtonClick(View view) {
Item item = new Item(...);
dbHandler.addItems(item);
}
MyDBHandler:
Public class MyDBHandler extends SQLiteOpenHelper{
...
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
public void addItems(Item item) {
ContentValues values = new ContentValues();
SQLiteDatabase db = getWritableDatabase();
// INSERT ITEMS
values.put(COLUMN_ITEM, item.getName());
...
db.close();
}
public String printDatabase() {
String dbString = "";
SQLiteDatabase db = getReadableDatabase();
String printQuery = "SELECT * FROM " + TABLE_NAME + " WHERE 1";
Cursor cursor = db.rawQuery(printQuery, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
dbString += "Item: " + cursor.getString(cursor.getColumnIndex(COLUMN_ITEM)) +
" \t Amount: " + cursor.getString(cursor.getColumnIndex(COLUMN_AMOUNT)) +
" \t Price: " + cursor.getString(cursor.getColumnIndex(COLUMN_PRICE));
cursor.moveToNext();
}
cursor.close();
db.close();
return dbString;
}
現在我想列出在另一個活動中的所有項目,但我不知道如何訪問dbHandler創建於AddItemActivity
public class ListItemActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_base);
}
public void printDatabase() {
String dbString = ****.printDataBase();
databaseTextView.setText(dbString);
}
THX!現在作品:D – Aye