How to extract data from an JsonObject in an android studio project - android

I'm working on a REST API application in android studio. I want to extract the data from a JsonObject which I saved using the model class when retrieving data using retrofit library. But It shows the below error.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.covid_19updates, PID: 15236
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
Caused by: org.json.JSONException: No value for flag
at org.json.JSONObject.get(JSONObject.java:400)
at org.json.JSONObject.getJSONObject(JSONObject.java:620)
at com.example.covid_19updates.MainActivity$onCreate$1.onResponse(MainActivity.kt:52)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:89)
at retrofit2.-$$Lambda$DefaultCallAdapterFactory$ExecutorCallbackCall$1$hVGjmafRi6VitDIrPNdoFizVAdk.run(Unknown Source:6)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
The single data object I'm extracting is below:
{"updated":1606563124609,"country":"Afghanistan","countryInfo":{"_id":4,"iso2":"AF","iso3":"AFG","lat":33,"long":65,"flag":"https://disease.sh/assets/img/flags/af.png"},"cases":45966,"todayCases":127,"deaths":1752,"todayDeaths":12,"recovered":36709,"todayRecovered":414,"active":7505,"critical":93,"casesPerOneMillion":1170,"deathsPerOneMillion":45,"tests":146413,"testsPerOneMillion":3727,"population":39280785,"continent":"Asia","oneCasePerPeople":855,"oneDeathPerPeople":22421,"oneTestPerPeople":268,"activePerOneMillion":191.06,"recoveredPerOneMillion":934.53,"criticalPerOneMillion":2.37}
I want to retrieve data inside the countryInfo object. Below is my modal class
data class Covid(
var updated: Long,
var country:String,
var countryInfo:JSONObject,
var cases:Int,
var todayCases:Int,
var deaths:Int,
var todayDeaths:Int,
var recovered:Int,
var todayRecovered:Int,
var active:Int,
var critical:Int,
var casesPerOneMillion:Double,
var deathsPerOneMillion:Double,
var test:Long,
var testPerOneMillion:Double,
var population:Long,
var continent:String,
var oneCasePerPeople:Double,
var oneDeathPerPeople:Double,
var oneTestPerPeople:Double,
var activePerOneMillion:Double,
var recoveredPerOneMilion:Double,
var criticalPerOneMillion:Double
)
And the code piece I wrote to get the data
override fun onResponse(call: Call<List<Covid>>, response: Response<List<Covid>>) {
var list = response.body()
Log.d("Response: ",response.toString())
var countryList = ArrayList<String>()
var countList = ArrayList<String>()
var activeList = ArrayList<String>()
var deathList = ArrayList<String>()
var recoveredList = ArrayList<String>()
var imageList = ArrayList<String>()
list?.map { item ->
countryList.add(item.country.toString())
var totalCases = "Total Cases: "+item.cases.toString()
var activeCases = "Active Cases: "+item.active.toString()
var deaths = "Total Deaths: "+item.deaths.toString()
var recovered = "Total Recovered: "+item.recovered.toString()
var image = item.countryInfo.getJSONObject("flag").toString()
countList.add(totalCases)
activeList.add(activeCases)
deathList.add(deaths)
recoveredList.add(recovered)
}

Try and make a separate data class for CountryInfo.
In covid class
val countryInfo: CountryInfo,
Then
data class CountryInfo(
val _id: Int,
val iso2: String,
val iso3: String,
val lat: Double, //trust me you should use double on latLng values.
val long: Double,
val flag: String
)
Sidenote, you can use this site to automate making kotlin objects from JSONs.

Related

Why i can't update a realmObject that has a realmList inside it ? (I get an error)

I want to update a RealmObject that contains RealmList and I faced this error : (look at the images)
So why I faced this error? and what's the solution?
Also why RealmObject has duplicate parameters (image 2)
My code and the error are below
InvoiceModel :
open class PurchaseDatabase : RealmObject {
#PrimaryKey
var id: Int? = 0
var date: String? = ""
var supplier: String? = ""
var products: RealmList<ProductBuyModel> = realmListOf()
var totalPrice: Int? = 0
var paymentMethod: String? = ""
var paymentPrice: Int? = 0
var restPrice: Int? = 0
}
Error :
FATAL EXCEPTION: main
Process: com.bakirdev.gestiondestock, PID: 9705
java.lang.IllegalArgumentException: Cannot import an outdated object. Use findLatest(object) to find an
up-to-date version of the object in the given context before importing it.
at io.realm.kotlin.internal.RealmObjectListOperator.insert(RealmListInternal.k:370)
at io.realm.kotlin.internal.ListOperator$DefaultImpls.insertAll(RealmListInternal.kt:202)
at io.realm.kotlin.internal.BaseRealmObjectListOperator.insertAll(RealmListInternal.kt:258)
at com.bakirdev.gestiondestock.ui.purchases.PurchaseDatabase.setProducts(PurchaseDatabase.kt:150)
at com.bakirdev.gestiondestock.ui.purchases.AddNewInvoice$initListenerEdit$2$1.invoke(AddNewInvoice.kt:168)
at com.bakirdev.gestiondestock.ui.purchases.AddNewInvoice$initListenerEdit$2$1.invoke(AddNewInvoice.kt:162)
at io.realm.kotlin.internal.SuspendableWriter$write$2.invokeSuspend(SuspendableWriter.kt:109)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:236)
at android.os.HandlerThread.run(HandlerThread.java:67)
My Code :
var invoiceModel: PurchaseDatabase? = purchasesList[position]
realm.writeBlocking {
// fetch a frog from the realm by primary key
invoiceModel = this.query<PurchaseDatabase>("id == ${model.id}").first().find()
// modify the frog's age in the write transaction to persist the new age to the realm
invoiceModel?.supplier = purchasesSupplier
invoiceModel?.products?.clear()
invoiceModel?.products = products
invoiceModel?.totalPrice = totalPrice
invoiceModel?.paymentMethod = paymentMethod
invoiceModel?.paymentPrice = purchasesPaymentPrice.trim().toInt()
invoiceModel?.restPrice = purchasesRestPrice.trim().toInt()
}
Purchases.invoiceModel = invoiceModel
val returnedValue = Intent().apply {
putExtra("position", position)
}
setResult(RESULT_OK, returnedValue)
finish()

FlexboxLayoutManager throw an indexOutOfBoundException

We have a RecyclerView with a FlexboxLayoutManager witch throw an IndexOutOfBound on each scroll of the recyclerView.
FlexBox version: 2.0.1
Kotlin version: 1.4.30
Our code
C = EbookFlexController(this)
B.recycler.setItemViewCacheSize(10)
C.adapter.hasStableIds()
B.recycler.adapter = C.adapter
B.recycler.layoutManager = getFlexLayoutManager()
C represents the FlexBoxController
class FlexController(private val callbacks: Callbacks) : TypedEpoxyController<StreamCluster?>() {
interface Callbacks {
fun onAppClick(app: AppItem)
fun onAppLongClick(app: AppItem)
}
override fun buildModels(streamCluster: StreamCluster?) {
if (streamCluster == null) {
for (i in 1..8) {
add(
AppViewShimmerModel_()
.id(i)
)
}
} else {
streamCluster.appList.forEach { app ->
add(
AppViewModel_()
.id(app.packageName)
.click { _ ->
callbacks.onAppClick(app)
}
.longClick { _ ->
callbacks.onAppLongClick(app)
false
}
.app(app)
)
}
}
}
}
The stream Cluster
data class EbookStreamCluster(val id: String = UUID.randomUUID().toString()) {
var title: String = String()
var subtitle: String = String()
var category: String = String()
var url: String = String()
var ebookList: MutableList<EbookItem> = ArrayList()
var hasNext: Boolean = false
var isPaid:Boolean = false
var page: Int = 0
var type: Type = Type.CLUSTER
}
On firebase, we have this error:
Process: com.gara.store, PID: 3655
java.lang.IndexOutOfBoundsException: Index: 18, Size: 18
at java.util.ArrayList.get(ArrayList.java:437)
at com.google.android.flexbox.FlexboxLayoutManager.recycleFlexLinesFromStart(FlexboxLayoutManager.java:1335)
at com.google.android.flexbox.FlexboxLayoutManager.recycleByLayoutState(FlexboxLayoutManager.java:1315)
at com.google.android.flexbox.FlexboxLayoutManager.fill(FlexboxLayoutManager.java:1302)
at com.google.android.flexbox.FlexboxLayoutManager.handleScrollingMainOrientation(FlexboxLayoutManager.java:1974)
at com.google.android.flexbox.FlexboxLayoutManager.scrollVerticallyBy(FlexboxLayoutManager.java:1935)
at androidx.recyclerview.widget.RecyclerView.scrollStep(RecyclerView.java:1972)
at androidx.recyclerview.widget.RecyclerView$ViewFlinger.run(RecyclerView.java:5476)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1037)
at android.view.Choreographer.doCallbacks(Choreographer.java:845)
at android.view.Choreographer.doFrame(Choreographer.java:775)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1022)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7870)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
The same lib is used somewhere in the app and works without bugs. We don't know why with the exact same code, it is not working.
Please how could we do ?
Thanks

http request in android kotlin

I try to get JSON or something like this, using URL.readText() from java.net.url in android studio, but my app crashes.
fun ButtonClick(view:View) {
textView.text = URL("https://www.google.com/robots.txt").readText()
}
I also added this into manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
but it crashes anyway
please, help me! what am i doing wrong?. I think it's ok to get text from url, using url.readText, because some guy in this post HTTP Request in Kotlin wrote that it's simpler
crash log:
2020-08-17 23:16:04.117 2251-2251/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 2251
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:5637) 
at android.view.View$PerformClick.run(View.java:22429) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
at java.net.InetAddress.getAllByName(InetAddress.java:752)
at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:187)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:156)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:98)
at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:345)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:328)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:405)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:243)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
at java.net.URL.openStream(URL.java:1057)
at kotlin.io.TextStreamsKt.readBytes(ReadWrite.kt:150)
at com.example.myapplication.MainActivity.ButtonClick(MainActivity.kt:25)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409) 
at android.view.View.performClick(View.java:5637) 
at android.view.View$PerformClick.run(View.java:22429) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
Based on what limited info you have provided, you might be having a NetworkOnMainThreadException wrap your code in a thread for it to work
fun ButtonClick(view:View){
thread {
val response = URL("https://www.google.com/robots.txt").readText()
activity?.runOnUiThread{
textView.text = response
}
}
}
I was have this problem and I wasn't fix it
but now I using Volley in android and it is really powerful and easy
I suggest you to work with Volley
you should use from Retrofit in your codes
1- Add the following lines in the app level build.gradle file to apply Google Services to your project
dependencies {
...
Implementation 'org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version'
implementation 'com.squareup.retrofit2:retrofit:2.0.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.0'
}
2-Then, click “Sync Now” to set up your project.
3- Don't forget to add the following permissions in your manifest file
<uses-permission android:name="android.permission.INTERNET"/>
4- Create an interface file named as “WeatherService.kt” and add the following lines in it
interface WeatherService {
#GET("data/2.5/weather?")
fun getCurrentWeatherData(#Query("lat") lat: String, #Query("lon") lon: String,
#Query("APPID") app_id: String): Call<WeatherResponse>
}
5-Create a class file named as “WeatherResponse.kt” and add the following lines. Here, we used a Gson Converter and so the JSON response is automatically converted to the respective and the converter will compare the response tree with the serialized name.
class WeatherResponse {
#SerializedName("coord")
var coord: Coord? = null
#SerializedName("sys")
var sys: Sys? = null
#SerializedName("weather")
var weather = ArrayList<Weather>()
#SerializedName("main")
var main: Main? = null
#SerializedName("wind")
var wind: Wind? = null
#SerializedName("rain")
var rain: Rain? = null
#SerializedName("clouds")
var clouds: Clouds? = null
#SerializedName("dt")
var dt: Float = 0.toFloat()
#SerializedName("id")
var id: Int = 0
#SerializedName("name")
var name: String? = null
#SerializedName("cod")
var cod: Float = 0.toFloat()
}
class Weather {
#SerializedName("id")
var id: Int = 0
#SerializedName("main")
var main: String? = null
#SerializedName("description")
var description: String? = null
#SerializedName("icon")
var icon: String? = null
}
class Clouds {
#SerializedName("all")
var all: Float = 0.toFloat()
}
class Rain {
#SerializedName("3h")
var h3: Float = 0.toFloat()
}
class Wind {
#SerializedName("speed")
var speed: Float = 0.toFloat()
#SerializedName("deg")
var deg: Float = 0.toFloat()
}
class Main {
#SerializedName("temp")
var temp: Float = 0.toFloat()
#SerializedName("humidity")
var humidity: Float = 0.toFloat()
#SerializedName("pressure")
var pressure: Float = 0.toFloat()
#SerializedName("temp_min")
var temp_min: Float = 0.toFloat()
#SerializedName("temp_max")
var temp_max: Float = 0.toFloat()
}
class Sys {
#SerializedName("country")
var country: String? = null
#SerializedName("sunrise")
var sunrise: Long = 0
#SerializedName("sunset")
var sunset: Long = 0
}
class Coord {
#SerializedName("lon")
var lon: Float = 0.toFloat()
#SerializedName("lat")
var lat: Float = 0.toFloat()
}
6- Then, open your Activity file and in my case, I have opened my MainActivity.kt file. Then, create a Retrofit Builder with Base URL and GsonConverterFactory.
val retrofit = Retrofit.Builder()
.baseUrl(BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()
7-Then, create a service for Retrofit with your service interface, as shown below
val service = retrofit.create(WeatherService::class.java)
val call = service.getCurrentWeatherData(lat, lon, AppId)
Here, “getCurrentWeatherData” is an interface function created in the “WeatherService” interface.
8-Then, create a queue with Weather Response which is used to de-serialize the JSON output of the Open Weather API. The following will show the created queue.
call.enqueue(object : Callback<WeatherResponse> {
override fun onResponse(call: Call<WeatherResponse>, response:
Response<WeatherResponse>) {
if (response.code() == 200) {
…
}
}
override fun onFailure(call: Call<WeatherResponse>, t: Throwable) {
…
}
})
variables defined :
companion object {
var BaseUrl = "http://api.openweathermap.org/"
var AppId = "2e65127e909e178d0af311a81f39948c"
var lat = "35"
var lon = "139"
}

Kotlin Firebase Realtime database transaction errors

I have the following code
database.child("users").child(this.invitedBy).runTransaction(object : Transaction.Handler {
override fun doTransaction(mutableData: MutableData): Transaction.Result {
val u = mutableData.getValue(User::class.java)
?: return Transaction.success(mutableData)
if (u.numReferrals == null || u.referralEarning == null) {
// Unstar the post and remove self from stars
u.numReferrals = 1
u.referralEarning = 1;
} else {
// Star the post and add self to stars
u.numReferrals = u.numReferrals!! + 1
u.referralEarning = u.referralEarning!! + 1;
}
// Set value and report transaction success
mutableData.value = u
return Transaction.success(mutableData)
}
override fun onComplete(
databaseError: DatabaseError?,
committed: Boolean,
currentData: DataSnapshot?
) {
// Transaction completed
Log.d("MUser", "postTransaction:onComplete:" + databaseError!!)
}
})
When I run it, it gives me the following error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.test.test, PID: 5375
kotlin.KotlinNullPointerException
at com.test.test.MUser$setReferral$1.onComplete(MUser.kt:229)
at com.google.firebase.database.core.Repo$16$1.run(com.google.firebase:firebase-database##19.2.1:1006)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7478)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
W/System.err: kotlin.KotlinNullPointerException
W/System.err: at com.test.test.MUser$setReferral$1.onComplete(MUser.kt:229)
at com.google.firebase.database.core.Repo$16$1.run(com.google.firebase:firebase-database##19.2.1:1006)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7478)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
Here's my User.kt
import com.google.firebase.database.IgnoreExtraProperties
// [START rtdb_user_class]
#IgnoreExtraProperties
data class User(
var id: String = "",
var name: String = "",
var email: String = "",
var userReads: Int? = 0,
var userPlays: Int? = 0,
var userWatches: Int? = 0,
var paidDate : Int? = 0,
var endPaidDate : Int? = 0,
var paidStatus : String? = "",
var paymentMethod : String? = "",
var planid : String? = "",
var firebaseUid : String? = "",
var referralEarning : Int? = 0,
var numReferrals : Int? = 0
)
What am I doing wrong?
Please take a look at onComplete method:
override fun onComplete(
databaseError: DatabaseError?,
committed: Boolean,
currentData: DataSnapshot?
) {
// Transaction completed
Log.d("MUser", "postTransaction:onComplete:" + databaseError!!)
}
You are using !! operator when referencing databaseError parameter, but it can be null, so you can't use !!. To avoid that Exception just remove !! operator:
Log.d("MUser", "postTransaction:onComplete:" + databaseError)
databaseError: DatabaseError? - it is a nullable object (nullable objects marked with ? operator), you can't use !! operator on it if you are not 100% sure that it is not null.
Also you can use ? operator on nullable objects to call its methods or properties, e.g.:
Log.d("MUser", "postTransaction:onComplete:" + databaseError?.getMessage())
More info about Null Safety in Kotlin.

java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.xxx.xxx.xxx.model.CategoryModel)

I am passing a list of model from one fragment A to another fragment B, when when i press recent app button on fragment B it crashed.
data class CategoryModel(
#SerializedName("id")
val id : Int,
#SerializedName("name")
val categoryName : String,
var isSelected : Boolean,
#SerializedName("image")
val imageUrl : String,
var isOpened: Boolean = false,
#SerializedName("service")
val services : MutableList<ServiceModel>,
var selectedServiceListAdapter: SelectedSeerviceListRecyclerAdapter? = null) : Serializable
and this is fragment A :
the list is
val localCategoryList: MutableList<CategoryModel> = arrayListOf()
and i am passing the list below :
val argument = bundleOf("list" to localCategoryList)
findNavController(this).navigate(R.id.action_categoryFragment_to_serviceListFragment, argument)
and in fragment B :
categoryList = arguments?.get("list") as MutableList<CategoryModel>
below are the stack trace
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.xxx.xxx.xxx.model.CategoryModel)
at android.os.Parcel.writeSerializable(Parcel.java:1394)
at android.os.Bundle.writeToParcel(Bundle.java:1034)
at android.os.Parcel.writeBundle(Parcel.java:669)
at androidx.fragment.app.FragmentState.writeToParcel(FragmentState.java:167)
at android.os.Parcel.writeTypedList(Parcel.java:1112)
at androidx.fragment.app.FragmentManagerState.writeToParcel(FragmentManagerState.java:51)
androidx.fragment.app.FragmentManagerState.writeToParcel(FragmentManagerState.java:51)
at android.os.Parcel.writeBundle(Parcel.java:669)
at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3270)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.io.NotSerializableException: com.xxxx.xxxx.xxxx.view.activities.ProviderDetailsActivity
at
java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1461)
at android.os.Parcel.writeSerializable(Parcel.java:1389)
at android.os.Parcel.writeValue(Parcel.java:1341) 
at androidx.fragment.app.FragmentState.writeToParcel(FragmentState.java:169) 
at android.os.Parcel.writeTypedList(Parcel.java:1112) 
at androidx.fragment.app.FragmentManagerState.writeToParcel(FragmentManagerState.java:51) 
at android.os.Parcel.writeParcelable(Parcel.java:1363) 
at android.os.Parcel.writeValue(Parcel.java:1268) 
at android.os.Parcel.writeArrayMapInternal(Parcel.java:644) 
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1313) 
at android.os.Bundle.writeToParcel(Bundle.java:1034) 
at android.os.Parcel.writeBundle(Parcel.java:669) 
at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3270) 
at android.app.ActivityThread$StopInfo.run(ActivityThread.java:4385) 
at android.os.Handler.handleCallback(Handler.java:739) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 
You need to parcelable data class like below example
Parcelize
data class WebViewTemplateParam(
var type:FeedsType?,
var placeholder: String = "",
var message: String = "",
var title: String? = "",
var image: Int?= null):Parcelable

Categories

Resources