如何使用ContentValues.put()插入对象列表?

时间:2017-09-11 18:58:08

标签: android sqlite android-sqlite content-values

我正在尝试将数据插入到SQLite数据库中,为此我编写了一个简单的方法来插入我从API获得的数据,如下所示:

public static ContentValues gameInfoToContentValues(@NonNull GameInfoList game) {

        ContentValues values = new ContentValues();

        values.put(GameEntry.COLUMN_GAME_ID, game.id());
        values.put(GameEntry.COLUMN_GAME_ALIASES, game.aliases());
        values.put(GameEntry.COLUMN_GAME_API_DETAIL_URL, game.api_detail_url());
        values.put(GameEntry.COLUMN_GAME_DATE_ADDED, game.date_added());
        values.put(GameEntry.COLUMN_GAME_DATE_LAST_UPDATED, game.date_last_updated());
        values.put(GameEntry.COLUMN_GAME_SMALL_IMAGE, game.image().small_url());
        values.put(GameEntry.COLUMN_GAME_MEDIUM_IMAGE, game.image().medium_url());
        values.put(GameEntry.COLUMN_GAME_HD_IMAGE, game.image().super_url());
        values.put(GameEntry.COLUMN_GAME_NAME, game.name());
        values.put(GameEntry.COLUMN_GAME_ORIGINAL_RELEASE_DATE, game.original_game_rating());

        return values;
    }

我到了最后一次

game.original_game_rating();

正确对齐,因为它是一个对象列表。

我的对象类名为" GameInfoList"作为方法中的参数传递的内容如下所示:

public abstract long id();

@Nullable
public abstract String aliases();

@Nullable
public abstract String api_detail_url();

@Nullable
public abstract String date_added();

@Nullable
public abstract String date_last_updated();

@Nullable
public abstract GameImages image();

@Nullable
public abstract String name();

@Nullable
public abstract List<GameRatings> original_game_rating();

修改

我也有GameRatings对象,如下所示:

@Nullable
public abstract String api_detail_url();

public abstract long id();

@Nullable
public abstract String name();

现在我想在表格中插入一个游戏评级名称,我修改了代码,如下所示:

public static ContentValues gameInfoToContentValues(@NonNull GameInfoList game) {

    ContentValues values = new ContentValues();

    if(game.original_game_rating() != null) {
        for(GameRatings ratings : game.original_game_rating()) {
            values.put(GameEntry.COLUMN_GAME_ID, game.id());
            values.put(GameEntry.COLUMN_GAME_ALIASES, game.aliases());
            values.put(GameEntry.COLUMN_GAME_API_DETAIL_URL, game.api_detail_url());
            values.put(GameEntry.COLUMN_GAME_DATE_ADDED, game.date_added());
            values.put(GameEntry.COLUMN_GAME_DATE_LAST_UPDATED, game.date_last_updated());
            values.put(GameEntry.COLUMN_GAME_SMALL_IMAGE, game.image().small_url());
            values.put(GameEntry.COLUMN_GAME_MEDIUM_IMAGE, game.image().medium_url());
            values.put(GameEntry.COLUMN_GAME_HD_IMAGE, game.image().super_url());
            values.put(GameEntry.COLUMN_GAME_NAME, game.name());
            values.put(GameEntry.COLUMN_GAME_ORIGINAL_GAME_RATING, ratings.name());
        }
    }

    return values;
}

这是对的吗?

1 个答案:

答案 0 :(得分:2)

您有两种选择:

  1. 摆脱该列并让GameRatings通过与您的GameEntry(?)表格的1:N关系进入单独的表格

  2. List<GameRatings>转换为文本(例如,JSON)并将文本存储在

  3. 列中