[英]Using onSaveInstanceState to prevent network call a second time
In my OnCreate method I am making a network call and populating a listview with the results. 在我的OnCreate方法中,我进行了网络调用,并在列表中填充了结果。 I am saving the result in an ArrayList and using the ArrayList to populate the listview.
我将结果保存在ArrayList中,并使用ArrayList填充listview。 If the user presses the back button and reenters the activity I would like to store the ArrayLists in a SavedInstanceState Bundle and populate the ListView with the stored ArrayLists instead of making the network call a second time.
如果用户按下后退按钮并重新输入活动,我想将ArrayLists存储在SavedInstanceState Bundle中,并用存储的ArrayLists填充ListView,而不是第二次进行网络调用。 The following is my OnCreate code:
以下是我的OnCreate代码:
if (savedInstanceState != null) {
largeImage = savedInstanceState.getParcelableArrayList("Image");
flowercode = savedInstanceState.getStringArrayList("Code");
flowerprice = savedInstanceState.getStringArrayList("Price");
flowerdimensions = savedInstanceState.getStringArrayList("Dimension");
largeImageText = savedInstanceState.getStringArrayList("Imagetext");
ListView listView = (ListView) findViewById(R.id.LowRomance);
FlowerShopAdapter listAdapter = new FlowerShopAdapter(this, flowercode, flowerName, flowerprice, largeImage, flowerdimensions);
listView.setAdapter(listAdapter);
} else if(savedInstanceState == null) {
makesoapcall();
}
}
This is my OnSaveInstanceState code 这是我的OnSaveInstanceState代码
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putParcelableArrayList("Image", largeImage);
savedInstanceState.putStringArrayList("Code", flowercode);
savedInstanceState.putStringArrayList("Price", flowerprice);
savedInstanceState.putStringArrayList("Dimension", flowerdimensions);
super.onSaveInstanceState(savedInstanceState);
}
Currently my App is making the network call every single time. 目前,我的App每次都在进行网络通话。 Is their something else I need to implement in order to get this to work or is their an error in the current way I am trying to implement this?
为了使它正常工作,我需要实现其他功能吗?还是在我尝试实现此功能的当前方式中存在错误? The ArrayList's are definitely not null when I put them into savedInstanceState.
当我将ArrayList放入saveInstanceState时,绝对不是null。
onSaveInstanceState()
is not supposed to be called when the back button is pressed on an Activity. 在活动上按下后退按钮时,不应调用
onSaveInstanceState()
。 It's called when Android decides to destroy the Activity. 当Android决定销毁Activity时调用。
eg When orientation changes. 例如,当方向改变时。
What you need here is SharedPreferences . 您这里需要的是SharedPreferences 。 Store the
ArrayLists
using SharedPreferences in onStop()
. 使用
onStop()
SharedPreferences存储ArrayLists
。 And get it in onStart()
. 并在
onStart()
获取它。 Here is how to store ArrayList in SharedPreferences. 这是在SharedPreferences中存储ArrayList的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.