gpt4 book ai didi

android - 房间数据库无法预填充数据并且未创建数据库文件

转载 作者:行者123 更新时间:2023-11-29 22:42:47 26 4
gpt4 key购买 nike

我已经在 Application 中实现了 Room 数据库。我想在应用程序首次打开时预填充数据。 Entity 类看起来像

@Entity(tableName = NameConstants.TABLE_NAME)
public class Name {

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

@PrimaryKey(autoGenerate = true)
private int id;

@ColumnInfo(name = NameConstants.COL_NAME)
private String Name;

@ColumnInfo(name= NameConstants.COL_PHONE)
private String Phone;

@ColumnInfo(name = NameConstants.COL_CITY)
private String City;

public Name(){

}

public Name(String name, String phone, String city) {
Name = name;
Phone = phone;
City = city;
}

public String getName() {
return Name;
}

public void setName(String name) {
Name = name;
}

public String getPhone() {
return Phone;
}

public void setPhone(String phone) {
Phone = phone;
}

public String getCity() {
return City;
}

public void setCity(String city) {
City = city;
}
}

DAO 实现是

@Dao
public interface NameDAO {

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAll(Name... names);

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(Name name);

@Delete
void delete(Name name);
}

Database 类似乎是这样的,其中数据是从一个 Raw 文件中读取的

@Database(entities = {Name.class},version = 1,exportSchema = false)
public abstract class NameDatabase extends RoomDatabase {

public abstract NameDAO nameDAO();

private static volatile NameDatabase dInstance=null;

static synchronized NameDatabase getInstance(final Context context){
if(dInstance==null){
synchronized (NameDatabase.class){
if(dInstance==null){
dInstance= Room.databaseBuilder(context.getApplicationContext(),NameDatabase.class,"appdatabase")
.allowMainThreadQueries()
.addCallback(new Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
fillWithDemoData(context);
}

}
).build();
}
}
}
return dInstance;
}

@WorkerThread
private static void fillWithDemoData(Context context){
NameDAO dao=getInstance(context).nameDAO();
JSONArray emoji = loadJsonArray(context);
try {
for (int i = 0; i < emoji.length(); i++) {
JSONObject item = emoji.getJSONObject(i);
dao.insert(new Name(item.getString("name"),
item.getString("phone"),
item.getString("city")));
}
} catch (JSONException exception) {
exception.printStackTrace();
}
}
private static JSONArray loadJsonArray(Context context) {
StringBuilder builder = new StringBuilder();
InputStream in = context.getResources().openRawResource(R.raw.namesdata);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
JSONObject json = new JSONObject(builder.toString());
return json.getJSONArray("names");

} catch (IOException | JSONException exception) {
exception.printStackTrace();
}

return null;
}
}

Repository 类是公开的

class DataRepository {

private NameDAO nDao;

public DataRepository(Application application) {
NameDatabase database = NameDatabase.getInstance(application);
nDao = database.nameDAO();
}
}

当安装应用程序并打开应用程序时,应用程序运行正常,没有崩溃,但没有创建数据库文件,也没有数据插入数据库。代码中还缺少什么或有什么错误吗?

最佳答案

When app is install and open app works fine, no crash but no Database files are created and no data is inserted in database.

如果您没有遇到崩溃,那么我相信您没有对数据库执行任何其他操作。只需构建它并获取实例。

在您尝试访问数据库之前,不会创建数据库。您需要尝试对数据库做一些事情。

然而!!!!!

然后您将得到一个 java.lang.IllegalStateException: getDatabase called recursively FATAL 异常。

基本上,通过访问数据库,您然后尝试打开它,因为数据库不存在,调用 onCreate 回调,然后通过插入访问它的尝试将尝试打开数据库,因此递归。

简而言之,您只能通过传递给 onCreate 的 SupportSQLiteDatabase 访问数据库。

你可以使用:-

