Getting Started on Mobile: Android

This page will discuss how to integrate the ChartIQ SDK into your native Android app and how to instantiate and interact with a ChartIQ chart.

Contents:

  1. Overview

  2. Download and Import the ChartIQ SDK

  3. Initialize the ChartIQ SDK


1. Overview

The ChartIQ SDK provides a native interface for Android developers to instantiate and interact with a ChartIQ chart. The interface will create a WebView and populate it with a predefined html file that loads the ChartIQ JavaScript library, supporting CSS, and a JavaScript “bridge” file which interfaces with the native interface.

What occurs in the WebView will be hidden, automatic, and not dependent on developer configuration. The developer should be able to instantiate the object as they would any other native component and essentially “feel” like they are working with a native component.

Important!

Although the SDK for Android and the JavaScript library may use the same function call names at times, they are not the same and they are not interchangeable . When using the mobile SDK, follow the documentation in the Native Library. When directly calling the javaScript API follow follow the documentation in the JavaScript CIQ core library

Prerequisites

  1. Minimum Android OS version - API 19 (4.4)
  2. A valid ChartIQ charting library (version 3.0 or greater)

Return to the top


2. Download and Import the ChartIQ SDK

There are two ways of integrating the ChartIQ SDK into your app. Please choose one integration method to avoid build issues.

  1. Via GitHub
  2. Via .aar import from GitHub

2a. Via GitHub

  1. Download the latest ChartIQ Sample App from GitHub.

  2. Load the project in Android Studio

  3. The chartiq Java SDK (chartiq-release) is already included and configured to the sample application

  4. Obtain a copy of the ChartIQ HTML5 Charting Library and install it on a webserver (Your application will load this dynamically when the app starts).

  5. Set String chartUrl = "your-server-url-location/sample-template-native-sdk.html" in MainActivity.java.

  6. Run the application

Return to the top


2b. Via .aar import

  1. Download the latest ChartIQ Sample App from GitHub.

  2. Copy the chartiq-release.aar from the chartiq-release directory

  3. Import ChartIQ.aar via File --> New --> New Module --> Import JAR/AAR Package.

  4. Open Project Structure, select your application's module and create a dependency to the newly imported ChartIQ SDK module.

  5. Open your main module's .gradle file and add three (3) additional dependencies:

     dependencies {
         implementation 'com.android.support:appcompat-v7:27.1.1'
         implementation 'com.android.support:recyclerview-v7:25.1.1'
         implementation 'com.google.code.gson:gson:2.8.0'
     }
  6. Import the ChartIQ library into your main Activity.

     import com.chartiq.sdk.ChartIQ;
  7. Obtain a copy of the ChartIQ HTML5 Charting Library and install it on a webserver (Your application will load this dynamically when the app starts).

  8. Set String chartUrl = "your-server-url-location/sample-template-native-sdk.html" in MainActivity.java.

  9. Build and run your app. If there are no build issues, you've successfully integrated the ChartIQ SDK into your project. Now, let's initialize the ChartIQ SDK and create our first chart.

Return to the top


