or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

data-management.mddata-storage.mdencryption.mdindex.mdinitialization.mdinstance-management.mdmulti-process.mdnamespace.md

data-storage.mddocs/

0

# Data Storage and Retrieval

1

2

Comprehensive data storage API supporting primitives, strings, byte arrays, string sets, and Parcelable objects with optional expiration times.

3

4

## Capabilities

5

6

### Boolean Values

7

8

Store and retrieve boolean values with optional expiration.

9

10

```java { .api }

11

/**

12

* Store a boolean value.

13

* @param key The key for the value

14

* @param value The boolean value to store

15

* @return True if successful, false otherwise

16

*/

17

public boolean encode(String key, boolean value);

18

19

/**

20

* Store a boolean value with expiration.

21

* @param key The key for the value

22

* @param value The boolean value to store

23

* @param expireDurationInSecond Expiration time in seconds, 0 means never expire

24

* @return True if successful, false otherwise

25

*/

26

public boolean encode(String key, boolean value, int expireDurationInSecond);

27

28

/**

29

* Retrieve a boolean value with default false.

30

* @param key The key for the value

31

* @return The boolean value or false if not found

32

*/

33

public boolean decodeBool(String key);

34

35

/**

36

* Retrieve a boolean value with custom default.

37

* @param key The key for the value

38

* @param defaultValue The default value if key not found

39

* @return The boolean value or defaultValue if not found

40

*/

41

public boolean decodeBool(String key, boolean defaultValue);

42

```

43

44

**Usage Example:**

45

46

```java

47

MMKV kv = MMKV.defaultMMKV();

48

49

// Store boolean values

50

kv.encode("is_premium", true);

51

kv.encode("show_tutorial", false);

52

53

// Store with expiration (expires in 1 hour)

54

kv.encode("temp_flag", true, MMKV.ExpireInHour);

55

56

// Retrieve boolean values

57

boolean isPremium = kv.decodeBool("is_premium"); // true

58

boolean showTutorial = kv.decodeBool("show_tutorial"); // false

59

boolean unknownFlag = kv.decodeBool("unknown"); // false (default)

60

boolean unknownFlag2 = kv.decodeBool("unknown", true); // true (custom default)

61

```

62

63

### Integer Values

64

65

Store and retrieve integer values with optional expiration.

66

67

```java { .api }

68

/**

69

* Store an integer value.

70

* @param key The key for the value

71

* @param value The integer value to store

72

* @return True if successful, false otherwise

73

*/

74

public boolean encode(String key, int value);

75

76

/**

77

* Store an integer value with expiration.

78

* @param key The key for the value

79

* @param value The integer value to store

80

* @param expireDurationInSecond Expiration time in seconds

81

* @return True if successful, false otherwise

82

*/

83

public boolean encode(String key, int value, int expireDurationInSecond);

84

85

/**

86

* Retrieve an integer value with default 0.

87

* @param key The key for the value

88

* @return The integer value or 0 if not found

89

*/

90

public int decodeInt(String key);

91

92

/**

93

* Retrieve an integer value with custom default.

94

* @param key The key for the value

95

* @param defaultValue The default value if key not found

96

* @return The integer value or defaultValue if not found

97

*/

98

public int decodeInt(String key, int defaultValue);

99

```

100

101

**Usage Example:**

102

103

```java

104

// Store integer values

105

kv.encode("user_id", 12345);

106

kv.encode("score", 9850);

107

kv.encode("level", 42);

108

109

// Store with expiration (expires in 1 day)

110

kv.encode("daily_bonus", 100, MMKV.ExpireInDay);

111

112

// Retrieve integer values

113

int userId = kv.decodeInt("user_id"); // 12345

114

int score = kv.decodeInt("score"); // 9850

115

int unknown = kv.decodeInt("unknown"); // 0 (default)

116

int lives = kv.decodeInt("lives", 3); // 3 (custom default)

117

```

118

119

### Long Values

120

121

Store and retrieve long values for large numbers or timestamps.

122

123

