August 29, 2013
Things I wish I knew about Android before starting my first Android app
Activities lose state when the screen rotates, but Views don’t
All those member variables/fields you set while a user interacts with an activity are going to become null when the user rotates their screen. However, the views being managed by your activity will preserve themselves – whether they were visible, what text set in them, and some other properties. To preserve the info that will be lost to the screen rotation, store information by overriding public void onSaveInstanceState(Bundle outState)
, and restore it by pulling out out of the bundle passed into public void onCreate(Bundle instanceBundle)
.
Saving member variable mSomeValue
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("myKey", mSomeValue);
}
Restoring it next time the activity is created (such as after a rotation)
@Override
public void onCreate(Bundle instanceBundle) {
super.onCreate(instanceBundle);
/* more of your code here */
mSomeValue = instanceBundle.getSerializable("myKey")
}
Network Requests
A bunch of people already figured out the best way to deal with queuing, retries, parsing, and keeping that stuff off the UI thread. Here’s a video on one library by a Google Play team member that was used in the official Google Play app – Volley. There are other libraries and structures that can help like ones described in this talk on REST requests
There’s something for making settings menus
It’s called PreferencesActivity and it will probably save you some time.
Try an Intent Service
The quickest way to get other operations out of the main thread? Cut synchronous code out of an activity or service, and paste it into an IntentService. Launch the IntentService with an Intent. Pass dependencies into the Intent Service inside the Intent’s extras.
XML Parsing Options
XPath is easy for the developer, but slow on the device. There are at least 2 other parsers that come with the Android and Java to look into.
Google Recommends the XmlPullParser. And this guy benchmarked these and other XML parsers.