Answer the question
In order to leave comments, you need to log in
How to populate SQLite with data after creating a database and parsing a file in Dagger?
There is a json
file, when you first start the application, you need to create a database, parse the file and write data to the database, the creation of the database lies in Dagger2. Accordingly, this must be done in a new thread. It’s as if I understand what and how, but the fact that the database is created in the Dagger module makes the
module difficult:
@Module
public class MainAppModule {
private Context context;
public MainAppModule(Context context) {
this.context = context;
}
@Singleton
@Provides //scope is not necessary for parameters stored within the module
public Context context() {
return context;
}
@Singleton
@Provides
public RoomDB provideRoomDB(Context context) {
RoomDatabase.Builder<RoomDB> roomDatabase = Room.databaseBuilder(context, RoomDB.class, RoomDB.NAME_DB).addCallback(new RoomDatabase.Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
//тут нужно заполнять бд
}
});
return roomDatabase.build();
}
@Singleton
@Provides
public CityUserDAO provideCustomMenuDAO(RoomDB roomDB) {
return roomDB.getCityUserDAO();
}
}
public class TempParserJson {
private static final String TAG = "TempParserJson";
@Inject
Context context;
public TempParserJson() {
MainApp.app().appComponent().inject(this);
String strJson;
AssetManager assetManager = context.getAssets();
try {
InputStream stream = assetManager.open("city.json");
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
strJson = new String(buffer, "UTF-8");
JsonParser parser = new JsonParser();
Object obj = parser.parse(strJson);
JsonArray jsonArray = (JsonArray) obj;
Log.d(TAG, "TempParserJson: " + jsonArray.get(0));
TempWeather tempWeather = new Gson().fromJson(jsonArray.get(0), TempWeather.class);
Log.d(TAG, "TempParserJson: " + tempWeather.getId());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Answer the question
In order to leave comments, you need to log in
Obviously, either you need to get the database asynchronously and do parsing and lay it down immediately on another thread, or give an empty database synchronously and postpone parsing to another thread.
Anyway, I consider, it is necessary to abstract from a specific DB. In the application, no one should know about it except the repository.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question