```java { .api }

124

/**

125

* Store a long value.

126

* @param key The key for the value

127

* @param value The long value to store

128

* @return True if successful, false otherwise

129

*/

130

public boolean encode(String key, long value);

131

132

/**

133

* Store a long value with expiration.

134

* @param key The key for the value

135

* @param value The long value to store

136

* @param expireDurationInSecond Expiration time in seconds

137

* @return True if successful, false otherwise

138

*/

139

public boolean encode(String key, long value, int expireDurationInSecond);

140

141

/**

142

* Retrieve a long value with default 0.

143

* @param key The key for the value

144

* @return The long value or 0 if not found

145

*/

146

public long decodeLong(String key);

147

148

/**

149

* Retrieve a long value with custom default.

150

* @param key The key for the value

151

* @param defaultValue The default value if key not found

152

* @return The long value or defaultValue if not found

153

*/

154

public long decodeLong(String key, long defaultValue);

155

```

156

157

**Usage Example:**

158

159

```java

160

// Store timestamps and large numbers

161

long currentTime = System.currentTimeMillis();

162

kv.encode("last_login", currentTime);

163

kv.encode("total_points", 999999999L);

164

165

// Store with expiration

166

kv.encode("session_start", currentTime, MMKV.ExpireInHour);

167

168

// Retrieve long values

169

long lastLogin = kv.decodeLong("last_login");

170

long totalPoints = kv.decodeLong("total_points");

171

long sessionStart = kv.decodeLong("session_start", currentTime);

172

```

173

174

### Float Values

175

176

Store and retrieve floating-point values.

177

178

```java { .api }

179

/**

180

* Store a float value.

181

* @param key The key for the value

182

* @param value The float value to store

183

* @return True if successful, false otherwise

184

*/

185

public boolean encode(String key, float value);

186

187

/**

188

* Store a float value with expiration.

189

* @param key The key for the value

190

* @param value The float value to store

191

* @param expireDurationInSecond Expiration time in seconds

192

* @return True if successful, false otherwise

193

*/

194

public boolean encode(String key, float value, int expireDurationInSecond);

195

196

/**

197

* Retrieve a float value with default 0.0f.

198

* @param key The key for the value

199

* @return The float value or 0.0f if not found

200

*/

201

public float decodeFloat(String key);

202

203

/**

204

* Retrieve a float value with custom default.

205

* @param key The key for the value

206

* @param defaultValue The default value if key not found

207

* @return The float value or defaultValue if not found

208

*/

209

public float decodeFloat(String key, float defaultValue);

210

```

211

212

**Usage Example:**

213

214

```java

215

// Store float values

216

kv.encode("completion_percentage", 85.5f);

217

kv.encode("volume", 0.8f);

218

kv.encode("temperature", 23.7f);

219

220

// Retrieve float values

221

float completion = kv.decodeFloat("completion_percentage"); // 85.5f

222

float volume = kv.decodeFloat("volume"); // 0.8f

223

float brightness = kv.decodeFloat("brightness", 1.0f); // 1.0f (default)

224

```

225

226

### Double Values

227

228

Store and retrieve double-precision floating-point values.

229

230

```java { .api }

231

/**

232

* Store a double value.

233

* @param key The key for the value

234

* @param value The double value to store

235

* @return True if successful, false otherwise

236

*/

237

public boolean encode(String key, double value);

238

239

/**

240

* Store a double value with expiration.

241

* @param key The key for the value

242

* @param value The double value to store

243

* @param expireDurationInSecond Expiration time in seconds

244

* @return True if successful, false otherwise

245

*/

246

public boolean encode(String key, double value, int expireDurationInSecond);

247

248

/**

249

* Retrieve a double value with default 0.0.

250

* @param key The key for the value

251

* @return The double value or 0.0 if not found

252

*/

253

public double decodeDouble(String key);

254

255

/**

256

* Retrieve a double value with custom default.

257

* @param key The key for the value

258

* @param defaultValue The default value if key not found

259

* @return The double value or defaultValue if not found

260

*/

261

public double decodeDouble(String key, double defaultValue);

262

```

263

264

**Usage Example:**

265

266

