0

I am new to sockets, I was hoping someone knows how to connect sockets on Android Studio and receive data.

This is the websocket which uses socket.io that I am trying to receive data from: https://ws-api.iextrading.com/1.0/stock/aapl/quote

This is a link to the API which explains the websocket: https://iextrading.com/developer/docs/#websockets

I am trying to get realtime stock data for my app, but I do not know how to connect to the socket then receive the data and my app crashes before it even opens, this is my code so far:

package com.example.android.stocksApp;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    private static Socket s;
    private static InputStreamReader isr;
    private static BufferedReader br;

    TextView result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        result = (TextView)findViewById(R.id.result);

        stockData();

    }

    public void stockData (){
        myTask mTask = new myTask();
        mTask.execute();
    }

    class myTask extends AsyncTask<Void, Void, Void>{

        @Override
        protected Void doInBackground(Void... params) {
            try {
                s = new Socket("https://ws-api.iextrading.com/1.0/stock/aapl/quote", 80);
                InputStream is = s.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String quote = br.readLine();
                result.setText(quote);
                s.close();
                is.close();
                isr.close();
                br.close();

            } catch (IOException e){
                e.printStackTrace();
            }

            return null;
        }
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

1 Answers1

0

You're trying to connect to a Web service. Web services may return either a XML or JSON. The actual Socket library isn't needed nor used for this. This specific web service returns a JSON, so what you need is a library that is capable of making a GET request to this URL and parse the response. For Android, I recommend using Volley. You can include Volley in your project by adding this line to your build.gradle.

implementation 'com.android.volley:volley:1.0.0'

This question might help you get started.

Morgan
  • 907
  • 1
  • 13
  • 35