LeTadas
LeTadas

Reputation: 3556

Export room database to json file

Is it possible to export all room database with all tables, entries to json file? I saw some example done with SQLite, but how about Room database?

Upvotes: 2

Views: 4696

Answers (2)

Subarata Talukder
Subarata Talukder

Reputation: 6311

It will be helpful if you understand how to export a table from Room Database to JSON. Let see how to do it.

Step 1: Create Model for Room Database

    @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;
        }
     }

Step 2: Create Data Access Object(DAO) for Room Database

@Dao
public interface StudentDAO {
    @Query("select * from students")
    List<Student> getStudents();

    @Insert
    public void insert(Student student);

    // Other CRUD methods
    // ..........
}

Step 3: Now Create Room Database

@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;
    }
}

Step 4: Export Student table from Room Database as 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();

    }
}

Even if you don't understand please let me write comments.

Note: In future I'll create a GitHub project for this issue. Thanks

Upvotes: 3

CommonsWare
CommonsWare

Reputation: 1006944

You can pass your Room entity objects to a JSON generator as you see fit. If you wish to retrieve a bunch of the entities and write them to JSON, you can do so.

In other words, you can write the data from Dog and Cat objects to JSON, using a JSON generator. Where the Dog and Cat objects come from — Room, Retrofit, Realm, etc. — does not matter.

Implementing the scope of the export ("all room database with all tables, entries") is up to you.

Upvotes: 5

Related Questions