无法在listview项目中显示图像

时间:2016-06-11 11:28:43

标签: php android mysql listview

我正在尝试从网址获取图片并将其显示到listview项目中。 该URL通过php从mysql数据库中获取。

目前我无法将图像显示在listview项目中。

我使用的过程是首先下载图像并将其缓存,然后将其显示在listview项目上。 (根据我在网上搜索的内容,我们可以直接将网址显示在listview项目中。)

任何建议或编码都会很棒。

以下是我正在使用并面临问题的代码。

public void GetProduct () {

        class GetJSON extends AsyncTask<Void, Void, String> {
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(getActivity(), "Fetching Data", "Wait...", false, false);
            }            
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                JSON_STRING = s;
                JSONObject jsonObject = null;
                ArrayList<HashMap<String, String>> list2= new ArrayList<HashMap<String, String>>();
                try {
                    jsonObject = new JSONObject(JSON_STRING);
                    JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
                    Log.d("JSON", Config.TAG_JSON_ARRAY);
                    for (int i = 0; i < result.length(); i++) {
                        JSONObject jo = result.getJSONObject(i);
                        String id = jo.getString(Config.TAG_ID);
                        String TITLE = jo.getString(Config.TAG_TITLE);
                        String BRAND = jo.getString(Config.TAG_BRAND);
                        String ITEMTYPE = jo.getString(Config.TAG_ITEMTYPE);
                        String BOOSTERTYPE = jo.getString(Config.TAG_BOOSTERTYPE);
                        String PRICE = jo.getString(Config.TAG_PRICE);
                        String IMGURL = jo.getString(Config.TAG_IMGURL);
                        String QTYINSTOCK = jo.getString(Config.TAG_QTYINSTOCK);
                        String QTYPENDING = jo.getString(Config.TAG_QTYPENDING);

                        HashMap<String, String> event = new HashMap<String, String>();
                        event.put(Config.TAG_ID, id);
                        event.put(Config.TAG_TITLE, TITLE);
                        event.put(Config.TAG_BRAND, BRAND);
                        event.put(Config.TAG_ITEMTYPE, ITEMTYPE);
                        event.put(Config.TAG_PRICE, PRICE);
                        event.put(Config.TAG_IMGURL, IMGURL);
                        event.put(Config.TAG_QTYINSTOCK, QTYINSTOCK);
                        event.put(Config.TAG_QTYPENDING, QTYPENDING);

//the code i added for picasso
                         ImageView img = (ImageView)getActivity().findViewById(R.id.iv_flag);
                    String imgUrl = (String)event.get(Config.TAG_IMGURL);
                    Picasso.with(getActivity()).load(imgUrl).into(img);
                            list2.add(event);
                            ListAdapter adapter = new MyAdapter(
                                            getActivity().getBaseContext(), list2, R.layout.productitem,
                                            new String[]{Config.TAG_TITLE, Config.TAG_PRICE, Config.TAG_BRAND, Config.TAG_ITEMTYPE, Config.TAG_QTYINSTOCK, "flag"},
                                            new int[]{R.id.text1, R.id.text2, R.id.text3, R.id.text4, R.id.text5, R.id.iv_flag});
                            ProductListing.setAdapter(adapter);
                            HashMap<String, Object> hm = (HashMap<String, Object>)adapter.getItem(i);
                            String imgUrl = (String)event.get(Config.TAG_IMGURL);
                            ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
                            HashMap<String, Object> hmDownload = new HashMap<String, Object>();
                            hm.put("flag_path", imgUrl);
                            hm.put("position",i);
                            imageLoaderTask.execute(hm);
                        }
                    } catch (JSONException e) {
                        Log.e("JSON Parser", "Error parsing data [" + e.getMessage() + "] " + jsonObject);
                        e.printStackTrace();
                    }
                }

                @Override
                protected String doInBackground(Void... params) {
                    RequestHandler rh = new RequestHandler();                
                    String s = rh.sendGetRequest("the url for my php file");
                    return s;
                }
            }
            final GetJSON gj = new GetJSON();
            gj.execute();
        }
        /** AsyncTask to download and load an image in ListView */
        private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
            @Override
            protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
                InputStream iStream=null;
                String imgUrl = (String) hm[0].get("flag_path");
                Log.d("url1", imgUrl);
                int position = (Integer) hm[0].get("position");
                URL url;
                try {
                    url = new URL(imgUrl);
                    // Creating an http connection to communicate with url
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    // Connecting to url
                    urlConnection.connect();
                    // Reading data from url
                    iStream = urlConnection.getInputStream();
                    // Getting Caching directory
                    File cacheDirectory = getActivity().getBaseContext().getCacheDir();
                    // Temporary file to store the downloaded image
                    File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");
                    // The FileOutputStream to the temporary file
                    FileOutputStream fOutStream = new FileOutputStream(tmpFile);
                    // Creating a bitmap from the downloaded inputstream
                    Bitmap b = BitmapFactory.decodeStream(iStream);
                    // Writing the bitmap to the temporary file as png file
                    b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
                    // Flush the FileOutputStream
                    fOutStream.flush();
                    //Close the FileOutputStream
                    fOutStream.close();
                    // Create a hashmap object to store image path and its position in the listview
                    HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
                    // Storing the path to the temporary image file
                    hmBitmap.put("flag",tmpFile.getPath());
                    // Storing the position of the image in the listview
                    hmBitmap.put("position",position);
                    // Returning the HashMap object containing the image path and position
                    return hmBitmap;

                }catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(HashMap<String, Object> result) {
                // Getting the path to the downloaded image
                String path = (String) result.get("flag");
                // Getting the position of the downloaded image
                int position = (Integer) result.get("position");
                // Getting adapter of the listview
                SimpleAdapter adapter = (SimpleAdapter)ProductListing.getAdapter();
                // Getting the hashmap object at the specified position of the listview
                HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
                // Overwriting the existing path in the adapter
                hm.put("flag",path);
                // Noticing listview about the dataset changes
                adapter.notifyDataSetChanged();
            }
        }

LogCat:

06-11 19:16:21.621 21935-22767/info.androidhive.slidingmenu D/url1: http://www.genesisfrontier.com/cfs/files/images/ib53ZANJkNPJ2cQCS/BFEH_EB2.png
06-11 19:16:21.621 21935-22767/info.androidhive.slidingmenu I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
06-11 19:16:21.631 21935-22767/info.androidhive.slidingmenu I/System.out: KnoxVpnUidStorageknoxVpnSupported API value returned is false
06-11 19:16:21.731 21935-21935/info.androidhive.slidingmenu E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: : open failed: ENOENT (No such file or directory)
06-11 19:16:21.731 21935-21935/info.androidhive.slidingmenu I/System.out: resolveUri failed on bad bitmap uri: 

下面是picasso的logcat

FATAL EXCEPTION: main
                                                                            Process: info.androidhive.slidingmenu, PID: 1289
                                                                            java.lang.IllegalArgumentException: Target must not be null.
                                                                                at com.squareup.picasso.RequestCreator.into(RequestCreator.java:618)
                                                                                at com.squareup.picasso.RequestCreator.into(RequestCreator.java:601)
                                                                                at info.androidhive.slidingmenu.FindPeopleFragment$1GetJSON.onPostExecute(FindPeopleFragment.java:147)
                                                                                at info.androidhive.slidingmenu.FindPeopleFragment$1GetJSON.onPostExecute(FindPeopleFragment.java:91)
                                                                                at android.os.AsyncTask.finish(AsyncTask.java:632)
                                                                                at android.os.AsyncTask.access$600(AsyncTask.java:177)
                                                                                at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:145)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5938)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)

1 个答案:

答案 0 :(得分:0)

使用Picasso lib从Url下载图像,它会自动从网址下载图片。要使用Picasso库,请将其添加到gradle文件中

compile 'com.squareup.picasso:picasso:2.5.2'

然后这样做

String imgUrl = (String)event.get(Config.TAG_IMGURL);
Picasso.with(context).load(imgUrl).into("your imageview");