```java

267

// Store high-precision values

268

kv.encode("pi", 3.141592653589793);

269

kv.encode("exchange_rate", 1.2345678901234567);

270

271

// Retrieve double values

272

double pi = kv.decodeDouble("pi");

273

double exchangeRate = kv.decodeDouble("exchange_rate");

274

double defaultRate = kv.decodeDouble("unknown_rate", 1.0);

275

```

276

277

### String Values

278

279

Store and retrieve string values with null support.

280

281

```java { .api }

282

/**

283

* Store a string value.

284

* @param key The key for the value

285

* @param value The string value to store (can be null)

286

* @return True if successful, false otherwise

287

*/

288

public boolean encode(String key, String value);

289

290

/**

291

* Store a string value with expiration.

292

* @param key The key for the value

293

* @param value The string value to store

294

* @param expireDurationInSecond Expiration time in seconds

295

* @return True if successful, false otherwise

296

*/

297

public boolean encode(String key, String value, int expireDurationInSecond);

298

299

/**

300

* Retrieve a string value with default null.

301

* @param key The key for the value

302

* @return The string value or null if not found

303

*/

304

public String decodeString(String key);

305

306

/**

307

* Retrieve a string value with custom default.

308

* @param key The key for the value

309

* @param defaultValue The default value if key not found

310

* @return The string value or defaultValue if not found

311

*/

312

public String decodeString(String key, String defaultValue);

313

```

314

315

**Usage Example:**

316

317

```java

318

// Store string values

319

kv.encode("username", "john_doe");

320

kv.encode("email", "john@example.com");

321

kv.encode("nickname", null); // Store null value

322

323

// Store with expiration (expires in 1 week)

324

kv.encode("temp_token", "abc123", 7 * MMKV.ExpireInDay);

325

326

// Retrieve string values

327

String username = kv.decodeString("username"); // "john_doe"

328

String email = kv.decodeString("email"); // "john@example.com"

329

String nickname = kv.decodeString("nickname"); // null

330

String theme = kv.decodeString("theme", "default"); // "default" (custom default)

331

```

332

333

### String Sets

334

335

Store and retrieve collections of strings.

336

337

```java { .api }

338

/**

339

* Store a string set.

340

* @param key The key for the value

341

* @param value The string set to store (can be null)

342

* @return True if successful, false otherwise

343

*/

344

public boolean encode(String key, Set<String> value);

345

346

/**

347

* Store a string set with expiration.

348

* @param key The key for the value

349

* @param value The string set to store

350

* @param expireDurationInSecond Expiration time in seconds

351

* @return True if successful, false otherwise

352

*/

353

public boolean encode(String key, Set<String> value, int expireDurationInSecond);

354

355

/**

356

* Retrieve a string set with default null.

357

* @param key The key for the value

358

* @return The string set or null if not found

359

*/

360

public Set<String> decodeStringSet(String key);

361

362

/**

363

* Retrieve a string set with custom default.

364

* @param key The key for the value

365

* @param defaultValue The default value if key not found

366

* @return The string set or defaultValue if not found

367

*/

368

public Set<String> decodeStringSet(String key, Set<String> defaultValue);

369

370

/**

371

* Retrieve a string set with custom default and set implementation.

372

* @param key The key for the value

373

* @param defaultValue The default value if key not found

374

* @param cls The Set implementation class to use

375

* @return The string set or defaultValue if not found

376

*/

377

public Set<String> decodeStringSet(String key, Set<String> defaultValue, Class<? extends Set> cls);

378

```

379

380

**Usage Example:**

381

382

```java

383

import java.util.*;

384

385

// Store string sets

386

Set<String> tags = new HashSet<>();

387

tags.add("android");

388

tags.add("mobile");

389

tags.add("development");

390

kv.encode("project_tags", tags);

391

392

Set<String> permissions = new LinkedHashSet<>();

393

permissions.add("CAMERA");

394

permissions.add("STORAGE");

395

kv.encode("granted_permissions", permissions);

396

397

// Store with expiration

398

Set<String> tempCategories = new HashSet<>();

399

tempCategories.add("featured");

400

kv.encode("temp_categories", tempCategories, MMKV.ExpireInHour);

401

402

// Retrieve string sets

403

Set<String> projectTags = kv.decodeStringSet("project_tags");

404

Set<String> grantedPerms = kv.decodeStringSet("granted_permissions");

405

406

// With custom default

407

Set<String> defaultTags = new HashSet<>();

408

defaultTags.add("default");

409

Set<String> userTags = kv.decodeStringSet("user_tags", defaultTags);

410

411

// With specific Set implementation (LinkedHashSet to preserve order)

412

Set<String> orderedSet = kv.decodeStringSet("ordered_items", null, LinkedHashSet.class);

413

```

