如何在我的活动中存储来自API的数据

时间:2019-08-24 13:03:40

标签: android kotlin

我从api获取json数据,然后使用gson将其转换为数据类 我想要的是:

1-存储数据以减少对api的Http请求并具有刷新数据的功能
2-在其他活动中访问数据

我已经尝试过:

1-将具有Intent的数据传递给第二个活动,它可以工作,但是当我回到主要活动时,我必须执行另一个Http请求以获取数据

2-使用onSaveInstanceStateonRestoreInstanceState存储数据类对象,但是当我回到主要活动时onRestoreInstanceState从未得到呼叫

class carView : AppCompatActivity() {
    val TAG = "Volly"
    lateinit var dataObject : Bundle
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_car_view)

        if(savedInstanceState == null){
            getData()
        }else{
            dataObject.putSerializable("all_cars",savedInstanceState.getSerializable("all_cars"))
        }
        Log.i(TAG," the object is $dataObject")

        recycler_View.layoutManager = LinearLayoutManager(this)
        recycler_View.adapter = mainAdapter(dataObject.getSerializable("all_cars") as Cars)
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
        super.onRestoreInstanceState(savedInstanceState)
        Log.i(TAG,"onRestoreInstanceState")

        val Object = savedInstanceState?.getSerializable("all_cars") as Cars
        recycler_View.adapter = mainAdapter(Object)
        Log.i(TAG,"Object is ${Object}")
    }
    override fun onSaveInstanceState(outState: Bundle?) {
        super.onSaveInstanceState(outState)
        Log.i(TAG,"onSaveInstanceState")
        val Object = intent.extras?.get("Extra_object") as Cars
        outState?.putSerializable("all_cars",Object)

    }
    fun getData(){
        val url = "http://192.168.1.100:5000/car/getCars"
        val oRequest = object : StringRequest(
            Request.Method.GET,
            url,
            Response.Listener { response ->
                try {
                    val gson = GsonBuilder().create()
                    val result = gson.fromJson(response,Cars::class.java)
                    Log.i(TAG,"the list ${result}")
                    dataObject.putSerializable("all_cars",result)

                }catch (e : JSONException){
                    e.printStackTrace()
                }
            },
            Response.ErrorListener { err ->
                Log.i(TAG,"err {$err}")
            }){

        }
        oRequest.retryPolicy = DefaultRetryPolicy(20* 1000 , 0 , DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)
        val requestQ = Volley.newRequestQueue(this)
        requestQ.add(oRequest)

    }

}
data class Cars(val cars:List<CarModel>?) : Serializable
data class CarModel(
    var _id     : String,
    var name    : String,
    var ownerId : String,
    var image   : String
//    var profile: List<imageData>
) : Serializable

2 个答案:

答案 0 :(得分:1)

从API获取数据后,以共享首选项存储数据,然后在onCreate中编写代码以使用共享首选项获取以前存储的数据。现在,每当您的活动开始时,检查数据是否在共享首选项中可用是否可用将其发送到第二个活动(如果不可用),然后进行API调用。

答案 1 :(得分:1)

使用共享的首选项

Kotlin保存信息的示例

val name = getName()
val surname = getSurname()
val saved = isSaved()

val preferences = getSharedPreferences("DATA", Context.MODE_PRIVATE)
val preferencesEditor = preferences.edit()
preferencesEditor.putBoolean("saved", saved)
preferencesEditor.putString("name", name)
preferencesEditor.putString("surname", surname)
preferencesEditor.apply()

Kotlin获取信息的示例

val preferences = getSharedPreferences("DATA", Context.MODE_PRIVATE)
val saved = preferences.getBoolean("saved", false /*Default value*/)