Android: consume a REST / HTTPs service using JSON and Threads

Updated:

GitHub: https://github.com/marco76/stockVoiceTicker

In this example we show how to implement some Android features:app_screenshot

  • Text-to-speech
  • Read a JSON web stream
  • Use a thread to communicate with a website (REST)
  • Timer

The application is very limited and has been created for educational purpose only.

 

1. Read a webpage content (REST/HTTPs)

With Android if you want to read a webpage you have to create a thread. Android doesn’t allow you to open an URL connection from the Main (thread) because it could be resource intensive and time consuming. If you try to use the main Thread you will get this exception android.os.NetworkOnMainThreadException.

In our case we are calling a Yahoo service using YQL with the following URL : https://query.yahooapis.com/v1/public/yql?q=select%20LastTradePriceOnly%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22GOOG%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback= 

And we wait an answer in JSON format similar to this one.

{"query":{"count":1,"created":"2016-01-27T08:42:41Z","lang":"en-US","results":{"quote":{"LastTradePriceOnly":"713.04"}}}}

In our application we create a Task in the main thread using ExecutorService and Future:

private String readFromWeb() {   
        // THREAD   
        final ExecutorService service;   
        // this Task will contact Yahoo and store the answer (web page) in a String   
        final Future<String> task;     
        String jsonString = null;   

The Future task will receive the result of the HTTPS request and it will store it in a String (using task.get()).

service = Executors.newFixedThreadPool(1);   
task = service.submit(new YahooQuote(YAHOO_URL_PRE + ticker.getText() + YAHOO_URL_POST));   
try { 
    jsonString = task.get();   
} catch (final InterruptedException | ExecutionException ex) {   
      ex.printStackTrace();   
  } finally {   
     service.shutdownNow();   
}   

The class (YahooQuote) that communicate with Yahoo implements Callable and must override the call() method:

// Task that return a String 
public class YahooQuote implements Callable<String>{ 

To pass the URL to the class we create a new constructor that receive the parameter:

private final String jsonURL; 
 
    public YahooQuote(String jsonURL) { 
        this.jsonURL = jsonURL; 
    } 

The result is stored in the String jsonString.

2. Parse JSON

Now we have our json result in a String. We can easily transform the String in a JSON object with the function … JSONObject:

Because of the nature of the answer (multiple level JSON objects) we have to create a new JSON object for each level

json_multiple

private String readPrice(String json) throws JSONException { 
        JSONObject jsonObject = new JSONObject(json); 
        JSONObject query = jsonObject.getJSONObject("query"); 
        JSONObject results = query.getJSONObject("results"); 
        JSONObject quote = results.getJSONObject("quote"); 
        return quote.getString("LastTradePriceOnly"); 
 
    } 

We get the price result with getString();


Fullstack Angular / Java application quick start guide.
WebApp built by Marco using SpringBoot 3.2.4 and Java 21. Hosted in Switzerland (GE8).