php - 无法在 ListView 项中显示图像

标签 php android mysql listview

我正在尝试从 url 获取图像并将其显示到 ListView 项中。 url 是通过 php 从 mysql 数据库中获取的。

目前我无法让图像显示在我的 ListView 项目中。

我正在使用的过程是先下载图像并缓存它,然后将其显示在 ListView 项目上。 (根据我在网上搜索到的内容,我们可以直接获取一个url并将其显示到 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)

最佳答案

使用 Picasso lib 从 Url 下载图片,它会自动从 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");

关于php - 无法在 ListView 项中显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37763201/

相关文章:

php - 10,000,000行数据库的最佳存储引擎

php - 在 MVC 框架中,我们应该将 NODE.js 文件放在哪里?

javascript - 用js在android中打开 native 选择弹出窗口

Android Text to Speech 示例失败

java - 在搜索栏中使用单引号

php - fatal error : Cannot use object of type mysqli_result as array in. ..第 97 行

php - 简单数组重定向

php - MySQL Workbench 与 PHP 的执行结果不同

java - Android 手机上的 RED 5 视频服务器...有开源端口吗?

mysql - 如何在mysql表中插入嵌套的json数据?