3 Initialize the ChartIQ SDK

  1. Add a ChartIQ view into your main Activity's xml layout. This view will display the ChartIQ chart.

     <?xml version="1.0" encoding="utf-8"?>
     <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
         xmlns:tools="https://schemas.android.com/tools"
         android:layout_width="match_parent"
         android:layout_height="match_parent">
    
         <com.chartiq.sdk.ChartIQ
             android:id="@+id/chartiq"
             android:layout_width="100dp"
             android:layout_height="100dp"
             android:layout_alignParentBottom="true"
             android:layout_alignParentEnd="true"
             android:layout_alignParentLeft="true"
             android:layout_alignParentRight="true"
             android:layout_alignParentStart="true"
             android:layout_alignParentTop="true" />
    
     </RelativeLayout>
  1. In your Activity's onCreate() method:

    • Create a ChartIQ object and attach it to the ChartIQ View
    • Make sure the chartUrl String is set to the path where your ChartIQ HTML5 library is deployed
    • Initialize the ChartIQ SDK, the ChartIQ library path and a success callback.
    • Initialize the data loading methods using setDataMethod() and setDataSource()

      import com.chartiq.sdk.ChartIQ;
      import com.chartiq.sdk.model.OHLCChart;
      import com.google.gson.Gson;
      
      import java.io.BufferedReader;
      import java.io.InputStream;
      import java.io.InputStreamReader;
      import java.net.HttpURLConnection;
      import java.net.URL;
      import java.text.DateFormat;
      import java.text.SimpleDateFormat;
      import java.util.Date;
      import java.util.Map;
      import java.util.TimeZone;
      
      public class MainActivity extends AppCompatActivity {
      
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
      
              // !!!!! adjust `deploypath` as needed match to match the path
            // to get to sample-template-native-sdk.html
            String chartUrl = "https://deploypath/template-native-sdk.html";
      
            // attach ChartIQ object to the view
            final ChartIQ chartIQview = (ChartIQ) findViewById(R.id.chartiq);
      
            // set up your quote feed
            chartIQview.setDataSource(new ChartIQ.DataSource() {
                @Override
                public void pullInitialData(Map<String, Object> params, ChartIQ.DataSourceCallback callback) {
                    // put code for initial data load from your feed here
                    // see loadChartData(params, callback); example
                }
      
                @Override
                public void pullUpdateData(Map<String, Object> params, ChartIQ.DataSourceCallback callback) {
                    // put code for data updates from your feed here
                    // see loadChartData(params, callback); example
      
                }
      
                @Override
                public void pullPaginationData(Map<String, Object> params, ChartIQ.DataSourceCallback callback) {
                    // put code for pagination loads from your feed here
                    // see loadChartData(params, callback); example
      
                }
            });
      
            // init the rest of the ChartIQ SDK and library path
            chartIQview.start(ChartIQLibraryPath, new ChartIQ.CallbackStart() {
                @Override
                public void onStart() {
                    // set 'PULL' data loading method
                    chartIQview.setDataMethod(ChartIQ.DataMethod.PULL);
                    // set the symbol for the chart
                    chartIQview.setSymbol("APPL");
                }
            });
      
        }
      
      // Sample code for loading data form your feed.
      private void loadChartData(Map<String, Object> params, final ChartIQ.DataSourceCallback callback) {
            if(!params.containsKey("start") || params.get("start") == null || "".equals(params.get("start"))) {
                params.put("start", "2016-12-16T16:00:00.000Z");
            }
      
            if(params.containsKey("end") || "".equals(params.get("start"))) {
                TimeZone tz = TimeZone.getTimeZone("UTC");
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
                df.setTimeZone(tz);
                String endDate = df.format(new Date());
                params.put("end", endDate);
            }
      
            boolean isMinute = params.containsKey("interval") && TextUtils.isDigitsOnly(String.valueOf(params.get("interval")));
            params.put("interval", isMinute ? "minute" : params.get("interval"));
            params.put("period", isMinute ? 1 : params.get("period"));
      
            StringBuilder builder = new StringBuilder();
            builder.append("https://simulator.chartiq.com/datafeed?");
            builder.append("identifier=" + params.get("symbol"));
            builder.append("&startdate=" + params.get("start"));
            if (params.containsKey("end")) {
                builder.append("&enddate=" + params.get("end"));
            }
            builder.append("&interval=" + params.get("interval"));
            builder.append("&period=" + params.get("period"));
            builder.append("&seed=1001");
      
            final String url = builder.toString();
            new AsyncTask<Void, Void, String>() {
                @Override
                protected String doInBackground(Void... params) {
                    String body = "";
                    try {
                        URL connectionUrl = new URL(url);
                        HttpURLConnection connection = (HttpURLConnection) connectionUrl.openConnection();
                        connection.setRequestMethod("GET");
                        connection.setRequestProperty("Content-Type", "application/json");
                        connection.connect();
                        int code = connection.getResponseCode();
      
                        InputStream is;
                        StringBuilder builder;
                        if (code >= 200 && code < 400) {
                            builder = new StringBuilder();
                            is = connection.getInputStream();
                        } else {
                            is = connection.getErrorStream();
                            builder = new StringBuilder("Error("+code+"): ");
                        }
                        if (is != null) {
                            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                            String line;
                            while ((line = reader.readLine()) != null) {
                                builder.append(line);
                            }
                            body = builder.toString();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return body;
                }
      
                @Override
                protected void onPostExecute(String body) {
                    if(!body.startsWith("Error") && !"invalid symbol".equals(body)){
                        OHLCChart[] data = new Gson().fromJson(body, OHLCChart[].class);
                        callback.execute(data);
                    }
                }
            }.execute((Void[]) null);
        }
      }
  2. Build and run your app. You should see a ChartIQ view loaded and populated with a chart.

Return to the top


Next Steps: