Ajji
Ajji

Reputation: 3086

Android Realm occupying a lot of data space

I am currently working on a CRM Android app using Realm for saving records. I am syncing the data from the web server. There 10 Tables.There was this one table that had around 450 pages, such that each page contains 100 records (100 row's data) After fetching 10 table's record , the data size of my app has grown to 118MB.

Is this much space taking normal for Realm? ---> 118MB.

Or am I doing something wrong with the Realm? I have checked my records for the duplication. There's no repetition, each row is getting saved only one time.

That's how I am configuring Realm in my Application class

realmConfig = new RealmConfiguration.Builder(this).build();
Realm.setDefaultConfiguration(realmConfig);

And later on I am using the Default instance wherever I need it. And closing the Realm on the onTerminate of Application class

More Info: Android studio Version = 2.1.3

Realm Version = 1.2.0

Device = Nexus 5 Marshmallow

My Intent service for saving records in Database. It get's called after every page response.

public class SaveTableRecord extends Base_IntentService {

    private static final String ACTION_SAVE_RECORDS = "saveRecords";
    private static final String EXTRA_CLASS = "classVar";
    private static final String EXTRA_TABLE_JSON = "tabJson";
    private static final String LOG_TAG = "saveTableRecord";

    private String json, className;
    Realm realm;
    private Gson gson;

    public SaveTableRecord() {
        super("SaveTableRecord");
    }

    public static void startSavingRecord(Context context, String cls, String tableJson) {
        Log.i("Service", "SAVETABLERECORD.CLASS started");
        Intent intent = new Intent(context, SaveTableRecord.class);
        intent.setAction(ACTION_SAVE_RECORDS);
        intent.putExtra(EXTRA_TABLE_JSON, tableJson);
        intent.putExtra(EXTRA_CLASS, cls);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            className = intent.getStringExtra(EXTRA_CLASS);
            json = intent.getStringExtra(EXTRA_TABLE_JSON);
            initGsonDataTypes();
            initRecordSaving();
        }
    }


    private void initGsonDataTypes() {
        GsonBuilder builder = new GsonBuilder();
        //  builder.setLongSerializationPolicy(LongSerializationPolicy.STRING);
        builder.registerTypeAdapter(long.class, new LongTypeAdapter());
        builder.registerTypeAdapter(double.class, new DoubleTypeAdapter());
        builder.registerTypeAdapter(int.class, new IntTypeAdapter());
        builder.registerTypeAdapter(short.class, new ShortTypeAdapter());
        builder.registerTypeAdapter(boolean.class, new BooleanTypeAdapter());
        builder.registerTypeAdapter(Date.class, new GsonUTCDateAdapter());
        builder.setExclusionStrategies(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes f) {
                return f.getDeclaringClass().equals(RealmObject.class);
            }

            @Override
            public boolean shouldSkipClass(Class<?> clazz) {
                return false;
            }
        });
        builder.setPrettyPrinting();
        gson = builder.create();
    }

    private void initRecordSaving() {
        try {
            realm = Realm.getDefaultInstance();
            showLog("-------------------InitRecordSaving()--------------------");
            final JSONObject main = new JSONObject(json);
            final JSONArray jsonArray = main.getJSONArray("records");
            //  String json = main.getString("records");
            //  saveATableRecord(json);

            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {

                    for (int i = 0; i < jsonArray.length(); i++) {
                        try {
                            String tableString = jsonArray.getString(i);
                            saveATableRecord(tableString);
                        } catch (Exception ex) {
                            showLog("EXCEPTION A ");
                        }
                    }
                }
            });


        } catch (Exception e) {
            //   showLog("EXCEPTION!!!! SAVETABLERECORD CLASS");
            e.printStackTrace();
        }
    }

    private void saveATableRecord(String tableData) {

        showLog("Table name =" + className + " AND Data = " + tableData);

        try {
            Class cls = Class.forName("com.oper.max.model.db.sync_tables." + className);
            Object obj = gson.fromJson(tableData, cls);
            // realm.beginTransaction();
            realm.copyToRealmOrUpdate((RealmObject) obj);
            // realm.commitTransaction();
            showLog("Object Added successfully");

        } catch (Exception e) {
            // realm.commitTransaction();
            showLog("Exception in saveATableRecord = " + e.getMessage().toString());
            e.printStackTrace();
        }
    }
}

Upvotes: 1

Views: 592

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81588

You are not closing your Realm instance, and you should always close your Realm instance on non-looping background threads.

Change this:

private void initRecordSaving() {
    try {
        realm = Realm.getDefaultInstance();
        showLog("-------------------InitRecordSaving()--------------------");
        final JSONObject main = new JSONObject(json);
        final JSONArray jsonArray = main.getJSONArray("records");
        //  String json = main.getString("records");
        //  saveATableRecord(json);

        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {

                for (int i = 0; i < jsonArray.length(); i++) {
                    try {
                        String tableString = jsonArray.getString(i);
                        saveATableRecord(tableString);
                    } catch (Exception ex) {
                        showLog("EXCEPTION A ");
                    }
                }

            }
        });


    } catch (Exception e) {
        //   showLog("EXCEPTION!!!! SAVETABLERECORD CLASS");
        e.printStackTrace();
    }
}

private void saveATableRecord(String tableData) {

    showLog("Table name =" + className + " AND Data = " + tableData);

    try {
        Class cls = Class.forName("com.oper.max.model.db.sync_tables." + className);
        Object obj = gson.fromJson(tableData, cls);
        // realm.beginTransaction();
        realm.copyToRealmOrUpdate((RealmObject) obj);
        // realm.commitTransaction();
        showLog("Object Added successfully");

    } catch (Exception e) {
        // realm.commitTransaction();
        showLog("Exception in saveATableRecord = " + e.getMessage().toString());
        e.printStackTrace();
    }

}

To this:

private void initRecordSaving() {
    Realm realm = null;
    try {
        realm = Realm.getDefaultInstance();
        showLog("-------------------InitRecordSaving()--------------------");
        final JSONObject main = new JSONObject(json);
        final JSONArray jsonArray = main.getJSONArray("records");
        //  String json = main.getString("records");
        //  saveATableRecord(json);

        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {

                for (int i = 0; i < jsonArray.length(); i++) {
                    try {
                        String tableString = jsonArray.getString(i);
                        saveATableRecord(realm, tableString);
                    } catch (Exception ex) {
                        showLog("EXCEPTION A ");
                    }
                }

            }
        });
    } catch (Exception e) {
        //   showLog("EXCEPTION!!!! SAVETABLERECORD CLASS");
        e.printStackTrace();
    } finally {
        if(realm != null) {
            realm.close();
        }
    }
}

private void saveATableRecord(Realm realm, String tableData) {

    showLog("Table name =" + className + " AND Data = " + tableData);

    try {
        Class cls = Class.forName("com.oper.max.model.db.sync_tables." + className);
        Object obj = gson.fromJson(tableData, cls);
        // realm.beginTransaction();
        realm.copyToRealmOrUpdate((RealmObject) obj);
        // realm.commitTransaction();
        showLog("Object Added successfully");

    } catch (Exception e) {
        // realm.commitTransaction();
        showLog("Exception in saveATableRecord = " + e.getMessage().toString());
        e.printStackTrace();
    }

}

Upvotes: 2

Related Questions