0

如果找不到图像 url,我正在尝试使用可绘制文件夹中的图像作为占位符。但是当我尝试实现它时,我遇到了死代码错误。并且可用的图像 url 从 JSON 加载图像。

这是我的代码:

String image_file = new String( Environment.getExternalStorageDirectory()
                                + "/images/" + shop.getImage());
 String place_holder = "@drawable/placeholder";
                    if(shop.getId().equals(sales.getShop_id())){
                        if(image_file != null){
                            hm.put("shop_image", image_file );
                        }else{
                                    //here I gets dead code error
                            hm.put("shop_image", place_holder );
                        }
                    }

请有人帮我解决?

编辑:

@Override
protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

            for(Sales sales : this.response.sales){
                HashMap<String, String> hm = new HashMap<String,String>();
                if (sales.getCategories1().contains("cat_id1")){
                    hm.put("sale_id", sales.getId());
                    hm.put("sale_title", "" + sales.getShort_title());
                    hm.put("shop_name","Shop : " + sales.getShop_name());
                    for(Shop shop : this.response.shops){
                        String image_file = new String( Environment.getExternalStorageDirectory()
                                + "/images/" + shop.getImage());
                        //String place_holder = new String("@drawable/placeholder");
if(shop.getId().equals(sales.getShop_id())){
                        if(new File(image_file).exists()){
                            hm.put("shop_image", image_file );
                        }else{
                            hm.put("shop_image", String.valueOf(R.drawable.placeholder) );
                        }
                    }
}
                    aList.add(hm);
                }
            }

            // Keys used in Hashmap
            String[] from = { "sale_id","shop_image","sale_title","shop_name"};

            // Ids of views in listview_layout
            int[] to = { R.id.sale_id,R.id.shop_image,R.id.sale_title,R.id.shop_name};

            // Instantiating an adapter to store each items
            // R.layout.listview_layout defines the layout of each item
            SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);

            // Getting a reference to listview of main.xml layout file
            ListView myList = ( ListView ) findViewById(R.id.listview);

            // Setting the adapter to the listView
            myList.setAdapter(adapter);
4

1 回答 1

0

在这一行

if(image_file != null)  
//The string 'image_file' will never be null according to the lines above.

我认为您正在尝试判断图像文件是否存在。试试这个:

if (new File(image_file).exists())
于 2013-09-06T07:04:45.283 回答