Reputation: 25
I want to get the data from several stock JSON data, but I know how to get only one at a time. I can't find a way to get several. It works if I request only AAPPL, but not if I request also FB
More information about the API I'm getting the data from: https://financialmodelingprep.com/developer/docs#Realtime-Stock-Price
I tried to add more stocks final String stockID = "AAPL,FB";
In the browser in shows the data https://financialmodelingprep.com/api/company/price/AAPL,FB?datatype=json But not in the app.
public class MainActivity extends AppCompatActivity {
ListView textView;
ArrayList<String> stocks;//is a resizable array
ArrayAdapter<String> adapter; //Returns a view for each object in a collection of data objects you provide
RequestQueue queue; //Cola peticiones volley
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
queue = Volley.newRequestQueue(this); //Creamos una requestqueue para que gestione hilos, peticiones y demas.
stocks = new ArrayList<>();
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, stocks); //Pasing the context, the row layout and the resource?
textView.setAdapter(adapter); //Setting to the listview the arrayadapter that returns the view from the arraylist
addstock();
}
//TODO: add the rest of the stocks
private void addstock() {
final String stockID = "AAPL";
final String stockName = "Apple";
String url = "https://financialmodelingprep.com/api/company/price/" +stockID+"?datatype=json";
//Making the request
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try{
JSONObject value = response.getJSONObject(stockID);
String price = value.getString("price");
String Linestock = stockName+ ":"+price+"$";
stocks.add(Linestock);//Adding it to the arraylist
adapter.notifyDataSetChanged(); //And to the view
} catch (Exception e){
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
queue.add(jsonObjectRequest);
}
}
Upvotes: 1
Views: 85
Reputation: 21
You can make your requests asynchronous. To do so, you could checkout this tutorial:
I personally use the okhttp3 package. With this you can build a function like this:
public static String performPostCall(String requestURL, JSONObject postDataParams, String auth)
{
String response;
Log.d(LOG_TAG, "Send: " + postDataParams.toString() + " to " + requestURL + " Auth: " + auth);
try
{
Request request;
Builder tmp = new Builder();
tmp.connectTimeout(10, TimeUnit.SECONDS);
tmp.readTimeout(30, TimeUnit.SECONDS);
tmp.writeTimeout(30, TimeUnit.SECONDS);
OkHttpClient client = tmp.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, postDataParams.toString());
if (auth.equals(""))
{
request = new Request.Builder().url(requestURL).post(body).addHeader("Accept", "application/json").addHeader("Content-Type", "application/json").build();
}
else
{
request = new Request.Builder().url(requestURL).post(body).addHeader("Accept", "application/json").addHeader("Content-Type", "application/json").addHeader("authorization", "Bearer " + auth).build();
}
Response recv = client.newCall(request).execute();
response = recv.body().string();
}
catch (Exception e)
{
response = "{\"api_version\":1,\"status\":-1}";
Log.e(LOG_TAG, e.getMessage());
}
Log.d(LOG_TAG, "Received: " + response);
return response;
}
Upvotes: 2
Reputation: 7468
If you simply set stockID
to AAPL,FB
the line
response.getJSONObject(stockID)
won't work, because there's no object by AAPL,FB
and the null pointer exception will be caught and swallowed by your empty catch block.
try{
String[] stockIDs = stockID.Split(","); // assuming stockID is the full string you passed to the API. i.e "AAPL,FB" so we have to get individual stocks.
for(int i= 0; i < stockIDs.size; i++) {
JSONObject value = response.getJSONObject(stockIDs[i]);
String price = value.getString("price");
String Linestock = stockName+ ":"+price+"$";
stocks.add(Linestock);//Adding it to the arraylist
}
adapter.notifyDataSetChanged(); //And to the view
} catch (Exception e){
// Log.e(....); so you see the error on LogCat atleast
}
You could also iterate the properties of the JSON object regardless of the ones you passed to the API.
Upvotes: 0