Stock Tracking App in Android Studio (Java)
Build a live stock tracker: type a symbol and watch its price, change and daily range refresh every 15 seconds, using the free Finnhub API and Volley.
What you'll learn
- Make web requests with Volley
- Read a stock quote from JSON
- Refresh only while the screen is visible
- Keep your API key out of your code
Before you start
- Android Studio (any recent version)
- Basic Java: variables, methods and if/else
- A free Finnhub API key (finnhub.io)
- An emulator or an Android phone
How it fits together
- 1Type a symbol
- 2StockClient (Volley)
- 3finnhub.io quote + profile
- 4Price, change and tiles
- 5Refresh every 15 s while visible
Build it step by step
1. Get a free API key
The video used IEX Cloud, which has shut down. This version uses Finnhub: sign up and copy your free API key. The free plan covers US stocks and 60 requests a minute.
2. Create the project
In Android Studio choose New Project → Empty Views Activity, with Language Java and Minimum SDK API 24.
3. Keep the key out of your code
Add your key to local.properties in the project folder:
FINNHUB_API_KEY=your-key-hereThis file is never committed, so your key isn't published with your code.
4. Add Volley and read the key
In app/build.gradle.kts, add the import at the very top:
import java.util.PropertiesInside android { defaultConfig { } }:
val localProperties = Properties().apply {
rootProject.file("local.properties").takeIf { it.exists() }?.inputStream()?.use { load(it) }
}
buildConfigField("String", "FINNHUB_API_KEY", "\"${localProperties.getProperty("FINNHUB_API_KEY", "")}\"")Inside android { }:
buildFeatures {
buildConfig = true
}Inside dependencies { }:
implementation("com.android.volley:volley:1.2.1")Press Sync Now. Also add <uses-permission android:name="android.permission.INTERNET" /> to the manifest.
5. Ask Finnhub
StockClient sends two requests with Volley:
/quote?symbol=AAPLfor the price:ccurrent,dchange,dpchange %,oopen,hhigh,llow,pcprevious close./stock/profile2?symbol=AAPLonce per symbol, for the company name, exchange and currency.
Volley works in the background and calls you back on the main thread, so results go straight onto the screen.
6. Spot unknown symbols
Finnhub doesn't return an error for a symbol it doesn't know; it sends zeros with no time (t). Quote.fromJson returns null then, and the app says "No price found".
7. Show the price
Format prices with NumberFormat.getCurrencyInstance and the stock's currency. Colour the change green with ▲ when it's up and red with ▼ when it's down.
8. Refresh while visible
A Handler reloads the quote every 15 seconds. Start it in onStart and stop it in onStop, and cancel waiting requests, so the app never uses data in the background.
9. Flash on change
When the new price differs from the last one, ObjectAnimator.ofArgb fades the price from green or red back to its normal colour.
10. Run it
Try AAPL, MSFT or TSLA during US market hours to see it move. Try a made-up symbol to see the error.
If something goes wrong
- "Finnhub rejected the API key": check
local.propertieshas no spaces or quotes, then Build → Rebuild Project. - "No price found": the free plan covers US symbols; others need a paid plan.
What's improved over the video
A working, free API instead of the closed IEX Cloud, the key kept out of your code, company name and exchange, green and red changes, refreshing only while visible, and clear error messages.
Files affected
Check what to add and what to replace before copying code.
- app/build.gradle.ktsAdd these lines
- local.properties (project folder)Add these lines
- app/src/main/java/com/example/stocktracker/MainActivity.javaReplace file
- app/src/main/res/layout/activity_main.xmlReplace file
- app/src/main/AndroidManifest.xmlReplace file
- app/src/main/res/values/colors.xmlAdd these lines
- app/src/main/res/drawable/error_box.xmlAdd these lines
- app/src/main/java/com/example/stocktracker/Quote.javaAdd these lines
- app/src/main/java/com/example/stocktracker/Screens.javaAdd these lines
- app/src/main/java/com/example/stocktracker/StockClient.javaAdd these lines
- app/src/main/res/values/strings.xmlReplace file
- app/src/main/res/values/themes.xmlReplace file
- app/src/main/res/drawable/tile.xmlAdd these lines
Required setup
These are additions to an existing project—not replacement project files.
Add Volley and read your API key
Add these linesWhere: app/build.gradle.kts
Put the import at the very top, and each part where its comment says. Then press Sync Now.
import java.util.Properties
// inside android { defaultConfig { ... } }
val localProperties = Properties().apply {
rootProject.file("local.properties").takeIf { it.exists() }?.inputStream()?.use { load(it) }
}
buildConfigField("String", "FINNHUB_API_KEY", "\"${localProperties.getProperty("FINNHUB_API_KEY", "")}\"")
// inside android { ... }
buildFeatures {
buildConfig = true
}
// inside dependencies { ... }
implementation("com.android.volley:volley:1.2.1")
Your API key
Add these linesWhere: local.properties (project folder)
Never committed, so your key stays out of your code and off GitHub.
FINNHUB_API_KEY=your-key-here
Application code
Select a file to see its code and where it belongs.
This code uses package com.example.stocktracker. Change that first line to your own package, the one at the top of your MainActivity.
app/src/main/java/com/example/stocktracker/MainActivity.javaTracks a symbol, refreshes every 15 seconds while visible, and flashes the price when it moves.
package com.example.stocktracker;
import android.animation.ObjectAnimator;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.format.DateFormat;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import org.json.JSONObject;
import java.text.NumberFormat;
import java.util.Currency;
import java.util.Date;
import java.util.Locale;
/**
* Type a stock symbol and watch its price. While the screen is visible, the price refreshes every 15 seconds,
* and flashes green or red when it moves.
*/
public class MainActivity extends AppCompatActivity {
private static final long REFRESH_MS = 15_000;
private final Handler handler = new Handler(Looper.getMainLooper());
private final Runnable refresh = new Runnable() {
@Override
public void run() {
loadQuote();
handler.postDelayed(this, REFRESH_MS);
}
};
private StockClient client;
private SharedPreferences prefs;
private String symbol;
private NumberFormat money = moneyFormat("USD");
private double lastPrice;
private int priceColour;
private EditText symbolInput;
private View content;
private TextView error, company, details, price, change, open, high, low, previousClose, updated;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Screens.setUp(this, R.layout.activity_main);
symbolInput = findViewById(R.id.inputSymbol);
content = findViewById(R.id.content);
error = findViewById(R.id.textError);
company = findViewById(R.id.textCompany);
details = findViewById(R.id.textDetails);
price = findViewById(R.id.textPrice);
change = findViewById(R.id.textChange);
open = findViewById(R.id.textOpen);
high = findViewById(R.id.textHigh);
low = findViewById(R.id.textLow);
previousClose = findViewById(R.id.textPreviousClose);
updated = findViewById(R.id.textUpdated);
priceColour = price.getCurrentTextColor();
client = new StockClient(this, BuildConfig.FINNHUB_API_KEY);
prefs = getSharedPreferences("stocks", MODE_PRIVATE);
symbol = prefs.getString("symbol", "AAPL");
symbolInput.setText(symbol);
findViewById(R.id.btnTrack).setOnClickListener(v -> track());
symbolInput.setOnEditorActionListener((v, actionId, event) -> {
if (actionId != EditorInfo.IME_ACTION_GO) return false;
track();
return true;
});
}
/** Refresh only while the screen is visible, so the app never uses data in the background. */
@Override
protected void onStart() {
super.onStart();
start();
}
@Override
protected void onStop() {
super.onStop();
handler.removeCallbacks(refresh);
client.cancelAll();
}
private void track() {
String typed = symbolInput.getText().toString().trim().toUpperCase(Locale.ROOT);
if (typed.isEmpty()) {
symbolInput.setError(getString(R.string.error_empty));
return;
}
WindowCompat.getInsetsController(getWindow(), symbolInput).hide(WindowInsetsCompat.Type.ime());
symbol = typed;
lastPrice = 0;
content.setVisibility(View.INVISIBLE);
handler.removeCallbacks(refresh);
start();
}
private void start() {
if (BuildConfig.FINNHUB_API_KEY.isEmpty()) {
showError(R.string.error_no_key);
return;
}
loadProfile();
handler.post(refresh);
}
private void loadProfile() {
client.profile(symbol, new StockClient.Listener<JSONObject>() {
@Override
public void onResult(JSONObject profile) {
String name = profile.optString("name");
company.setText(name.isEmpty() ? symbol : name);
String exchange = profile.optString("exchange");
details.setText(exchange.isEmpty() ? symbol : getString(R.string.details, symbol, exchange));
money = moneyFormat(profile.optString("currency", "USD"));
}
@Override
public void onError(int message) {
// The quote request reports problems; the name is a nice extra.
company.setText(symbol);
}
});
}
private void loadQuote() {
client.quote(symbol, new StockClient.Listener<Quote>() {
@Override
public void onResult(Quote quote) {
show(quote);
prefs.edit().putString("symbol", symbol).apply();
}
@Override
public void onError(int message) {
showError(message);
}
});
}
private void show(Quote quote) {
error.setVisibility(View.GONE);
content.setVisibility(View.VISIBLE);
price.setText(money.format(quote.price));
boolean up = quote.change >= 0;
int colour = ContextCompat.getColor(this, up ? R.color.up : R.color.down);
change.setText(getString(up ? R.string.change_up : R.string.change_down,
money.format(Math.abs(quote.change)), Math.abs(quote.percent)));
change.setTextColor(colour);
open.setText(money.format(quote.open));
high.setText(money.format(quote.high));
low.setText(money.format(quote.low));
previousClose.setText(money.format(quote.previousClose));
updated.setText(getString(R.string.updated, DateFormat.getTimeFormat(this).format(new Date())));
// Flash the price when it moves since the last refresh, then fade back.
if (lastPrice != 0 && quote.price != lastPrice) {
int flash = ContextCompat.getColor(this, quote.price > lastPrice ? R.color.up : R.color.down);
ObjectAnimator.ofArgb(price, "textColor", flash, priceColour).setDuration(1200).start();
}
lastPrice = quote.price;
}
private void showError(int message) {
error.setText(message);
error.setVisibility(View.VISIBLE);
}
private static NumberFormat moneyFormat(String currencyCode) {
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault());
try {
format.setCurrency(Currency.getInstance(currencyCode));
} catch (IllegalArgumentException unknownCurrency) {
format.setCurrency(Currency.getInstance("USD"));
}
return format;
}
}


