【发布时间】:2019-04-23 11:34:48
【问题描述】:
我想从多个库存 JSON 数据中获取数据,但我知道如何一次只获取一个。 我找不到获得几个的方法。 如果我只请求 AAPPL,它就可以工作,但如果我也请求 FB,它就不行
有关我从中获取数据的 API 的更多信息: https://financialmodelingprep.com/developer/docs#Realtime-Stock-Price
我尝试添加更多股票 final String stockID = "AAPL,FB";
在浏览器中显示数据 https://financialmodelingprep.com/api/company/price/AAPL,FB?datatype=json 但不在应用程序中。
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);
}
}
【问题讨论】:
-
问题不清楚,至少对我来说是这样
-
您能否更新代码以显示您如何处理多个 stockIDs?如果您只是将
stockID设置为AAPL,FB,则response.getJSONObject(stockID)行将不起作用,因为AAPL,FB没有对象,并且空指针异常将被您的空catch块捕获并吞下。