如何将JsonArray值插入Room数据库?

时间:2018-01-23 12:36:22

标签: android android-room

我有一个Json数组,其中包含城市名称(" pa")和城市名称(" tan")。我想将它们添加到Room数据库,但应用程序崩溃没有任何错误,可能是我的插入操作,打开阻止UI线程

这是我如何遍历Json数组并获取值

try {
            JSONArray citiesJsonArray = new JSONArray(unzippedCitiesString);
            Cities cities = new Cities();


            for (int i = 0; i < citiesJsonArray.length(); i++) {

                JSONObject data = citiesJsonArray.getJSONObject(i);
                String cityNumber = data.getString("pa");
                String cityName = data.getString("tar");

                cities.setCityName(cityName);
                cities.setCityCode(cityNumber);

            }


        } catch (JSONException e) {
            e.printStackTrace();
        }

我将它们设置为城市实体

@Entity(tableName = "cities")
public class Cities {


    @PrimaryKey(autoGenerate = true)
    private int uid;

    @ColumnInfo(name = "_cityname")
    private String cityName;

    @ColumnInfo(name = "_citycode")
    private String cityCode;

.... getters and setters here

这是我的CitiesDao

@Dao
public interface CitiesDao {

    @Query("SELECT * FROM cities")
    List<Banks> getAllCities();

    @Query("SELECT * FROM cities where _cityname LIKE  :cityName")
    Banks findByName(String cityName);

    @Query("SELECT * FROM cities where _citycode LIKE  :cityCode")
    Banks findByCode(int cityCode);

    @Query("SELECT COUNT(*) from cities")
    int countCities();

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void addCity(Cities cities);


    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertAll(Cities... cities);

    @Delete
    void delete(Cities cities);

    @Update
    void update(Cities cities);


}

这是我的数据库

@Database(entities = {Cities.class}, version = 1)
public abstract class MyDatabase extends RoomDatabase {

    public static final String DB_NAME = "DB";

    public abstract CitiesDao citiesDao();


}

最后我在MainActivity的onCreate方法中初始化我的数据库

database = Room.databaseBuilder(this, MyDatabase.class, MyDatabase.DB_NAME).build();

我尝试在try catch块中填充数据库,如:

database.CitiesDao()。在设置值后插入所有(城市),但它在没有任何日志的情况下崩溃。无法找到解决方案

编辑: 我通过在我的基础应用程序初始化db解决了异常,但我不知道如何使用json数组数据填充db

1 个答案:

答案 0 :(得分:0)

试试我有同样的问题

初始化数据库后使用AsyncTaskRxJava后台操作或新线程以避免UI阻止

  database = Room.databaseBuilder(this, MyDatabase.class, 
 MyDatabase.DB_NAME).build();

new DatabaseAsync().execute();



private class DatabaseAsync extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //Perform pre-adding operation here.
        }

        @Override
        protected Void doInBackground(Void... voids) {
            database.CitiesDao().insertAll(cities) 
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            //To after addition operation here.
        }
    }

}