414

415

### Byte Arrays

416

417

Store and retrieve binary data as byte arrays.

418

419

```java { .api }

420

/**

421

* Store a byte array.

422

* @param key The key for the value

423

* @param value The byte array to store (can be null)

424

* @return True if successful, false otherwise

425

*/

426

public boolean encode(String key, byte[] value);

427

428

/**

429

* Store a byte array with expiration.

430

* @param key The key for the value

431

* @param value The byte array to store

432

* @param expireDurationInSecond Expiration time in seconds

433

* @return True if successful, false otherwise

434

*/

435

public boolean encode(String key, byte[] value, int expireDurationInSecond);

436

437

/**

438

* Retrieve a byte array with default null.

439

* @param key The key for the value

440

* @return The byte array or null if not found

441

*/

442

public byte[] decodeBytes(String key);

443

444

/**

445

* Retrieve a byte array with custom default.

446

* @param key The key for the value

447

* @param defaultValue The default value if key not found

448

* @return The byte array or defaultValue if not found

449

*/

450

public byte[] decodeBytes(String key, byte[] defaultValue);

451

```

452

453

**Usage Example:**

454

455

```java

456

// Store binary data

457

String text = "Hello, MMKV!";

458

byte[] textBytes = text.getBytes("UTF-8");

459

kv.encode("text_data", textBytes);

460

461

// Store image or file data

462

byte[] imageData = loadImageFromAssets();

463

kv.encode("cached_image", imageData);

464

465

// Store with expiration (cache for 1 hour)

466

byte[] tempData = generateTempData();

467

kv.encode("temp_cache", tempData, MMKV.ExpireInHour);

468

469

// Retrieve binary data

470

byte[] storedText = kv.decodeBytes("text_data");

471

if (storedText != null) {

472

String restoredText = new String(storedText, "UTF-8"); // "Hello, MMKV!"

473

}

474

475

byte[] cachedImage = kv.decodeBytes("cached_image");

476

byte[] defaultBytes = new byte[]{0, 1, 2};

477

byte[] someData = kv.decodeBytes("unknown_data", defaultBytes);

478

```

479

480

### Parcelable Objects

481

482

Store and retrieve Android Parcelable objects.

483

484

```java { .api }

485

/**

486

* Store a Parcelable object.

487

* @param key The key for the value

488

* @param value The Parcelable object to store (can be null)

489

* @return True if successful, false otherwise

490

*/

491

public boolean encode(String key, Parcelable value);

492

493

/**

494

* Store a Parcelable object with expiration.

495

* @param key The key for the value

496

* @param value The Parcelable object to store

497

* @param expireDurationInSecond Expiration time in seconds

498

* @return True if successful, false otherwise

499

*/

500

public boolean encode(String key, Parcelable value, int expireDurationInSecond);

501

502

/**

503

* Retrieve a Parcelable object with default null.

504

* @param key The key for the value

505

* @param tClass The class of the Parcelable object

506

* @return The Parcelable object or null if not found

507

*/

508

public <T extends Parcelable> T decodeParcelable(String key, Class<T> tClass);

509

510

/**

511

* Retrieve a Parcelable object with custom default.

512

* @param key The key for the value

513

* @param tClass The class of the Parcelable object

514

* @param defaultValue The default value if key not found

515

* @return The Parcelable object or defaultValue if not found

516

*/

517

public <T extends Parcelable> T decodeParcelable(String key, Class<T> tClass, T defaultValue);

518

```

519

520

**Usage Example:**

521

522

