Top Related Projects
Android Database - first and fast, lightweight on-device vector database
greenDAO is a light & fast ORM solution for Android that maps objects to SQLite databases.
A Java serialization/deserialization library to convert Java Objects into JSON and back
A modern JSON library for Kotlin and Java.
FlatBuffers: Memory Efficient Serialization Library
Lightweight, embedded, syncable NoSQL database engine for Android.
Quick Overview
Realm Java is a mobile database solution that offers an alternative to SQLite and ORMs. It's designed to be fast, easy to use, and optimized for mobile devices. Realm Java allows developers to work with data efficiently in Android applications.
Pros
- Fast performance due to its object-oriented database design
- Simple and intuitive API, reducing boilerplate code
- Supports real-time data synchronization across devices
- Offers encryption for data security
Cons
- Limited query capabilities compared to SQL databases
- Requires a specific data model structure, which may not fit all use cases
- Learning curve for developers accustomed to traditional SQLite or ORM solutions
- Potential migration challenges when updating to newer versions
Code Examples
- Defining a Realm model:
public class Person extends RealmObject {
@PrimaryKey
private String id;
private String name;
private int age;
// Getters and setters
}
- Inserting data into Realm:
Realm realm = Realm.getDefaultInstance();
realm.executeTransaction(r -> {
Person person = r.createObject(Person.class, UUID.randomUUID().toString());
person.setName("John Doe");
person.setAge(30);
});
realm.close();
- Querying data from Realm:
Realm realm = Realm.getDefaultInstance();
RealmResults<Person> results = realm.where(Person.class)
.equalTo("name", "John Doe")
.findAll();
realm.close();
Getting Started
- Add Realm to your project's
build.gradle
:
dependencies {
implementation 'io.realm:realm-android-library:10.11.1'
}
- Initialize Realm in your Application class:
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Realm.init(this);
RealmConfiguration config = new RealmConfiguration.Builder().build();
Realm.setDefaultConfiguration(config);
}
}
- Use Realm in your activities or fragments:
Realm realm = Realm.getDefaultInstance();
try {
// Perform database operations
} finally {
realm.close();
}
Competitor Comparisons
Android Database - first and fast, lightweight on-device vector database
Pros of ObjectBox
- Faster performance, especially for bulk operations and queries
- Simpler setup and configuration process
- Native support for relations and object graphs
Cons of ObjectBox
- Smaller community and ecosystem compared to Realm
- Less extensive documentation and learning resources
- Limited cross-platform support (primarily focused on Java/Android)
Code Comparison
ObjectBox:
@Entity
public class User {
@Id long id;
String name;
int age;
}
Box<User> userBox = store.boxFor(User.class);
userBox.put(new User(0, "Alice", 25));
List<User> users = userBox.query().equal(User_.age, 25).build().find();
Realm:
public class User extends RealmObject {
@PrimaryKey
private long id;
private String name;
private int age;
}
realm.executeTransaction(r -> {
r.insert(new User(0, "Alice", 25));
});
RealmResults<User> users = realm.where(User.class).equalTo("age", 25).findAll();
Both libraries offer similar functionality for defining models and performing database operations. ObjectBox uses annotations for entity definition, while Realm extends a base class. ObjectBox's query syntax is more fluent, whereas Realm's is more method-chaining based.
greenDAO is a light & fast ORM solution for Android that maps objects to SQLite databases.
Pros of greenDAO
- Simpler setup and integration process
- Smaller library size, resulting in lower app overhead
- Faster query execution for complex operations
Cons of greenDAO
- Less feature-rich compared to Realm
- Limited support for real-time data synchronization
- Requires more boilerplate code for entity definitions
Code Comparison
greenDAO entity definition:
@Entity
public class User {
@Id private Long id;
private String name;
private int age;
}
Realm entity definition:
public class User extends RealmObject {
@PrimaryKey
private long id;
private String name;
private int age;
}
Both greenDAO and Realm are popular Android ORM (Object-Relational Mapping) libraries for database management. greenDAO is lightweight and focuses on performance, while Realm offers a more comprehensive feature set with real-time synchronization capabilities.
greenDAO uses annotation-based entity definitions and generates code at compile-time, which can lead to faster query execution. Realm, on the other hand, uses a custom storage engine and provides a more object-oriented approach to data management.
While greenDAO may be easier to set up and integrate, Realm offers more advanced features like real-time data synchronization and cross-platform support. The choice between the two depends on the specific requirements of your project and the level of complexity you're willing to manage.
A Java serialization/deserialization library to convert Java Objects into JSON and back
Pros of gson
- Lightweight and simple to use for JSON serialization/deserialization
- No external dependencies, making it easy to integrate into projects
- Extensive documentation and community support
Cons of gson
- Limited to JSON processing, while Realm offers a full-fledged database solution
- Lacks built-in support for complex data structures and relationships
- No automatic data synchronization or real-time updates
Code Comparison
gson:
Gson gson = new Gson();
String json = gson.toJson(myObject);
MyClass obj = gson.fromJson(json, MyClass.class);
realm-java:
Realm realm = Realm.getDefaultInstance();
realm.executeTransaction(r -> {
r.copyToRealm(myObject);
});
MyClass obj = realm.where(MyClass.class).findFirst();
The gson code demonstrates simple JSON serialization and deserialization, while the realm-java code shows object persistence and querying in a database context. Realm offers more advanced features for data management, while gson focuses solely on JSON processing.
A modern JSON library for Kotlin and Java.
Pros of Moshi
- Lightweight and focused solely on JSON parsing, making it more efficient for simple JSON operations
- Easier integration with Kotlin, including support for Kotlin data classes
- More flexible customization options for JSON serialization/deserialization
Cons of Moshi
- Limited to JSON processing, while Realm Java offers a complete database solution
- Requires manual object mapping, whereas Realm Java provides automatic object-relational mapping
- Less suitable for complex data persistence scenarios compared to Realm Java's full-featured database capabilities
Code Comparison
Moshi (JSON parsing):
val moshi = Moshi.Builder().build()
val jsonAdapter = moshi.adapter(User::class.java)
val user = jsonAdapter.fromJson(jsonString)
Realm Java (database operations):
val realm = Realm.getDefaultInstance()
realm.executeTransaction { r ->
r.copyToRealm(user)
}
Summary
Moshi excels in lightweight JSON processing with strong Kotlin support, while Realm Java offers a comprehensive database solution with automatic object mapping. Choose Moshi for simple JSON operations and Realm Java for complex data persistence needs.
FlatBuffers: Memory Efficient Serialization Library
Pros of FlatBuffers
- Faster serialization and deserialization due to zero-copy design
- Smaller memory footprint and file size for serialized data
- Cross-platform support with multiple language bindings
Cons of FlatBuffers
- Steeper learning curve and more complex setup
- Less intuitive for simple data models
- Limited built-in database functionality compared to Realm
Code Comparison
FlatBuffers:
FlatBufferBuilder builder = new FlatBufferBuilder(1024);
int nameOffset = builder.createString("John Doe");
int person = Person.createPerson(builder, nameOffset, 30);
builder.finish(person);
Realm:
realm.executeTransaction(r -> {
Person person = r.createObject(Person.class);
person.setName("John Doe");
person.setAge(30);
});
Summary
FlatBuffers excels in performance and cross-platform support, making it ideal for high-performance applications and games. Realm Java offers a more user-friendly API and built-in database functionality, making it better suited for typical mobile app development. The choice between the two depends on specific project requirements, with FlatBuffers being more appropriate for performance-critical scenarios and Realm Java for easier database management in Android apps.
Lightweight, embedded, syncable NoSQL database engine for Android.
Pros of Couchbase Lite Android
- Supports multi-master replication and offline-first capabilities
- Offers flexible querying with N1QL (SQL-like language)
- Provides built-in conflict resolution mechanisms
Cons of Couchbase Lite Android
- Steeper learning curve compared to Realm
- Larger database size and potentially higher memory usage
- More complex setup and configuration process
Code Comparison
Realm Java:
RealmConfiguration config = new RealmConfiguration.Builder().build();
Realm realm = Realm.getInstance(config);
realm.executeTransaction(r -> {
User user = r.createObject(User.class);
user.setName("John");
});
Couchbase Lite Android:
Database database = new Database("mydb");
MutableDocument document = new MutableDocument();
document.setString("name", "John");
database.save(document);
Both libraries offer simple APIs for data persistence, but Realm's syntax is more concise and object-oriented. Couchbase Lite uses a document-based approach, which may be more familiar to developers with NoSQL experience.
While Realm excels in ease of use and performance for local data storage, Couchbase Lite shines in scenarios requiring robust synchronization and offline capabilities. The choice between the two depends on specific project requirements and the developer's familiarity with each system.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Realm is a mobile database that runs directly inside phones, tablets or wearables. This repository holds the source code for the Java version of Realm, which currently runs only on Android.
Realm Kotlin
The Realm Kotlin SDK is now GA and can be used for both Android and Kotlin Multiplatform. While we are still adding features, please consider using Realm Kotlin for any new project, and let us know if you miss anything there!
Features
- Mobile-first: Realm is the first database built from the ground up to run directly inside phones, tablets, and wearables.
- Simple: Data is directly exposed as objects and queryable by code, removing the need for ORM's riddled with performance & maintenance issues. Plus, we've worked hard to keep our API down to very few classes: most of our users pick it up intuitively, getting simple apps up & running in minutes.
- Modern: Realm supports easy thread-safety, relationships & encryption.
- Fast: Realm is faster than even raw SQLite on common operations while maintaining an extremely rich feature set.
- Device Sync: Makes it simple to keep data in sync across users, devices, and your backend in real-time. Get started for free with a template application and create the cloud backend.
Getting Started
Please see the detailed instructions in our docs to add Realm to your project.
Documentation
Documentation for Realm can be found at mongodb.com/docs/atlas/device-sdks/sdk/java/. The API reference is located at mongodb.com/docs/atlas/device-sdks/sdk/java/api/.
Getting Help
- Got a question?: Look for previous questions on the #realm tag â or ask a new question. We actively monitor & answer questions on StackOverflow! You can also check out our Community Forum where general questions about how to do something can be discussed.
- Think you found a bug? Open an issue. If possible, include the version of Realm, a full log, the Realm file, and a project that shows the issue.
- Have a feature request? Open an issue. Tell us what the feature should do, and why you want the feature.
Using Snapshots
If you want to test recent bugfixes or features that have not been packaged in an official release yet, you can use a -SNAPSHOT release of the current development version of Realm via Gradle, available on Sonatype OSS
buildscript {
repositories {
mavenCentral()
google()
maven {
url 'https://oss.sonatype.org/content/repositories/snapshots/'
}
jcenter()
}
dependencies {
classpath "io.realm:realm-gradle-plugin:<version>-SNAPSHOT"
}
}
allprojects {
repositories {
mavenCentral()
google()
maven {
url 'https://oss.sonatype.org/content/repositories/snapshots/'
}
jcenter()
}
}
See version.txt for the latest version number.
Building Realm
In case you don't want to use the precompiled version, you can build Realm yourself from source.
Prerequisites
-
Download the JDK 8 from Oracle and install it.
-
The latest stable version of Android Studio. Currently 4.1.1.
-
Download & install the Android SDK Build-Tools 29.0.3, Android Pie (API 29) (for example through Android Studioâs Android SDK Manager).
-
Install CMake version 3.18.4 and build Ninja.
-
Install the NDK (Side-by-side) 21.0.6113669 from the SDK Manager in Android Studio. Remember to check
â Show package details
in the manager to display all available versions. -
Add the Android home environment variable to your profile:
export ANDROID_HOME=~/Library/Android/sdk
-
If you are launching Android Studio from the macOS Finder, you should also run the following command:
launchctl setenv ANDROID_HOME "$ANDROID_HOME"
-
If you'd like to specify the location in which to store the archives of Realm Core, define the
REALM_CORE_DOWNLOAD_DIR
environment variable. It enables caching core release artifacts.export REALM_CORE_DOWNLOAD_DIR=~/.realmCore
macOS users must also run the following command for Android Studio to see this environment variable.
launchctl setenv REALM_CORE_DOWNLOAD_DIR "$REALM_CORE_DOWNLOAD_DIR"
It would be a good idea to add all of the symbol definitions (and their accompanying launchctl
commands, if you are using macOS) to your ~/.profile
(or ~/.zprofile
if the login shell is zsh
)
-
If you develop Realm Java with Android Studio, we recommend you to exclude some directories from indexing target by executing following steps on Android Studio. It really speeds up indexing phase after the build.
- Under
/realm/realm-library/
, selectbuild
,.cxx
anddistribution
folders inProject
view. - Press
Command + Shift + A
to openFind action
dialog. If you are not using default keymap nor using macOS, you can find your shortcut key inKeymap
preference by searchingFind action
. - Search
Excluded
(notExclude
) action and select it. Selected folder icons should become orange (in default theme). - Restart Android Studio.
- Under
Download sources
You can download the source code of Realm Java by using git. Since realm-java has git submodules, use --recursive
when cloning the repository.
git clone git@github.com:realm/realm-java.git --recursive
or
git clone https://github.com/realm/realm-java.git --recursive
Build
Once you have completed all the pre-requisites building Realm is done with a simple command.
./gradlew assemble
That command will generate:
- a jar file for the Realm Gradle plugin
- an aar file for the Realm library
- a jar file for the annotations
- a jar file for the annotations processor
The full build may take an hour or more, to complete.
Building from source
It is possible to build Realm Java with the submodule version of Realm Core. This is done by providing the following parameter when building: -PbuildCore=true
.
./gradlew assembleBase -PbuildCore=true
You can turn off interprocedural optimizations with the following parameter: -PenableLTO=false
.
./gradlew assembleBase -PenableLTO=false`
Note: Building the Base
variant would always build realm-core.
Note: Interprocedural optimizations are enabled by default.
Note: If you want to build from source inside Android Studio, you need to update the Gradle parameters by going into the Realm projects settings Settings > Build, Execution, Deployment > Compiler > Command-line options
and add -PbuildCore=true
or -PenableLTO=false
to it. Alternatively you can add it into your gradle.properties
:
buildCore=true
enableLTO=false
Note: If building on OSX you might like to prevent Gatekeeper to block all NDK executables by disabling it: sudo spctl --master-disable
. Remember to enable it afterwards: sudo spctl --master-enable
Other Commands
./gradlew tasks
will show all the available tasks./gradlew javadoc
will generate the Javadocs./gradlew monkeyExamples
will run the monkey tests on all the examples./gradlew installRealmJava
will install the Realm library and plugin to mavenLocal()./gradlew clean -PdontCleanJniFiles
will remove all generated files except for JNI related files. This reduces recompilation time a lot../gradlew connectedUnitTests -PbuildTargetABIs=$(adb shell getprop ro.product.cpu.abi)
will build JNI files only for the ABI which corresponds to the connected device. These tests require a running Object Server (see below)
Generating the Javadoc using the command above may generate warnings. The Javadoc is generated despite the warnings.
Upgrading Gradle Wrappers
All gradle projects in this repository have wrapper
task to generate Gradle Wrappers. Those tasks refer to gradle
property defined in /dependencies.list
to determine Gradle Version of generating wrappers.
We have a script ./tools/update_gradle_wrapper.sh
to automate these steps. When you update Gradle Wrappers, please obey the following steps.
- Edit
gradle
property in defined in/dependencies.list
to new Gradle Wrapper version. - Execute
/tools/update_gradle_wrapper.sh
.
Gotchas
The repository is organized into six Gradle projects:
realm
: it contains the actual library (including the JNI layer) and the annotations processor.realm-annotations
: it contains the annotations defined by Realm.realm-transformer
: it contains the bytecode transformer.gradle-plugin
: it contains the Gradle plugin.examples
: it contains the example projects. This project directly depends ongradle-plugin
which adds a dependency to the artifacts produced byrealm
.- The root folder is another Gradle project. All it does is orchestrate the other jobs.
This means that ./gradlew clean
and ./gradlew cleanExamples
will fail if assembleExamples
has not been executed first.
Note that IntelliJ does not support multiple projects in the same window
so each of the six Gradle projects must be imported as a separate IntelliJ project.
Since the repository contains several completely independent Gradle projects, several independent builds are run to assemble it.
Seeing a line like: :realm:realm-library:compileBaseDebugAndroidTestSources UP-TO-DATE
in the build log does not imply
that you can run ./gradlew :realm:realm-library:compileBaseDebugAndroidTestSources
.
Examples
The ./examples
folder contains many example projects showing how Realm can be used. If this is the first time you checkout or pull a new version of this repository to try the examples, you must call ./gradlew installRealmJava
from the top-level directory first. Otherwise, the examples will not compile as they depend on all Realm artifacts being installed in mavenLocal()
.
Standalone examples can be downloaded from website.
Running Tests on a Device
To run these tests, you must have a device connected to the build computer, and the adb
command must be in your PATH
-
Connect an Android device and verify that the command
adb devices
shows a connected device:adb devices List of devices attached 004c03eb5615429f device
-
Run instrumentation tests:
cd realm ./gradlew connectedBaseDebugAndroidTest
These tests may take as much as half an hour to complete.
Running Tests Using The Realm Object Server
Tests in realm/realm-library/src/syncIntegrationTest
require a running testing server to work.
A docker image can be built from tools/sync_test_server/Dockerfile
to run the test server.
tools/sync_test_server/start_server.sh
will build the docker image automatically.
To run a testing server locally:
-
Install docker and run it.
-
Run
tools/sync_test_server/start_server.sh
:cd tools/sync_test_server ./start_server.sh
This command will not complete until the server has stopped.
-
Run instrumentation tests
In a new terminal window, run:
cd realm ./gradlew connectedObjectServerDebugAndroidTest
Note that if using VirtualBox (Genymotion), the network needs to be bridged for the tests to work.
This is done in VirtualBox > Network
. Set "Adapter 2" to "Bridged Adapter".
These tests may take as much as half an hour to complete.
Contributing
See CONTRIBUTING.md for more details!
This project adheres to the MongoDB Code of Conduct. By participating, you are expected to uphold this code. Please report unacceptable behavior to community-conduct@mongodb.com.
The directory realm/config/studio
contains lint and style files recommended for project code.
Import them from Android Studio with Android Studio > Preferences... > Code Style > Manage... > Import,
or Android Studio > Preferences... > Inspections > Manage... > Import. Once imported select the
style/lint in the drop-down to the left of the Manage... button.
License
Realm Java is published under the Apache 2.0 license.
Realm Core is also published under the Apache 2.0 license and is available here.
Feedback
If you use Realm and are happy with it, all we ask is that you, please consider sending out a tweet mentioning @realm to share your thoughts!
And if you don't like it, please let us know what you would like improved, so we can fix it!
Top Related Projects
Android Database - first and fast, lightweight on-device vector database
greenDAO is a light & fast ORM solution for Android that maps objects to SQLite databases.
A Java serialization/deserialization library to convert Java Objects into JSON and back
A modern JSON library for Kotlin and Java.
FlatBuffers: Memory Efficient Serialization Library
Lightweight, embedded, syncable NoSQL database engine for Android.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot