我正在使用twitch API来获取当前关于twitch的前20个类别。此后,将它们解析为模型,然后将其显示在CardView中。我可以检索所有数据并将其解析到我的模型中,但URL(用于图片)除外。我可以检索该网址并将其记录到控制台,但是没有其他反应,
我尝试在api调用中创建一个runnable,但是一直获取NetworkingOnUIThreadException。现在,除了在控制台中打印网址外,它什么也没做。
这是我对API的GET请求
public void requestWithSomeHttpHeaders() {
//Retrieving the request URL from SETTINGS.
String url = StreamAPISetting.getRequestTopGames();
//Initiates response listener from Volley library
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
for (Categories c: Parser.parseCategories(response)) {
cats.add(c);
}
System.out.println(cats.get(4).getId());
mAdapter.notifyDataSetChanged();
Log.d(TAG, response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
})
{
@Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Client-ID", StreamAPISetting.getClientId());
params.put("Accept", StreamAPISetting.getHeaderAccept());
return params;
}
};
//Adds the request to the Queue
MySingleton.getInstance(this.getActivity()).addToRequestQueue(jsonObjReq);
}
这是我的解析器
public static List<Categories> parseCategories(JSONObject res){
List<Categories> categoriesList;
categoriesList = new ArrayList<>();
try {
JSONArray objects = res.getJSONArray("data");
for(int i = 0; i<objects.length(); i++){
JSONObject o = objects.getJSONObject(i);
System.out.println(o.getString("name"));
String url = o.getString("box_art_url")
.replace("{height}", "400")
.replace("{width}", "300");
System.out.println(url);
categoriesList.add(new Categories(o.getString("name"),
o.getString("id"),
ImageLoader.LoadImageFromWebOperations(url)));
}
} catch(JSONException e){
System.out.println(e.toString());
}
return categoriesList;
}
最后是我的ImageLoader,这似乎有问题
public class ImageLoader {
public static Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
}
我希望将该网址转换为可绘制的内容,以便可以将其解析为我的模型。