公共类MainActivity扩展AppCompatActivity实现了View.OnClickListener {
Button btn;
TextView price;
String url = "https://koinim.com/ticker/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btn_get_information);
price = (TextView)findViewById(R.id.price);
btn.setOnClickListener(this);
}
@Override
public void onClick(View v){
if (v.getId() == R.id.btn_get_information){
JsonObjectRequest jsonObjectRequest = new
JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
price.setText("BTC: " +
response.getString("sell")+ " " + "₺" );
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText((getApplicationContext()),"Error",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
MySingleton.getmInstance(getApplicationContext()).
addToRequestQue(jsonObjectRequest);
}
}
}
我是android的新开发者。 我查看了源代码并从一个链接进行了解析。但我有四个链接。我如何解析四个链接?
答案 0 :(得分:0)
不要使用String url,而是创建一个包含所有URL的字符串ArrayList。
在onClick()方法中循环访问URL。
请注意,在onCreate中填充了ArrayList。我还在onClick中添加了一个try / catch子句,因此如果某个URL出现问题,其他URL将被解析。
处理不同的网址:
对于解析Koinim代码,您需要密钥&#34; sell&#34;,对于Paribu,您将需要&#34; last&#34;。
在循环中,我正在检查URL是否包含Koinim或Paribu,并相应地调整它们的键。
ArrayList<String> urls = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn_get_information);
price = (TextView) findViewById(R.id.price);
urls.add("https://koinim.com/ticker/");
urls.add("url2");
urls.add("url3");
urls.add("url4");
btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_get_information) {
for (String url : urls) {
try {
JsonObjectRequest request = null;
if(url.contains("koinim"))
{
request = getSellPrice("sell");
}
else if(url.contains("paribu"))
{
request = getSellPrice("last");
}
if(request != null)
{
MySingleton.getmInstance(getApplicationContext()).
addToRequestQue(jsonObjectRequest);
}
} catch (Exception ex) {
// something went wrong, handle exception here
}
}
}
}
private JsonObjectRequest getSellPrice(String key)
{
JsonObjectRequest jsonObjectRequest = new
JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
price.setText("BTC: " +
response.getString(key) + " " + "₺");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText((getApplicationContext()), "Error", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
return jsonObjectRequest;
}