public static void fillWithDemoData(Context context, SupportSQLiteDatabase sdb){

ContentValues cv = new ContentValues(); //<<<<<<<<<< ADDED


JSONArray emoji = loadJsonArray(context);
try {
for (int i = 0; i < emoji.length(); i++) {
JSONObject item = emoji.getJSONObject(i);

//<<<<<<<<<< CANNOT USE ROOM here >>>>>>>>>
//dao.insert(new Name(item.getString("name"),
// item.getString("phone"),
// item.getString("city")));


cv.clear();
cv.put(NameConstants.COL_NAME,item.getString(NameConstants.COL_NAME));
cv.put(NameConstants.COL_CITY,item.getString(NameConstants.COL_CITY));
cv.put(NameConstants.COL_PHONE,item.getString(NameConstants.COL_PHONE));
sdb.insert(NameConstants.TABLE_NAME, OnConflictStrategy.IGNORE,cv);
}
} catch (JSONException exception) {
exception.printStackTrace();
}

}

但是您需要尝试访问 ROOM,例如所以在你的 Activity 或同等 Activity 中你可以使用:-

    ndb = NameDatabase.getInstance(this); //<<<<<<<<<< ROOM databse not yet created (opened)
ndb.getOpenHelper(); //<<<<<<<<<< FORCE OPEN and thus create (or just access the db via a Dao call)

示例/演示/测试

因为我无权访问您的 JSON 文件,所以我使用 :-

测试了上面的内容
@WorkerThread
public static void fillWithDemoData(Context context, SupportSQLiteDatabase sdb){

ContentValues cv = new ContentValues(); //<<<<<<<<<< ADDED
cv.clear();
cv.put(NameConstants.COL_NAME,"Fred");
cv.put(NameConstants.COL_CITY,"London");
cv.put(NameConstants.COL_PHONE,"0000000000");
sdb.insert(NameConstants.TABLE_NAME, OnConflictStrategy.IGNORE,cv);

/*
JSONArray emoji = loadJsonArray(context);
try {
for (int i = 0; i < emoji.length(); i++) {
JSONObject item = emoji.getJSONObject(i);

//<<<<<<<<<< CANNOT USE ROOM here >>>>>>>>>
//dao.insert(new Name(item.getString("name"),
// item.getString("phone"),
// item.getString("city")));


cv.clear();
cv.put(NameConstants.COL_NAME,item.getString(NameConstants.COL_NAME));
cv.put(NameConstants.COL_CITY,item.getString(NameConstants.COL_CITY));
cv.put(NameConstants.COL_PHONE,item.getString(NameConstants.COL_PHONE));
sdb.insert(NameConstants.TABLE_NAME, OnConflictStrategy.IGNORE,cv);
}
} catch (JSONException exception) {
exception.printStackTrace();
}
*/
}
  • 同时注释掉loadJsonArray中的代码

使用的 Activity 是:-

public class MainActivity extends AppCompatActivity {

NameDatabase ndb;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ndb = NameDatabase.getInstance(this);
ndb.getOpenHelper(); //<<<<<<<<<< FORCE OPEN and thus create (not needed as db accessed below)

//This would also do the same, this used to test the data//
List<Name> nameList = ndb.nameDAO().getALl();
for (Name n: nameList) {
logName(n);
}
}

private void logName(Name n) {
Log.d("NAMEINFO","Name is " + n.getName() + "\n\tCity is " + n.getCity() + "\n\tPhone is " + n.getPhone() + "ID is " + n.getId());
}
}

结果

安装后首次运行:-

2019-11-14 08:22:08.483 D/ONCREATE: onCreate has been called
2019-11-14 08:22:08.492 D/NAMEINFO: Name is Fred
City is London
Phone is 0000000000ID is 1
  • 没有将日志添加到 onCreate,因此它显示它已被调用。

第二次运行:-

2019-11-14 08:23:22.532 D/NAMEINFO: Name is Fred
City is London
Phone is 0000000000ID is 1

关于android - 房间数据库无法预填充数据并且未创建数据库文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58837724/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com