繁体   English   中英

我无法使用 JSON 在我的应用程序中显示可绘制的图像

[英]i cant show image from drawable in my app using JSON

我做了一切正确的事情来从资产(recipe.json)中读取我的 json 数据,其中包含

{"id":"1", "name":"الوصفة 1", "desc":"الوصفة 1", "image":"R.drawable.image"}...

我在 recyclerView 中正确加载了名称和 desc,但使用 getIdentifier() 未显示图像...这是我的代码


     private void addItemsFromJSON() {
        try {

            String jsonDataString = readJSONDataFromFile();
            JSONObject jsonObject = new JSONObject(jsonDataString);
            JSONArray jsonArray=jsonObject.getJSONArray("recipes");



            for (int i=0; i<jsonArray.length(); ++i) {

                JSONObject itemObj = jsonArray.getJSONObject(i);

                String name = itemObj.getString("name");
                String desc = itemObj.getString("desc");
                String image = itemObj.getString("image");
                // get resource id by image name
                int resourceId =getResources().getIdentifier(image, "drawable",getPackageName());
                Recipe recipe = new Recipe(name, desc,resourceId);
                recipes.add(recipe);
            }

        } catch (JSONException | IOException e) {
            Log.d(TAG, "addItemsFromJSON: ", e);
        }
    }

它显示标题和描述,但图像为空

修改 JSON 中的图片名称,如 {"id":"1", "name":"image1", "desc":"Image Description", "image":"imageNameInTheDrawable"} 从资源中获取drawable:

for (int i=0; i<jsonArray.length(); ++i) {

            JSONObject itemObj = jsonArray.getJSONObject(i);

            String name = itemObj.getString("name");
            String desc = itemObj.getString("desc");
            String imageName = itemObj.getString("image");
            // Get drawable by image name
         Drawable drawable = getResources().getDrawable(getResources()
              .getIdentifier(imageName, "drawable", getPackageName()));
            Recipe recipe = new Recipe(name, desc,drawable);
            recipes.add(recipe);
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM