Android Export and Import Data
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 'com.google.code.gson:gson:2.8.9'
First, create a simple UI for the purpose of learning.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btnExport"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginStart="-6dp"
android:layout_marginTop="65dp"
android:layout_marginBottom="20dp"
android:text="Export"
android:textSize="20sp" />
<Button
android:id="@+id/btnImport"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btnExport"
android:layout_centerInParent="true"
android:text="Import"
android:textSize="20sp" />
</RelativeLayout>
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
true
} else {
//Permission is revoked
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
false
}
} else {
// Permission is automatically granted on sdk<23 upon installation
true
}
}
- 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
try {
// Instantiate the FileOutputStream object and pass myExternalFile in constructor
fos = FileOutputStream(myExternalFile)
// Write to the file
fos.write(jsonResponse?.toByteArray())
// Close the stream
fos.close()
} catch (e: IOException) {
e.printStackTrace()
}
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()) {
writeTextToFile(allJsonResponse)
}
}
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.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "*/*"
getDataFromFile.launch(intent)
}
- Read data from your JSON file
private fun readTextFromUri(uri: Uri): String {
var inputStream: InputStream? = null
val 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
stringBuilder.append(line).append('\n')
// Again read the next line and store in variable line
line = reader.readLine()
}
} catch (e: IOException) {
e.printStackTrace()
}
return stringBuilder.toString()
}
- Get your JSON data in your activity
private var getDataFromFile =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if (result.resultCode == RESULT_OK) {
val uri = result.data?.data
val fileContents = readTextFromUri(uri!!)
Toast.makeText(this@MainActivity, fileContents, Toast.LENGTH_SHORT).show()
}
}
- Use import button to restore your data
binding.btnImport.setOnClickListener {
openFileManager()
}
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