How to Run an Android App against a localhost API

Last week, when working on the new release of the eat foody Android app, I run into a significant issue. For some reason, my requests to our staging API were incomplete or somehow broken after updating to the newest version of our request library. After some rather clueless digging I knew I needed to run the broken requests against a debuggable server environment. This allows me to compare how the request leaves the Android app and arrives at the server. In my case, the local API endpoints were at http://localhost:3000/api.

Before googling the issue I attempted to change the code of eat foody’s Android app to run against http://localhost:3000/api. However, this rather obvious choice does not work, since localhost is the Android emulator or the device itself. The next two sections will describe solutions for making requests to your localhost server.

Case 1: If You Are Using the Emulator

The bad news first: this solution only work with the emulator and not with your actual devices. So start up your emulator (since it could take a while until it is ready). Start your server at localhost and attach the debugger. Next, change the API endpoints in your Android code to http://10.0.2.2. This reroutes the requests from your emulator to your computer’s localhost. Run the Android app on the emulator and cause the requests you want to debug. This should enable you to catch the incoming request on the localhost server. In my case, this quickly resolved my issue.

Obviously, the use of this method is not limited to debugging. If you are on the train and have no Internet connection, you can use this approach to develop your app anyway. One last tip: if you use GenyMotion as your emulator, use http://10.0.3.2 as the localhost rerouting address.

Case 2: You Are Using a Device

A different approach is necessary when you want to avoid using the emulator. However, this solution requires you to be on the same Wi-Fi network. Change the API request endpoint to your computer's local IP address, e.g. http://192.168.0.142 and run the app on your device. Once again, all requests should go against the localhost server running on your computer.

Let us know if you have any questions or issues: @futurestud_io

Happy Coding!

Explore the Library

Find interesting tutorials and solutions for your problems.