0

Hi everybody i want to save a class variable in database but i recieve this error :

 error: Cannot figure out how to save this field into database. You can consider adding a type 
 converter for it.

this is my table :

     @Entity(tableName = "tbl_projects")
     public class Room_Database_Project {
     @PrimaryKey(autoGenerate = true)
     private int id;
     private Project project;  

Project variable can't make... what can i do?

  • You need to create a type converter class like this: https://developer.android.com/training/data-storage/room/referencing-data or this: https://stackoverflow.com/questions/61963144/how-to-make-a-typeconverter-in-room-from-a-custom-list – Mayur Gajra May 12 '21 at 06:48
  • if the solution helped please upvote – Dinkar Kumar May 14 '21 at 03:07

1 Answers1

2

You can do this using kind of two ways. See what fits better to your situation.

TypeConverter: With type converters defined, you can use your custom type in your entities and DAOs just as you would use primitive types

Example:

public static class Converters {
    @TypeConverter
    public Date fromTimestamp(Long value) {
        return value == null ? null : new Date(value);
    }

    @TypeConverter
    public Long dateToTimestamp(Date date) {
        if (date == null) {
            return null;
        } else {
            return date.getTime();
        }
    }

    @TypeConverter
    public Project fromString(String value) {
        return new Gson().fromJson(value, Project.class);
    }

    @TypeConverter
    public String fromProject(Project project) {
        return new Gson().toJson(project);
    }
}

Then you can add @TypeConverters(Converters.class) annotation on your abstract RoomDatabase class.

Embedded: This annotation indicates that the instance of the class being embedded is stored as an intrinsic part of the class where the annotation is being used.

Example:

public class Project {
     double projectLatitude;
     double ProjectLongitude;
    String projectName;
   }




@Entity(tableName = "tbl_projects")
     public class Room_Database_Project {
     @PrimaryKey(autoGenerate = true)
     private int id;
     @Embedded
     private Project project;  
    }

https://developer.android.com/training/data-storage/room/referencing-data

Dinkar Kumar
  • 2,175
  • 2
  • 12
  • 22
  • what are we supposed to do here i need to return an object list because the internal structures are multiple; https://stackoverflow.com/questions/70815892/what-should-we-do-for-nested-objects-in-room/ https://github.com/theoyuncu8/roomdb –  Jan 23 '22 at 09:49