Как заставить типоконвертеры работать со списком пользовательских классов? - PullRequest
0 голосов
/ 04 февраля 2019

У меня есть объект User, в котором хранится список пользовательских объектов Notifications.Хотя я использовал TypeConverters, я все еще получаю сообщение об ошибке для запроса.

Мой пользовательский объект (пропущен метод получения и установки)

@Entity(tableName = "User")
public class User {
    @PrimaryKey(autoGenerate = true)
    private int userId;

    @ColumnInfo(name = "username")
    private String username;

    @ColumnInfo(name = "number")
    private String number;

    @TypeConverters(Converters.class)
    private List<Notifications> notifications;

    public User(String username, String number, List<Notifications> notifications) {
        this.username = username;
        this.number = number;
        this.notifications = notifications;
    }


}

интерфейс userDao

@Dao
public interface UserDao {
    @Query("SELECT * FROM User")
    List<User> getAll();

    @Query("SELECT COUNT(*) from User")
    int countUsers();

    @Query("SELECT notifications from User where userId LIKE :userId")
    List<Notifications> getNotifications(int userId);

    @Insert
    void insert(User... users);

    @Delete
    void delete(User... users);

    @Update
    void update(User... users);

} 

Класс конвертера

public class Converters {
    @TypeConverter
    public static List<Notifications> fromString(String value) {
        Type listType = new TypeToken<List<Notifications>>() {}.getType();
        List<Notifications> notifications = new Gson().fromJson(value,listType);
        return notifications;
    }

    @TypeConverter
    public static String listToString(List<Notifications> list) {
        Gson gson = new Gson();
        return gson.toJson(list);
    }
} 

Класс уведомлений (пропущены геттеры и сеттеры)

public class Notifications {
    private String app;
    private String type;
    private String time;


    public Notifications(String app, String type, String time) {
        this.app = app;
        this.type = type;
        this.time = time;
    }
} 

Класс AppDatabase

@Database(entities = {User.class}, version = 1)
@TypeConverters({Converters.class})
public abstract class AppDatabase extends RoomDatabase {

    private static AppDatabase INSTANCE;

    public abstract UserDao userDao();

    public static AppDatabase getAppDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE =
                    Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "user-database")
                            .allowMainThreadQueries()
                            .build();
        }
        return INSTANCE;
    }


    public static void destroyInstance() {
        INSTANCE = null;
    }
} 

Я получаю ошибку

error: Not sure how to convert a Cursor to this method's return type

и

The query returns some columns [notifications] which are not use by com.example.ark.example.database.Notifications. You can use @ColumnInfo annotation on the fields to specify the mapping. com.example.ark.example.database.Notifications has some fields [app, type, time] which are not returned by the query. If they are not supposed to be read from the result, you can mark them with @Ignore annotation. You can suppress this warning by annotating the method with @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH). Columns returned by the query: notifications. Fields in com.example.ark.example.database.Notifications: app, type, time.

Не уверен, что я ошибаюсь, поскольку преобразователи типов выглядят хорошо для меня.

Ответы [ 3 ]

0 голосов
/ 05 февраля 2019

Попробуйте добавить аннотации @ColumnInfo и @SerializedName ко всем полям, как показано ниже.

@TypeConverters(Converters.class)
@ColumnInfo(name = "notifications")
@SerializedName("notifications")
private List<Notifications> notifications;

Также добавьте для

Уведомления Модель:

@SerializedName("app")
private String app;
@SerializedName("type")
private String type;
@SerializedName("time")
private String time;
0 голосов
/ 05 февраля 2019

пожалуйста, добавьте @ColumnInfo(name = "........") к List<Notifications> notifications записи

0 голосов
/ 05 февраля 2019

Попробуйте добавить @ColumnInfo(name = "notifications") ниже @TypeConverters(Converters.class)

...