Last active
December 1, 2021 08:14
-
-
Save labibmuhajir/9dd109bb690c7365a87ed502520d4de0 to your computer and use it in GitHub Desktop.
read big json file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context | |
import android.net.Uri | |
import androidx.hilt.work.HiltWorker | |
import androidx.work.* | |
import com.google.gson.Gson | |
import com.google.gson.stream.JsonReader | |
import dagger.assisted.Assisted | |
import dagger.assisted.AssistedInject | |
import kotlinx.coroutines.Dispatchers | |
import kotlinx.coroutines.withContext | |
import java.io.BufferedReader | |
import java.io.InputStreamReader | |
@HiltWorker | |
class JsonWorker @AssistedInject constructor( | |
@Assisted val context: Context, | |
@Assisted parameters: WorkerParameters, | |
private val repository: Repository | |
) : CoroutineWorker(context, parameters) { | |
companion object { | |
const val URI_DATA = "uri_data" | |
fun runOnce(context: Context, uri: String) { | |
val data = Data.Builder().putString(URI_DATA, uri).build() | |
val syncWork = OneTimeWorkRequestBuilder<JsonWorker>() | |
.setInputData(data) | |
.addTag("JsonWorker") | |
.build() | |
WorkManager.getInstance(context).enqueueUniqueWork( | |
"JsonWorker", | |
ExistingWorkPolicy.KEEP, | |
syncWork | |
) | |
} | |
} | |
override suspend fun doWork(): Result { | |
return withContext(Dispatchers.Default) { | |
var reader: JsonReader? = null | |
try { | |
val data = inputData.getString(URI_DATA) | |
val uri = Uri.parse(data) | |
val inputStream = context.contentResolver.openInputStream(uri) ?: throw Exception() | |
reader = JsonReader(InputStreamReader(inputStream, Charsets.UTF_8)) | |
val yourObject = mutableListOf<YourObject>() | |
reader.beginArray() | |
val gson = Gson() | |
while (reader.hasNext()) { | |
yourObject.add(gson.fromJson(reader, YourObject::class.java)) | |
} | |
reader.endArray() | |
reader.close() | |
repository.save(yourObject) | |
Result.success() | |
} catch (e: Exception) { | |
e.printStackTrace() | |
Result.failure() | |
} finally { | |
try { | |
reader?.close() | |
} catch (e: Exception) { | |
e.printStackTrace() | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment