好吧,che了所有关于Room db的帖子,没有人解决我的问题。 看来我的数据库从未创建。我只使用标准的代码示例。
public class LocalRepository {
private static AppDatabase database;
private static final Object LOCK = new Object();
private static Context ctx;
public synchronized static AppDatabase getDB(Context context) {
if (database == null) {
ctx = context;
synchronized (LOCK) {
if (database == null) {
database = Room.databaseBuilder(context,
AppDatabase.class, "goDetectDB")
.fallbackToDestructiveMigration()
.addCallback(dbCallback).build();
}
}
}
return database;
}
private static RoomDatabase.Callback dbCallback = new RoomDatabase.Callback() {
public void onCreate(SupportSQLiteDatabase db) {
Executors.newSingleThreadScheduledExecutor().execute(new Runnable() {
@Override
public void run() {
populateDB(ctx);
}
});
}
};
private static void populateDB(Context ctx){
getDB(ctx).discoveryDao().insertAll(DiscoveryContent.ITEMS.toArray(new Discovery[DiscoveryContent.ITEMS.size()]));
}
}
这是我的数据库的仓库。
@Database(entities = {Discovery.class}, version = 1, exportSchema = true)
public abstract class AppDatabase extends RoomDatabase {
public abstract DiscoveryDAO discoveryDao();
}
然后我将dao与所有getter和setter映射。
@Entity(tableName = "discovery") public class Discovery {
@PrimaryKey
private int id; ....
要使用的刀。
@Dao
public interface DiscoveryDAO {
@Insert
public void insert(Discovery... items);
@Update
public void update(Discovery... items);
@Delete
public void delete(Discovery item);
@Query("SELECT * FROM discovery")
List<Discovery> getAll();
@Query("SELECT * FROM discovery WHERE id IN (:listIds)")
List<Discovery> loadAllByIds(int[] listIds);
@Query("SELECT * FROM discovery WHERE categorie LIKE :categorie AND " +
"nom LIKE :nom LIMIT 1")
Discovery findByName(String categorie, String nom);
@Insert
void insertAll(Discovery... items);
@Query("SELECT * FROM discovery WHERE id = :id")
public Discovery getItemById(int id);
}
然后我用异步任务在一个片段中呼叫我的dao。
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
final TextView textView = root.findViewById(R.id.text_home);
// ajout db
new AsyncTask<Void, Void, Void>() {
String message = "none";
@Override
protected Void doInBackground(Void... voids) {
AppDatabase database = LocalRepository.getDB(getContext());
final DiscoveryDAO discoveryDAO = database.discoveryDao();
message = "failure";
if(discoveryDAO.getAll() != null && discoveryDAO.getAll().size() > 0){
message = "read data ";
message += discoveryDAO.getAll().size();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getContext(), message, duration);
toast.show();
}
}.execute();
homeViewModel.getText().observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
主要问题是,我从未收到“读取数据”消息,这始终是失败。看起来有些问题,但logcat或类似问题没有问题。
我在这里检查了有关Room db的一些帖子,主要错误是没有调用dao或类似启用填充方法的操作。这里不是这种情况,或者出了点问题。
你能帮我吗?
编辑:请注意,在create回调中使用dao的某些示例无法正常工作,因为您会收到异常消息或没有消息,例如我的情况,这很奇怪。 我的答案中的最终代码:)
答案 0 :(得分:1)
我相信您不能使用Dao ,因为这需要已构建数据库的实例。
在完成之前,回调将作为构建的一部分被调用。您需要使用SupportSQLiteDatabase来完成您的工作。
根据您的一些代码,考虑此精简/简化版本:-
@Entity
public class Discovery {
@PrimaryKey
Long id;
String name;
public Discovery(){}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Dao
public interface DiscoveryDao {
@Insert
long[] insertAll(Discovery... discoveries);
@Query("SELECT * FROM Discovery")
List<Discovery> getAll();
}
@Database(version = 1, entities = Discovery.class)
public abstract class AppDatabase extends RoomDatabase {
public abstract DiscoveryDao discoveryDao();
}
public class MainActivity extends AppCompatActivity {
AppDatabase mAppDB;
DiscoveryDao mDao;
String[] DiscoveryNamesToInsert = new String[]{"Found","Discovered","Located"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAppDB = Room.databaseBuilder(
this,
AppDatabase.class,
"goDetectDB"
)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.addCallback(dbCallback)
.build();
mDao = mAppDB.discoveryDao();
List<Discovery> discoveryList = mDao.getAll();
for (Discovery d: discoveryList) {
Log.d("DISCOVERYINFO","DiscoveryName is " + d.getName() + ", ID is " + d.getId());
}
}
private RoomDatabase.Callback dbCallback = new RoomDatabase.Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
long[] results = new long[DiscoveryNamesToInsert.length];
db.beginTransaction();
for (int i = 0; i < DiscoveryNamesToInsert.length; i++) {
results[i] = insert(db,DiscoveryNamesToInsert[i]);
}
db.setTransactionSuccessful();
db.endTransaction();
}
@Override
public void onOpen(@NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
}
@Override
public void onDestructiveMigration(@NonNull SupportSQLiteDatabase db) {
super.onDestructiveMigration(db);
}
private long insert(SupportSQLiteDatabase db,String name) {
ContentValues cv = new ContentValues();
cv.put("name",name);
return db.insert("Discovery", OnConflictStrategy.IGNORE,cv);
}
};
}
2019-10-05 14:11:37.135 D/DISCOVERYINFO: DiscoveryName is Found, ID is 1
2019-10-05 14:11:37.135 D/DISCOVERYINFO: DiscoveryName is Discovered, ID is 2
2019-10-05 14:11:37.135 D/DISCOVERYINFO: DiscoveryName is Located, ID is 3
答案 1 :(得分:0)
编辑:请注意,在创建回调中使用dao的某些示例无法正常工作,因为您会收到异常消息或没有消息,例如我的情况。
数据库对象中的最终代码(使用奶酪对象)。
@Entity(tableName = Cheese.TABLE_NAME)
public class Cheese {
/** The name of the Cheese table. */
public static final String TABLE_NAME = "cheeses";
/** The name of the ID column. */
public static final String COLUMN_ID = BaseColumns._ID;
/** The name of the name column. */
public static final String COLUMN_NAME = "name";
/** The unique ID of the cheese. */
@PrimaryKey(autoGenerate = true)
@ColumnInfo(index = true, name = COLUMN_ID)
public long id;
/** The name of the cheese. */
@ColumnInfo(name = COLUMN_NAME)
public String name;
/**
* Create a new {@link Cheese} from the specified {@link ContentValues}.
*
* @param values A {@link ContentValues} that at least contain {@link #COLUMN_NAME}.
* @return A newly created {@link Cheese} instance.
*/
public static Cheese fromContentValues(ContentValues values) {
final Cheese cheese = new Cheese();
if (values.containsKey(COLUMN_ID)) {
cheese.id = values.getAsLong(COLUMN_ID);
}
if (values.containsKey(COLUMN_NAME)) {
cheese.name = values.getAsString(COLUMN_NAME);
}
return cheese;
}
/** Dummy data. */
public static final String[] CHEESES = {
"Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
"Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale",
"Aisy Cendre", "Allgauer Emmentaler", "Alverca", "Ambert", "American Cheese",
"Ami du Chambertin", "Anejo Enchilado", "Anneau du Vic-Bilh", "Anthoriro", "Appenzell",
"Aragon", "Ardi Gasna", "Ardrahan", "Armenian String", "Aromes au Gene de Marc",
"Asadero", "Asiago", "Aubisque Pyrenees", "Autun", "Avaxtskyr", "Baby Swiss",
"Babybel", "Baguette Laonnaise", "Bakers", "Baladi", "Balaton", "Bandal", "Banon",
"Barry's Bay Cheddar", "Basing", "Basket Cheese", "Bath Cheese", "Bavarian Bergkase",
"Baylough", "Beaufort", "Beauvoorde", "Beenleigh Blue", "Beer Cheese", "Bel Paese",
"Bergader", "Bergere Bleue", "Berkswell", "Beyaz Peynir", "Bierkase", "Bishop Kennedy",
"Blarney", "Bleu d'Auvergne", "Bleu de Gex", "Bleu de Laqueuille",
"Bleu de Septmoncel", "Bleu Des Causses", "Blue", "Blue Castello", "Blue Rathgore",
"Blue Vein (Australian)", "Blue Vein Cheeses", "Bocconcini", "Bocconcini (Australian)",
"Boeren Leidenkaas", "Bonchester", "Bosworth", "Bougon", "Boule Du Roves",
"Boulette d'Avesnes", "Boursault", "Boursin", "Bouyssou", "Bra", "Braudostur",
"Breakfast Cheese", "Brebis du Lavort", "Brebis du Lochois", "Brebis du Puyfaucon",
"Bresse Bleu", "Brick", "Brie", "Brie de Meaux", "Brie de Melun", "Brillat-Savarin",
"Brin", "Brin d' Amour", "Brin d'Amour", "Brinza (Burduf Brinza)",
"Briquette de Brebis", "Briquette du Forez", "Broccio", "Broccio Demi-Affine",
"Brousse du Rove", "Bruder Basil", "Brusselae Kaas (Fromage de Bruxelles)", "Bryndza",
"Buchette d'Anjou", "Buffalo", "Burgos", "Butte", "Butterkase", "Button (Innes)",
"Buxton Blue", "Cabecou", "Caboc", "Cabrales", "Cachaille", "Caciocavallo", "Caciotta",
"Caerphilly", "Cairnsmore", "Calenzana", "Cambazola", "Camembert de Normandie",
"Canadian Cheddar", "Canestrato", "Cantal", "Caprice des Dieux", "Capricorn Goat",
"Capriole Banon", "Carre de l'Est", "Casciotta di Urbino", "Cashel Blue", "Castellano",
"Castelleno", "Castelmagno", "Castelo Branco", "Castigliano", "Cathelain",
"Celtic Promise", "Cendre d'Olivet", "Cerney", "Chabichou", "Chabichou du Poitou",
"Chabis de Gatine", "Chaource", "Charolais", "Chaumes", "Cheddar",
"Cheddar Clothbound", "Cheshire", "Chevres", "Chevrotin des Aravis", "Chontaleno",
"Civray", "Coeur de Camembert au Calvados", "Coeur de Chevre", "Colby", "Cold Pack",
"Comte", "Coolea", "Cooleney", "Coquetdale", "Corleggy", "Cornish Pepper",
"Cotherstone", "Cotija", "Cottage Cheese", "Cottage Cheese (Australian)",
"Cougar Gold", "Coulommiers", "Coverdale", "Crayeux de Roncq", "Cream Cheese",
"Cream Havarti", "Crema Agria", "Crema Mexicana", "Creme Fraiche", "Crescenza",
"Croghan", "Crottin de Chavignol", "Crottin du Chavignol", "Crowdie", "Crowley",
"Cuajada", "Curd", "Cure Nantais", "Curworthy", "Cwmtawe Pecorino",
"Cypress Grove Chevre", "Danablu (Danish Blue)", "Danbo", "Danish Fontina",
"Daralagjazsky", "Dauphin", "Delice des Fiouves", "Denhany Dorset Drum", "Derby",
"Dessertnyj Belyj", "Devon Blue", "Devon Garland", "Dolcelatte", "Doolin",
"Doppelrhamstufel", "Dorset Blue Vinney", "Double Gloucester", "Double Worcester",
"Dreux a la Feuille", "Dry Jack", "Duddleswell", "Dunbarra", "Dunlop", "Dunsyre Blue",
"Duroblando", "Durrus", "Dutch Mimolette (Commissiekaas)", "Edam", "Edelpilz",
"Emental Grand Cru", "Emlett", "Emmental", "Epoisses de Bourgogne", "Esbareich",
"Esrom", "Etorki", "Evansdale Farmhouse Brie", "Evora De L'Alentejo", "Exmoor Blue",
"Explorateur", "Feta", "Feta (Australian)", "Figue", "Filetta", "Fin-de-Siecle",
"Finlandia Swiss", "Finn", "Fiore Sardo", "Fleur du Maquis", "Flor de Guia",
"Flower Marie", "Folded", "Folded cheese with mint", "Fondant de Brebis",
"Fontainebleau", "Fontal", "Fontina Val d'Aosta", "Formaggio di capra", "Fougerus",
"Four Herb Gouda", "Fourme d' Ambert", "Fourme de Haute Loire", "Fourme de Montbrison",
"Fresh Jack", "Fresh Mozzarella", "Fresh Ricotta", "Fresh Truffles", "Fribourgeois",
"Friesekaas", "Friesian", "Friesla", "Frinault", "Fromage a Raclette", "Fromage Corse",
"Fromage de Montagne de Savoie", "Fromage Frais", "Fruit Cream Cheese",
"Frying Cheese", "Fynbo", "Gabriel", "Galette du Paludier", "Galette Lyonnaise",
"Galloway Goat's Milk Gems", "Gammelost", "Gaperon a l'Ail", "Garrotxa", "Gastanberra",
"Geitost", "Gippsland Blue", "Gjetost", "Gloucester", "Golden Cross", "Gorgonzola",
"Gornyaltajski", "Gospel Green", "Gouda", "Goutu", "Gowrie", "Grabetto", "Graddost",
"Grafton Village Cheddar", "Grana", "Grana Padano", "Grand Vatel",
"Grataron d' Areches", "Gratte-Paille", "Graviera", "Greuilh", "Greve",
"Gris de Lille", "Gruyere", "Gubbeen", "Guerbigny", "Halloumi",
"Halloumy (Australian)", "Haloumi-Style Cheese", "Harbourne Blue", "Havarti",
"Heidi Gruyere", "Hereford Hop", "Herrgardsost", "Herriot Farmhouse", "Herve",
"Hipi Iti", "Hubbardston Blue Cow", "Hushallsost", "Iberico", "Idaho Goatster",
"Idiazabal", "Il Boschetto al Tartufo", "Ile d'Yeu", "Isle of Mull", "Jarlsberg",
"Jermi Tortes", "Jibneh Arabieh", "Jindi Brie", "Jubilee Blue", "Juustoleipa",
"Kadchgall", "Kaseri", "Kashta", "Kefalotyri", "Kenafa", "Kernhem", "Kervella Affine",
"Kikorangi", "King Island Cape Wickham Brie", "King River Gold", "Klosterkaese",
"Knockalara", "Kugelkase", "L'Aveyronnais", "L'Ecir de l'Aubrac", "La Taupiniere",
"La Vache Qui Rit", "Laguiole", "Lairobell", "Lajta", "Lanark Blue", "Lancashire",
"Langres", "Lappi", "Laruns", "Lavistown", "Le Brin", "Le Fium Orbo", "Le Lacandou",
"Le Roule", "Leafield", "Lebbene", "Leerdammer", "Leicester", "Leyden", "Limburger",
"Lincolnshire Poacher", "Lingot Saint Bousquet d'Orb", "Liptauer", "Little Rydings",
"Livarot", "Llanboidy", "Llanglofan Farmhouse", "Loch Arthur Farmhouse",
"Loddiswell Avondale", "Longhorn", "Lou Palou", "Lou Pevre", "Lyonnais", "Maasdam",
"Macconais", "Mahoe Aged Gouda", "Mahon", "Malvern", "Mamirolle", "Manchego",
"Manouri", "Manur", "Marble Cheddar", "Marbled Cheeses", "Maredsous", "Margotin",
"Maribo", "Maroilles", "Mascares", "Mascarpone", "Mascarpone (Australian)",
"Mascarpone Torta", "Matocq", "Maytag Blue", "Meira", "Menallack Farmhouse",
"Menonita", "Meredith Blue", "Mesost", "Metton (Cancoillotte)", "Meyer Vintage Gouda",
"Mihalic Peynir", "Milleens", "Mimolette", "Mine-Gabhar", "Mini Baby Bells", "Mixte",
"Molbo", "Monastery Cheeses", "Mondseer", "Mont D'or Lyonnais", "Montasio",
"Monterey Jack", "Monterey Jack Dry", "Morbier", "Morbier Cru de Montagne",
"Mothais a la Feuille", "Mozzarella", "Mozzarella (Australian)",
"Mozzarella di Bufala", "Mozzarella Fresh, in water", "Mozzarella Rolls", "Munster",
"Murol", "Mycella", "Myzithra", "Naboulsi", "Nantais", "Neufchatel",
"Neufchatel (Australian)", "Niolo", "Nokkelost", "Northumberland", "Oaxaca",
"Olde York", "Olivet au Foin", "Olivet Bleu", "Olivet Cendre",
"Orkney Extra Mature Cheddar", "Orla", "Oschtjepka", "Ossau Fermier", "Ossau-Iraty",
"Oszczypek", "Oxford Blue", "P'tit Berrichon", "Palet de Babligny", "Paneer", "Panela",
"Pannerone", "Pant ys Gawn", "Parmesan (Parmigiano)", "Parmigiano Reggiano",
"Pas de l'Escalette", "Passendale", "Pasteurized Processed", "Pate de Fromage",
"Patefine Fort", "Pave d'Affinois", "Pave d'Auge", "Pave de Chirac", "Pave du Berry",
"Pecorino", "Pecorino in Walnut Leaves", "Pecorino Romano", "Peekskill Pyramid",
"Pelardon des Cevennes", "Pelardon des Corbieres", "Penamellera", "Penbryn",
"Pencarreg", "Perail de Brebis", "Petit Morin", "Petit Pardou", "Petit-Suisse",
"Picodon de Chevre", "Picos de Europa", "Piora", "Pithtviers au Foin",
"Plateau de Herve", "Plymouth Cheese", "Podhalanski", "Poivre d'Ane", "Polkolbin",
"Pont l'Eveque", "Port Nicholson", "Port-Salut", "Postel", "Pouligny-Saint-Pierre",
"Pourly", "Prastost", "Pressato", "Prince-Jean", "Processed Cheddar", "Provolone",
"Provolone (Australian)", "Pyengana Cheddar", "Pyramide", "Quark",
"Quark (Australian)", "Quartirolo Lombardo", "Quatre-Vents", "Quercy Petit",
"Queso Blanco", "Queso Blanco con Frutas --Pina y Mango", "Queso de Murcia",
"Queso del Montsec", "Queso del Tietar", "Queso Fresco", "Queso Fresco (Adobera)",
"Queso Iberico", "Queso Jalapeno", "Queso Majorero", "Queso Media Luna",
"Queso Para Frier", "Queso Quesadilla", "Rabacal", "Raclette", "Ragusano", "Raschera",
"Reblochon", "Red Leicester", "Regal de la Dombes", "Reggianito", "Remedou",
"Requeson", "Richelieu", "Ricotta", "Ricotta (Australian)", "Ricotta Salata", "Ridder",
"Rigotte", "Rocamadour", "Rollot", "Romano", "Romans Part Dieu", "Roncal", "Roquefort",
"Roule", "Rouleau De Beaulieu", "Royalp Tilsit", "Rubens", "Rustinu", "Saaland Pfarr",
"Saanenkaese", "Saga", "Sage Derby", "Sainte Maure", "Saint-Marcellin",
"Saint-Nectaire", "Saint-Paulin", "Salers", "Samso", "San Simon", "Sancerre",
"Sap Sago", "Sardo", "Sardo Egyptian", "Sbrinz", "Scamorza", "Schabzieger", "Schloss",
"Selles sur Cher", "Selva", "Serat", "Seriously Strong Cheddar", "Serra da Estrela",
"Sharpam", "Shelburne Cheddar", "Shropshire Blue", "Siraz", "Sirene", "Smoked Gouda",
"Somerset Brie", "Sonoma Jack", "Sottocenare al Tartufo", "Soumaintrain",
"Sourire Lozerien", "Spenwood", "Sraffordshire Organic", "St. Agur Blue Cheese",
"Stilton", "Stinking Bishop", "String", "Sussex Slipcote", "Sveciaost", "Swaledale",
"Sweet Style Swiss", "Swiss", "Syrian (Armenian String)", "Tala", "Taleggio", "Tamie",
"Tasmania Highland Chevre Log", "Taupiniere", "Teifi", "Telemea", "Testouri",
"Tete de Moine", "Tetilla", "Texas Goat Cheese", "Tibet", "Tillamook Cheddar",
"Tilsit", "Timboon Brie", "Toma", "Tomme Brulee", "Tomme d'Abondance",
"Tomme de Chevre", "Tomme de Romans", "Tomme de Savoie", "Tomme des Chouans", "Tommes",
"Torta del Casar", "Toscanello", "Touree de L'Aubier", "Tourmalet",
"Trappe (Veritable)", "Trois Cornes De Vendee", "Tronchon", "Trou du Cru", "Truffe",
"Tupi", "Turunmaa", "Tymsboro", "Tyn Grug", "Tyning", "Ubriaco", "Ulloa",
"Vacherin-Fribourgeois", "Valencay", "Vasterbottenost", "Venaco", "Vendomois",
"Vieux Corse", "Vignotte", "Vulscombe", "Waimata Farmhouse Blue",
"Washed Rind Cheese (Australian)", "Waterloo", "Weichkaese", "Wellington",
"Wensleydale", "White Stilton", "Whitestone Farmhouse", "Wigmore", "Woodside Cabecou",
"Xanadu", "Xynotyro", "Yarg Cornish", "Yarra Valley Pyramid", "Yorkshire Blue",
"Zamorano", "Zanetti Grana Padano", "Zanetti Parmigiano Reggiano"
};
}
奶酪的DAO。
/**
* Data access object for Cheese.
*/
@Dao
public interface CheeseDao {
/**
* Counts the number of cheeses in the table.
*
* @return The number of cheeses.
*/
@Query("SELECT COUNT(*) FROM " + Cheese.TABLE_NAME)
int count();
/**
* Inserts a cheese into the table.
*
* @param cheese A new cheese.
* @return The row ID of the newly inserted cheese.
*/
@Insert
long insert(Cheese cheese);
/**
* Inserts multiple cheeses into the database
*
* @param cheeses An array of new cheeses.
* @return The row IDs of the newly inserted cheeses.
*/
@Insert
long[] insertAll(Cheese[] cheeses);
/**
* Select all cheeses.
*
* @return A {@link Cursor} of all the cheeses in the table.
*/
@Query("SELECT * FROM " + Cheese.TABLE_NAME)
List<Cheese> selectAll();
/**
* Select a cheese by the ID.
*
* @param id The row ID.
* @return A {@link Cursor} of the selected cheese.
*/
@Query("SELECT * FROM " + Cheese.TABLE_NAME + " WHERE " + Cheese.COLUMN_ID + " = :id")
Cursor selectById(long id);
/**
* Delete a cheese by the ID.
*
* @param id The row ID.
* @return A number of cheeses deleted. This should always be {@code 1}.
*/
@Query("DELETE FROM " + Cheese.TABLE_NAME + " WHERE " + Cheese.COLUMN_ID + " = :id")
int deleteById(long id);
/**
* Update the cheese. The cheese is identified by the row ID.
*
* @param cheese The cheese to update.
* @return A number of cheeses updated. This should always be {@code 1}.
*/
@Update
int update(Cheese cheese);
}
还有填充数据的数据库。
@Database(entities = {Discovery.class, Director.class, Cheese.class}, version = 1, exportSchema = true)
public abstract class AppDatabase extends RoomDatabase {
public abstract DiscoveryDAO discoveryDao();
public abstract DirectorDao directorDao();
public abstract CheeseDao cheese();
/** The only instance */
private static AppDatabase sInstance;
/**
* Gets the singleton instance of SampleDatabase.
*
* @param context The context.
* @return The singleton instance of SampleDatabase.
*/
public static synchronized AppDatabase getInstance(final Context context) {
if (sInstance == null) {
sInstance = Room
.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "goDetectDB")
.allowMainThreadQueries()
.addCallback(new RoomDatabase.Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
db.beginTransaction();
Cheese cheese = new Cheese();
for (int i = 0; i < Cheese.CHEESES.length; i++) {
cheese.name = Cheese.CHEESES[i];
ContentValues cv = new ContentValues();
cv.put(Cheese.COLUMN_NAME, cheese.name);
long id = db.insert(Cheese.TABLE_NAME, OnConflictStrategy.IGNORE, cv);
cheese.id = id;
Log.d("DISCOVERYINFO","DiscoveryName cheese is " + cheese.name + ", ID is " + cheese.id);
}
db.setTransactionSuccessful();
db.endTransaction();
}
@Override
public void onOpen(@NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
}
@Override
public void onDestructiveMigration(@NonNull SupportSQLiteDatabase db) {
super.onDestructiveMigration(db);
}
})
.build();
}
return sInstance;
}
}
然后您可以在主活动\ o /中调用dao。谢谢您的帮助!
database = AppDatabase.getInstance(getApplicationContext()).cheese().selectAll();