Nerd For Tech
Published in

Nerd For Tech

Android Export and Import Data

Export/Import Data in JSON format

One of the highly-important things which occupy our mind concerning data is not to lose it at all. We have to back up our data to restore it when we need them. So, we need to know how to push the data to the device’s SD memory. In this article, we will figure out how to import and export data from and to JSON files.

Let’s get started

To export and import data, we will use Gson Library. It is a Java library that converts Java Objects into their JSON representation. Also, It converts a JSON string to an equivalent Java object.

To set it up:

implementation ''

First, create a simple UI for the purpose of learning.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""



Then, let’s get back to code.

1. Export Data to JSON file

Usually, we get the data from a certain data source like Room, Realm , Firebase or any other one.

In our example, we will create fake data. It will be two lists of customers and employees.

  • Create Customer class
class Customer(var name: String, var job: String, var overDue: Float)
  • Create Employee class
class Employee(var nameEmployee: String, var jobEmployee: String)
  • Create Data class for storing both lists
class Data(val customers: List<Customer>, val employees: List<Employee>)
  • Create two lists with dummy data
val customers = ArrayList<Customer>()
customers.add(Customer("Hala", "developer", 34.5f))
customers.add(Customer("Nora", "teacher", 43.5f))
customers.add(Customer("Rana", "doctor", 56.5f))

val employees = ArrayList<Employee>()
employees.add(Employee("ALi", "carpenter"))
employees.add(Employee("Yaser", "mechanic"))
  • Initialize Gson Object and make it global to be able to reach it
private var gson: Gson? = nullgson = GsonBuilder().serializeNulls().setPrettyPrinting().create()
  • Convert classes to JSON format
private fun convertClassToJson(customers: List<Customer>, employees: List<Employee>): String? {
val allData = Data(customers, employees)
return gson?.toJson(allData)
  • Add permissions for writing and reading data
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  • Check if Storage Permission is granted.
private fun isStoragePermissionGranted(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
//Permission is granted
} else {
//Permission is revoked
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
} else {
// Permission is automatically granted on sdk<23 upon installation
  • Get a random file name instead of overriding the same one
private fun getRandomFileName(): String {
return Calendar.getInstance().timeInMillis.toString() + ".json"
  • Write Data To JSON File
private fun writeTextToFile(jsonResponse: String?) {
if (jsonResponse != "") {
// Create a File object like this.
val dir = File("//sdcard//Download//")
val myExternalFile = File(dir, getRandomFileName())
// Create an object of FileOutputStream for writing data to myFile.txt
var fos: FileOutputStream? = null
// Instantiate the FileOutputStream object and pass myExternalFile in constructor
fos = FileOutputStream(myExternalFile)
// Write to the file
// Close the stream
} catch (e: IOException) {
Toast.makeText(this@MainActivity, "Information saved to SD card. $myExternalFile", Toast.LENGTH_SHORT).show()
  • Use export button to back up your data
binding.btnExport.setOnClickListener {
if (isStoragePermissionGranted()) {

Now, your data is exported to a JSON file found in the download folder on your phone.

2. Import Data from JSON file

  • Open File Manager to choose the JSON file you want to import
private fun openFileManager() {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.type = "*/*"
  • Read data from your JSON file
private fun readTextFromUri(uri: Uri): String {
var inputStream: InputStream? = null
stringBuilder = StringBuilder()
try {
inputStream = contentResolver.openInputStream(uri)
val reader = BufferedReader(InputStreamReader(inputStream))

// Read a line of text.
var line = reader.readLine()
// Read the entire file
while (line != null) {
// Append the line read to StringBuilder object. Also, append a new-line
// Again read the next line and store in variable line
line = reader.readLine()
} catch (e: IOException) {
return stringBuilder.toString()
  • Get your JSON data in your activity
private var getDataFromFile =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
(result.resultCode == RESULT_OK) {
val uri =
val fileContents = readTextFromUri(uri!!)
Toast.makeText(this@MainActivity, fileContents, Toast.LENGTH_SHORT).show()
  • Use import button to restore your data
binding.btnImport.setOnClickListener {

Congrats, your data is imported from a JSON file, and you can now insert it in your database or use it in any way suitable for your application’s purpose.

For Sample App on GitHub, click BackupData. Also, this feature is implemented in My app Wordi. Get it through Google Play

For more Articles: Click Here

Find me here: GitHub | LinkedIn | Twitter




NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit

Recommended from Medium

Android: End of WiFi?

Binder Introduction

Flutter Hero widget and Bloc error

Support Android App Bundle

Flutter Analysis and Practice: Hybrid Projects and Continuous Integration

Trackr comes to the Big Screen

Running containerized android tests in GCP using Pulumi and Selenoid

Automatically turn wifi off with Tasker

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Marwa Eltayeb

Marwa Eltayeb

Android Developer

More from Medium

Lost in Java Time with Android

The Basics of Android Unit Testing

Testing in Android