【问题标题】:Export room database to json file将房间数据库导出到 json 文件
【发布时间】:2018-06-18 18:41:13
【问题描述】:

是否可以将所有房间数据库以及所有表格、条目导出到 json 文件?我看到一些example 用 SQLite 完成了,但是 Room 数据库呢?

【问题讨论】:

    标签: android sqlite android-sqlite android-room


    【解决方案1】:

    您可以根据需要将 Room 实体对象传递给 JSON 生成器。如果您希望检索一堆实体并将它们写入 JSON,您可以这样做。

    换句话说,您可以使用 JSON 生成器将来自 DogCat 对象的数据写入 JSON。 DogCat 对象来自哪里——Room、Retrofit、Realm 等——并不重要。

    实现导出的范围(“所有房间数据库以及所有表格、条目”)由您决定。

    【讨论】:

    • 还有外键和连接表的多对多数据库怎么样?
    • @kosas:在DogCat POJO 级别,在JSON 级别,没有外键和连接表之类的东西。如何选择在 JSON 中建模取决于您自己,而 Room 在该建模方法中并没有太多参与。
    • 感谢您的帮助!
    【解决方案2】:

    如果您了解如何将表从 Room Database 导出到 JSON,将会很有帮助。让我们看看怎么做。

    第 1 步:为房间数据库创建 模型

        @Entity(tableName = "students")
        public class Student{
            @PrimaryKey(autoGenerate = true)
            private int id;
            @ColumnInfo(name = "std_name")
            private String name;
            public Student(int id, String name){
                this.id = id;
                this.name = name;
            }
            @Ignore
            public Student(String name){
                this.name = name;
            }
            public int getId() {
                return id;
            }
            public String getName() {
                return name;
            }
         }
    

    第 2 步:为房间数据库创建 数据访问对象 (DAO)

    @Dao
    public interface StudentDAO {
        @Query("select * from students")
        List<Student> getStudents();
    
        @Insert
        public void insert(Student student);
    
        // Other CRUD methods
        // ..........
    }
    

    第 3 步:现在创建 房间数据库

    @Database(entities = { Student.class }, version = 1, exportSchema = false)
    public abstract class StudentDatabase extends RoomDatabase {
        private static final String DB_NAME ="StudentDb";
        private static StudentDatabase stdInstance;
        public abstract StudentDAO stdDAO();    
    
        public synchronized static StudentDatabase getInstance(final Context context) {
            if (stdInstance == null) {
                stdInstance = Room.databaseBuilder(context, StudentDatabase.class, DB_NAME)
                                            .allowMainThreadQueries().build();
            }
            return stdInstance;
        }
    }
    

    第 4 步:将房间数据库中的 学生表导出为 JSON

    // Create reference variables in your Activity
    private List<Student> stdList;
    private StudentDatabase stdDatabase;
    
    private void exportJSON(){
        Completable.fromAction(new Action() {
            @Override
            public void run() throws Exception {
               // stdDatabase.stdDAO().getStudents();
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CompletableObserver() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }
    
                    @Override
                    public void onComplete() {
                        stdList = stdDatabase.stdDAO().getStudents();
                        Gson gson = new Gson();
                        Type type = new TypeToken<List<Student>>(){}.getType();
                        String stdJson = gson.toJson(stdList, type);
    
                        // Call function to write file to external directory
                        writeToStorage(getApplicationContext(), "StudnetJson", stdJson)
                    }
    
                    @Override
                    public void onError(Throwable e) {
                        // Show error message
                    }
                });
        }
    
    //Create a Method in your Activity
    public void writeToStorage(Context mContext, String fileName, String jsonContent){      
        File file = new File(mContext.getFilesDir(),"exportStudentJson");
        if(!file.exists()){
            file.mkdir();
        }
        try{
            File mFile = new File(file, fileName);
            FileWriter writer = new FileWriter(mFile);
            writer.append(jsonContent);
            writer.flush();
            writer.close();
    
        }catch (Exception e){
            e.printStackTrace();
    
        }
    }
    

    就算不懂也请让我写cmets。

    注意:以后我会为这个问题创建一个 GitHub 项目。谢谢

    【讨论】:

      猜你喜欢
      • 2018-12-05
      • 2023-01-13
      • 2022-08-02
      • 1970-01-01
      • 2021-12-18
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多