6 Things I Wish I Knew When I Wrote My First Android App

6 Things I Wish I Knew When I Wrote My First Android App

My first app was terrible. In fact, it was so terrible that I pulled it from the store and I don't even bother listing it on my resume anymore. If I had known a little bit about Android development before I wrote it, that app wouldn't have been so terrible.

Here’s a list of things to keep in mind when writing your first Android app. These lessons are real mistakes I made when writing the source code for my first app. I’ll show you what those mistakes are later. Keeping these things in mind will help you write an app you can be a little proud of.

Of course, if you’re doing the right job as an Android development student, you’ll probably hate the apps you wrote soon anyway, and as @codestandards says, if the code you wrote a year ago doesn’t make you feel uncomfortable, you probably haven’t learned much.

If you are an experienced Java developer, items 1, 2, and 5 may not interest you. On the other hand, items 3 and 4 may show you some cool stuff that you may not know yet.
Don’t have static references to Contexts

  1. public   class MainActivity extends LocationManagingActivity implements ActionBar.OnNavigationListener,
  2. GooglePlayServicesClient.ConnectionCallbacks,
  3. GooglePlayServicesClient.OnConnectionFailedListener {
  4.  
  5. //...  
  6.  
  7. private   static MeTrackerStore mMeTrackerStore;
  8.  
  9. //...  
  10.  
  11. @Override  
  12. protected   void onCreate(Bundle savedInstanceState) {
  13. //...  
  14.  
  15. mMeTrackerStore = new MeTrackerStore( this );
  16. }
  17. }

This may seem like an impossible mistake to make for anyone. But it is not. I have made it. I have seen other people make it, and I have seen many people who cannot immediately figure out why it is a mistake. Don't do it. It is a noob move.

If MeTrackerStore holds a reference to the Activity when it is passed into its constructor, the Activity will still not be garbage collected (unless the static variable is reassigned to another Activity). This is because mMeTrackerStore is static, and the memory of static variables is not reclaimed until the running process of the program is stopped. If you find yourself trying to do this, there is probably something seriously wrong with your code. For help, check out Google's Udacity course "Android Development for Beginners"

Note: Technically, you can hold a static reference to the Context without causing a memory leak, but I would not recommend it.
Beware of implicit references to objects whose lifetime you do not control

  1. public   class DefineGeofenceFragment extends Fragment {
  2. public   class GetLatAndLongAndUpdateMapCameraAsyncTask extends AsyncTask<String, Void, LatLng> {
  3.  
  4. @Override  
  5. protected LatLng doInBackground(String... params) {
  6. //...  
  7. try {
  8. //Here we make the http request for the place search suggestions  
  9. httpResponse = httpClient.execute(httpPost);
  10. HttpEntity entity = httpResponse.getEntity();
  11. inputStream = entity.getContent();
  12. //..  
  13. }
  14. }
  15. }
  16.  
  17.  
  18. }

There are many problems with this code, but I will focus on one of them. In Java, a non-static inner class has an implicit reference to the class object that contains it.

In this example, any GetLatAndLongAndUpdateMapCameraAsyncTask object will have a reference to the DefineGeofenceFragment object. The same is true for anonymous classes: they will have an implicit reference to the class object that contains them.

This GetLatAndLongAndUpdateMapCameraAsyncTask object has an implicit reference to the Fragment object, an object whose lifecycle we have no control over. The Android SDK is responsible for creating and destroying Fragment objects appropriately, and if the GetLatAndLongAndUpdateMapCameraAsyncTask object cannot be recycled because it is executing, then the objects it holds cannot be recycled either.

Here’s a great Google IO video explaining why this happens
Make Android Studio work for you

  1. public ViewPager getmViewPager() {
  2. return mViewPager;
  3. }

This snippet is what Android Studio generated for me when I used the "Generate Getter" code completion. The getter method keeps the 'm' prefix for this instance variable. This is not ideal.

(Also, you must be wondering why instance variables are prefixed with an 'm': this 'm' is often used as a prefix for instance variables. It stands for 'member'.)

Regardless of whether you think it's a good idea to prefix your instance variables with 'm', here's a rule of thumb: Android Studio can help you write code in the manner you develop. For example, you can use the Code Style box in Android Studio to have Android Studio automatically add 'm' to your instance variables and automatically remove 'm' when it generates getters, setters, and constructor parameters.

Android Studio can do a lot of things, and learning shortcuts and activity templates is a good start.
Methods should do only one thing

I had a method that was over 1000 lines long. Such methods are hard to read, modify, and reuse. Try to write methods that do just one thing. Typically, this means you should be suspicious of any code you write that is over 20 lines long. Here’s where you can recruit Android Studio to help you point out problematic methods:

Learn from people who are smarter and more experienced than you

This may not seem important, but it was a mistake I made when I wrote my first app.

When you are writing programs, you will make mistakes. Other people have already made those mistakes. Learn from others. If you repeat avoidable mistakes, you are wasting your time.

Read Pragmatic Programmer. Then read Effective Java. These two books will help you avoid making some common mistakes. After you finish reading these two books, keep learning from smart people.
Using the Library

When you write an app, you may encounter a problem that has already been solved by someone else. Moreover, a large number of solutions are open as libraries. Take advantage of them.

In my first app, the functionality I wrote was already provided by other libraries, some of which are part of standard Java. Others are libraries like Retrofit and Picasso. If you are not sure what library you should use, there are three things you can do:

1. Listen to Google IO Fragmented podcast episode
2. Subscribe to Android Weekly
3. Look for open source applications that solve similar problems. You may find that they use third-party libraries or standard Java libraries that you don't care about.
Summarize

Writing a good Android app is hard. Don't make it harder by repeating my mistakes.

<<:  Remember! Do not perform time-consuming operations in the UI main thread

>>:  Learn more about iOS 9 every day 5: Xcode Code Coverage Tools

Recommend

A collection of 10 classic cases of growth hacking, including To C and To B

Since Sean Ellis proposed the concept of Growth H...

3 major elements to create addictive products and brands!

Everyone's persistent pursuit and unremitting...

Analysis of Xiaomi’s advertising and marketing!

Xiaomi has struck a very delicate balance between...

Nature sub-journal: Subverting cognition! Do we really need to be "brainwashed"?

Produced by: Science Popularization China Author:...

A small breeze shakes a big bridge, how can it turn into a storm?!

A small breeze shakes a big bridge, how can it tu...

12 golden rules for designing e-commerce operation tools

Although the tool itself is not easy to share, it...

7 Benefits of Data Visualization

Data visualization refers to the presentation of ...

The Duolingo team’s Swift coding practices

[[127033]] We recently released a new Swift-based...

Does Douyin Blue V need a business license? How to authenticate Blue V?

Douyin is a platform dedicated to publishing and ...