```java

523

import android.graphics.Rect;

524

import android.graphics.Point;

525

526

// Store Parcelable objects

527

Rect bounds = new Rect(0, 0, 100, 200);

528

kv.encode("window_bounds", bounds);

529

530

Point location = new Point(50, 75);

531

kv.encode("cursor_position", location);

532

533

// Store with expiration

534

Bundle tempBundle = new Bundle();

535

tempBundle.putString("temp_key", "temp_value");

536

kv.encode("temp_bundle", tempBundle, MMKV.ExpireInMinute);

537

538

// Retrieve Parcelable objects

539

Rect storedBounds = kv.decodeParcelable("window_bounds", Rect.class);

540

if (storedBounds != null) {

541

int width = storedBounds.width(); // 100

542

int height = storedBounds.height(); // 200

543

}

544

545

Point cursorPos = kv.decodeParcelable("cursor_position", Point.class);

546

547

// With default value

548

Point defaultPoint = new Point(0, 0);

549

Point somePoint = kv.decodeParcelable("unknown_point", Point.class, defaultPoint);

550

```

551

552

## SharedPreferences Compatibility

553

554

MMKV implements the SharedPreferences interface for easy migration from Android SharedPreferences.

555

556

```java { .api }

557

// SharedPreferences.Editor methods

558

public Editor putString(String key, String value);

559

public Editor putStringSet(String key, Set<String> values);

560

public Editor putInt(String key, int value);

561

public Editor putLong(String key, long value);

562

public Editor putFloat(String key, float value);

563

public Editor putBoolean(String key, boolean value);

564

public Editor putBytes(String key, byte[] bytes); // MMKV extension

565

public Editor remove(String key);

566

public Editor clear();

567

568

// With expiration support (MMKV extensions)

569

public Editor putString(String key, String value, int expireDurationInSecond);

570

public Editor putStringSet(String key, Set<String> values, int expireDurationInSecond);

571

public Editor putInt(String key, int value, int expireDurationInSecond);

572

public Editor putLong(String key, long value, int expireDurationInSecond);

573

public Editor putFloat(String key, float value, int expireDurationInSecond);

574

public Editor putBoolean(String key, boolean value, int expireDurationInSecond);

575

public Editor putBytes(String key, byte[] bytes, int expireDurationInSecond);

576

577

// SharedPreferences methods

578

public String getString(String key, String defValue);

579

public Set<String> getStringSet(String key, Set<String> defValues);

580

public int getInt(String key, int defValue);

581

public long getLong(String key, long defValue);

582

public float getFloat(String key, float defValue);

583

public boolean getBoolean(String key, boolean defValue);

584

public byte[] getBytes(String key, byte[] defValue); // MMKV extension

585

public boolean contains(String key);

586

public Editor edit();

587

588

// Deprecated SharedPreferences methods (compatibility only)

589

public boolean commit(); // Use sync() instead

590

public void apply(); // Use async() instead

591

```

592

593

**Usage Example:**

594

595

```java

596

// Easy migration from SharedPreferences

597

MMKV kv = MMKV.defaultMMKV();

598

599

// SharedPreferences-style usage

600

kv.edit()

601

.putString("name", "John")

602

.putInt("age", 25)

603

.putBoolean("premium", true)

604

.apply(); // or commit()

605

606

// Retrieve values

607

String name = kv.getString("name", "");

608

int age = kv.getInt("age", 0);

609

boolean isPremium = kv.getBoolean("premium", false);

610

611

// MMKV extensions with expiration

612

kv.edit()

613

.putString("session_token", "abc123", MMKV.ExpireInHour)

614

.putInt("daily_count", 5, MMKV.ExpireInDay)

615

.apply();

616

```

617

618

### Native Buffer Operations

619

620

Advanced operations using native memory buffers for high-performance scenarios.

621

622

```java { .api }

623

/**

624

* Create a native buffer for direct JNI memory operations.

625

* @param size The size of the underlying memory

626

* @return NativeBuffer instance or null if creation failed

627

*/

628

public static NativeBuffer createNativeBuffer(int size);

629

630

/**

631

* Destroy a native buffer to avoid memory leaks.

632

* @param buffer The NativeBuffer to destroy

633

*/

634

public static void destroyNativeBuffer(NativeBuffer buffer);

635

636

/**

637

* Write the value of a key to the native buffer.

638

* @param key The key of the value to write

639

* @param buffer The native buffer to write to

640

* @return The size written, or -1 on error

641

*/

642

public int writeValueToNativeBuffer(String key, NativeBuffer buffer);

643

```

