【发布时间】:2021-04-13 18:29:31
【问题描述】:
我正在尝试通过从 api 服务器获取指令来构造一个 BottomNavigationBar。
*目前代码抛出 [java.lang.IllegalStateException] 因为它是从 onResponse 方法调用 Picasso。
void updateMenuItems(RequestQueue queue, Menu menu){
String url = "http://10.0.2.2:5000/api/menuIcons";
//Request a string response from the provided URL
JsonArrayRequest jsonArrRequest = new JsonArrayRequest (Request.Method.GET, url, null
, new Response.Listener<JSONArray>(){
@Override
public void onResponse(JSONArray response) {
Log.e("updateMenu", response.toString());
List<MenuItems> menuItemsList = new ArrayList<MenuItems>();
for(int i = 0; i<response.length(); i++){
try {
JSONObject jsonItem = response.getJSONObject(i);
String imageLink = jsonItem.getString("image");
menu.add(0,
jsonItem.getInt("id"),
jsonItem.getInt("id"),
jsonItem.getString("name")).setIcon(new BitmapDrawable(getResources(), Picasso.get().load(imageLink).get()));
} catch (JSONException | IOException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("updateMenu","response error");
}
});
queue.add(jsonArrRequest);
}
服务器发送的JSON文件如下
app.get('/api/menuIcons', (req,res) => {
res.send([
{
'id': 1,
'name': 'Home',
'url': 'http://10.0.2.2:3000/',
'image': "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/Home_Icon.svg/1200px-Home_Icon.svg.png"
},
{
'id': 2,
'name': 'Dashboard',
'url': 'http://google.com/',
'image': "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/Home_Icon.svg/1200px-Home_Icon.svg.png"
},
{
'id': 3,
'name': 'Alarm',
'url': 'https://google.com/',
'image': "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/Home_Icon.svg/1200px-Home_Icon.svg.png"
},
{
'id': 4,
'name': 'Setting',
'url': 'http://google.com/',
'image': "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/Home_Icon.svg/1200px-Home_Icon.svg.png"
}
]);
});
所以这就是问题所在。我可以通过一个 Volley 请求添加没有图标的菜单项。 但是,要将图像图标添加到菜单项,我需要访问图像 URL,这需要另一个异步线程。
我不想在 volley call 中声明另一个 volley call(这很混乱)。 我想知道是否有结构上更好的解决方案。
【问题讨论】:
标签: android asynchronous android-volley picasso