644

645

**Usage Example:**

646

647

```java

648

// Create a native buffer for high-performance operations

649

NativeBuffer buffer = MMKV.createNativeBuffer(1024); // 1KB buffer

650

if (buffer != null) {

651

try {

652

MMKV kv = MMKV.defaultMMKV();

653

kv.encode("test_data", "Hello, native buffer!");

654

655

// Write value directly to native memory

656

int bytesWritten = kv.writeValueToNativeBuffer("test_data", buffer);

657

if (bytesWritten > 0) {

658

Log.d("MMKV", "Wrote " + bytesWritten + " bytes to native buffer");

659

// Use the buffer for JNI operations...

660

}

661

} finally {

662

// Always destroy the buffer to prevent memory leaks

663

MMKV.destroyNativeBuffer(buffer);

664

}

665

}

666

```

667

668

### Key Expiration Features

669

670

Advanced features for automatic key expiration to manage data lifecycle.

671

672

```java { .api }

673

/**

674

* Enable auto key expiration with default duration.

675

* @param expireDurationInSecond Default expire duration for all keys, 0 means no default

676

* @return True if successful

677

*/

678

public boolean enableAutoKeyExpire(int expireDurationInSecond);

679

680

/**

681

* Disable auto key expiration.

682

* @return True if successful

683

*/

684

public boolean disableAutoKeyExpire();

685

```

686

687

**Usage Example:**

688

689

```java

690

MMKV kv = MMKV.defaultMMKV();

691

692

// Enable auto-expiration with 1 hour default for all new keys

693

boolean enabled = kv.enableAutoKeyExpire(MMKV.ExpireInHour);

694

if (enabled) {

695

// All new keys will expire in 1 hour unless overridden

696

kv.encode("auto_expire_key", "This will expire in 1 hour");

697

698

// Override with custom expiration

699

kv.encode("custom_expire_key", "This expires in 1 day", MMKV.ExpireInDay);

700

701

Log.d("MMKV", "Auto-expiration enabled");

702

}

703

704

// Later, disable auto-expiration

705

kv.disableAutoKeyExpire();

706

```

707

708

### Performance Optimization Features

709

710

Features for optimizing MMKV performance in specific scenarios.

711

712

```java { .api }

713

/**

714

* Enable data compare before set for better performance.

715

* Use when data for key seldom changes.

716

* Invalid when encryption or expiration is enabled.

717

*/

718

public void enableCompareBeforeSet();

719

720

/**

721

* Disable data compare before set.

722

*/

723

public void disableCompareBeforeSet();

724

```

725

726

**Usage Example:**

727

728

```java

729

MMKV kv = MMKV.defaultMMKV();

730

731

// Enable compare-before-set for performance optimization

732

// Only works with non-encrypted instances without expiration

733

try {

734

kv.enableCompareBeforeSet();

735

736

// Now MMKV will compare values before writing

737

// If the value is the same, it won't write to disk

738

kv.encode("stable_config", "value1");

739

kv.encode("stable_config", "value1"); // No actual write occurs

740

kv.encode("stable_config", "value2"); // Write occurs due to change

741

742

Log.d("MMKV", "Compare-before-set enabled for performance");

743

744

} catch (RuntimeException e) {

745

Log.e("MMKV", "Cannot enable compare-before-set: " + e.getMessage());

746

// This happens if encryption or expiration is enabled

747

}

748

749

// Disable when no longer needed

750

kv.disableCompareBeforeSet();

751

```

752

753

## Constants

754

755

```java { .api }

756

// Expiration time constants

757

public static final int ExpireNever = 0;

758

public static final int ExpireInMinute = 60;

759

public static final int ExpireInHour = 3600;

760

public static final int ExpireInDay = 86400;

761

public static final int ExpireInMonth = 2592000;

762

public static final int ExpireInYear = 946080000;

763

```