-2
      public class MyFragment extends Fragment {
    int mCurrentPage;
    Context c;
    GridView mListView;
    String id, cat;
    String strUrl;
    TextView tvtitle;
    TextView tv_id, tv_rating, tv_url;
    public static String img_url, img_rating, img_id, img_name;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle data = getArguments();
        mCurrentPage = data.getInt("current_page", 0);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = null;
        DownloadTask downloadTask = new DownloadTask();
        v = inflater.inflate(R.layout.starters, container, false);
        tv_id = (TextView) v.findViewById(R.id.tv_starter_hide_id);
        tv_rating = (TextView) v.findViewById(R.id.tv_starter_hide_ratinf);
        tv_url = (TextView) v.findViewById(R.id.tv_starter_hide_url);
        cat = Category.Main_Cat;
        Log.i("Logcat Cat1", cat);
        switch (mCurrentPage) {
        case 1:
            Log.v("MyFragment Heap", "Max Mem in MB:"
                    + (Runtime.getRuntime().maxMemory() / 1024 / 1024));
            // strUrl =
            // "http://vaibhavtech.com/work/android/get_json.php?cat="+cat+"&subcat=1";
            strUrl = " http://vaibhavtech.com/work/android/movie_list.php?category=BollyWood%20&sub_category=top";
            downloadTask.execute(strUrl);
            mListView = (GridView) v.findViewById(R.id.lv_countries);
            mListView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    // TODO Auto-generated method stub
                    Intent i = new Intent(getActivity().getBaseContext(),
                            Starter_info.class);
                    img_id = ((TextView) arg1
                            .findViewById(R.id.tv_starter_hide_id)).getText()
                            .toString();
                    img_rating = ((TextView) arg1
                            .findViewById(R.id.tv_starter_hide_ratinf))
                            .getText().toString();
                    img_url = ((TextView) arg1
                            .findViewById(R.id.tv_starter_hide_url)).getText()
                            .toString();
                    img_name = ((TextView) arg1
                            .findViewById(R.id.tv_starter_hide_imagename))
                            .getText().toString();
                    startActivity(i);
                }
            });
            break;
        case 2:
            // strUrl =
            // "http://vaibhavtech.com/work/android/get_json.php?cat="+cat+"&subcat=1";
            strUrl = " http://vaibhavtech.com/work/android/movie_list.php?category=BollyWood%20&sub_category=top";
            downloadTask.execute(strUrl);
            Log.v("Splash Heap", "Max Mem in MB:"
                    + (Runtime.getRuntime().maxMemory() / 1024 / 1024));
            mListView = (GridView) v.findViewById(R.id.lv_countries);
            mListView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    // TODO Auto-generated method stub
                    Intent i = new Intent(getActivity().getBaseContext(),
                            Starter_info.class);
                    img_id = ((TextView) arg1
                            .findViewById(R.id.tv_starter_hide_id)).getText()
                            .toString();
                    img_rating = ((TextView) arg1
                            .findViewById(R.id.tv_starter_hide_ratinf))
                            .getText().toString();
                    img_url = ((TextView) arg1
                            .findViewById(R.id.tv_starter_hide_url)).getText()
                            .toString();
                    img_name = ((TextView) arg1
                            .findViewById(R.id.tv_starter_hide_imagename))
                            .getText().toString();
                    startActivity(i);

                }
            });
            break;
        default:
            Log.i("Cat IS", Category.Main_Cat);
            // strUrl =
            // "http://vaibhavtech.com/work/android/get_json.php?cat="+cat+"&subcat=1";
            strUrl = " http://vaibhavtech.com/work/android/movie_list.php?category=BollyWood%20&sub_category=top";
            downloadTask.execute(strUrl);
            Log.v("Splash Heap", "Max Mem in MB:"
                    + (Runtime.getRuntime().maxMemory() / 1024 / 1024));
            mListView = (GridView) v.findViewById(R.id.lv_countries);
            mListView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    // TODO Auto-generated method stub
                    Intent i = new Intent(getActivity().getBaseContext(),
                            Starter_info.class);
                    img_id = ((TextView) arg1
                            .findViewById(R.id.tv_starter_hide_id)).getText()
                            .toString();
                    img_rating = ((TextView) arg1
                            .findViewById(R.id.tv_starter_hide_ratinf))
                            .getText().toString();
                    img_url = ((TextView) arg1
                            .findViewById(R.id.tv_starter_hide_url)).getText()
                            .toString();
                    img_name = ((TextView) arg1
                            .findViewById(R.id.tv_starter_hide_imagename))
                            .getText().toString();
                    startActivity(i);

                }
            });
            break;
        }
        return v;
    }

    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        try {
            URL url = new URL(strUrl);
            // 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();
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    iStream));
            StringBuffer sb = new StringBuffer();
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            data = sb.toString();
            br.close();

        } catch (Exception e) {
            Log.d("Exception while downloading url", e.toString());
        } finally {
            iStream.close();
        }

        return data;
    }

    private class DownloadTask extends AsyncTask<String, Integer, String> {
        String data = null;

        @Override
        protected String doInBackground(String... url) {
            try {
                data = downloadUrl(url[0]);

            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
            ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
            listViewLoaderTask.execute(result);
        }

    }

    private class ListViewLoaderTask extends
            AsyncTask<String, Void, SimpleAdapter> {
        JSONObject jObject;

        @Override
        protected SimpleAdapter doInBackground(String... strJson) {
            try {
                jObject = new JSONObject(strJson[0]);
                StarterParser countryJsonParser = new StarterParser();
                countryJsonParser.parse(jObject);
            } catch (Exception e) {
                Log.d("JSON Exception1", e.toString());
            }
            StarterParser countryJsonParser = new StarterParser();
            List<HashMap<String, Object>> countries = null;
            try {
                // Getting the parsed data as a List construct
                countries = countryJsonParser.parse(jObject);
            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }
            String[] from = { "poster", "year", "duration", "id", "title" };
            int[] to = { R.id.iv_flag, R.id.tv_starter_hide_url,
                    R.id.tv_starter_hide_ratinf, R.id.tv_starter_hide_id,
                    R.id.tv_starter_hide_imagename };
            SimpleAdapter adapter = new SimpleAdapter(getActivity()
                    .getBaseContext(), countries, R.layout.lv_layout, from, to);

            return adapter;
        }

        @Override
        protected void onPostExecute(SimpleAdapter adapter) {
            mListView.setAdapter(adapter);
            ImageLoader imageLoader=new ImageLoader(getActivity());
            for (int i = 0; i < adapter.getCount(); i++) {
                HashMap<String, Object> hm = (HashMap<String, Object>) adapter
                        .getItem(i);
                String imgUrl = (String) hm.get("flag_path");
                ImageView posterImage=((ImageView)adapter.getView(i, null, null).findViewById(R.id.iv_flag));
                imageLoader.DisplayImage(imgUrl, R.drawable.img, posterImage);
                /*ImageLoaderTask imageLoaderTask = new ImageLoaderTask();

                HashMap<String, Object> hmDownload = new HashMap<String, Object>();
                hm.put("flag_path", imgUrl);
                hm.put("position", i);
                imageLoaderTask.execute(hm);*/
            }
        }
    }

    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");
            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) mListView.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();
        }
    }

     }

here is my imagelaoder class
public class ImageLoader {

    MemoryCache memoryCache=new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService; 

    public ImageLoader(Context context){
        fileCache=new FileCache(context);
        executorService=Executors.newFixedThreadPool(5);
    }

    int stub_id = R.drawable.img;
    public void DisplayImage(String url, int loader, ImageView imageView)
    {
        stub_id = loader;
        imageViews.put(imageView, url);
        Bitmap bitmap=memoryCache.get(url);
        if(bitmap!=null)
            imageView.setImageBitmap(bitmap);
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(loader);
        }
    }

    private void queuePhoto(String url, ImageView imageView)
    {
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url)
    {
        File f=fileCache.getFile(url);

        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;

        //from web
        try {
            Bitmap bitmap=null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           return null;
        }
    }

    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }

    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u;
            imageView=i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;
        PhotosLoader(PhotoToLoad photoToLoad){
            this.photoToLoad=photoToLoad;
        }

        @Override
        public void run() {
            if(imageViewReused(photoToLoad))
                return;
            Bitmap bmp=getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if(imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
            Activity a=(Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad){
        String tag=imageViews.get(photoToLoad.imageView);
        if(tag==null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;
        public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
        public void run()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap!=null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }



          }
here is my starterparser class



    public class StarterParser {

    // Receives a JSONObject and returns a list
            public List<HashMap<String,Object>> parse(JSONObject jObject){      

                JSONArray jCountries = null;
                try {       
                    // Retrieves all the elements in the 'countries' array 
                    jCountries = jObject.getJSONArray("Demo");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                 // Invoking getCountries with the array of json object
                 // where each json object represent a country
                return getCountries(jCountries);
            }


            private List<HashMap<String, Object>> getCountries(JSONArray jCountries){
                int countryCount = jCountries.length();
                List<HashMap<String, Object>> countryList = new ArrayList<HashMap<String,Object>>();
                HashMap<String, Object> country = null; 

                // Taking each country, parses and adds to list object 
                for(int i=0; i<countryCount;i++){
                    try {
                        // Call getCountry with country JSON object to parse the country 
                        country = getCountry((JSONObject)jCountries.get(i));
                        countryList.add(country);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                return countryList;
            }

            // Parsing the Country JSON object 
            private HashMap<String, Object> getCountry(JSONObject jCountry){

                HashMap<String, Object> country = new HashMap<String, Object>();
                String countryName = "";
                String flag="";
                String language = "";
                String capital = "";
                String currencyCode = "";
                String currencyName = "";       

                try {
                    countryName = jCountry.getString("id");
                //  flag = "http://vaibhavtech.com/work/android/admin/upload/"+jCountry.getString("Images");
                    flag="http://vaibhavtech.com/work/android/admin/upload/img.png";
                    Log.i("imGE PATH", ""+flag);
                //  language = jCountry.getString("rank");
                    //capital = jCountry.getString("country");
                    currencyCode = jCountry.getString("duration");
                    currencyName = jCountry.getString("id");

                    String details =        "Price : " + language + "\n" +
                             "Rating : " + currencyCode + "\n";

                    country.put("id", currencyName);
                    country.put("poster", R.drawable.picture_frame);
                    country.put("flag_path", flag);
                    country.put("duration",currencyCode);
                    country.put("year", flag);
                    country.put("title", jCountry.getString("title"));
                    Log.i("Json Imag Name", jCountry.getString("poster"));


                } catch (JSONException e) {         
                    e.printStackTrace();
                }       
                return country;
            }

}

我在此使用了图像加载器概念,但它没有在屏幕上显示图像。logcat 上只显示图像的名称和值。

4

2 回答 2

0

在 ListViewLoaderTask 的 onPostExecute 方法中,检查返回的 Url 模式。

String imgUrl = (String) hm.get("flag_path");

可接受的格式是

String imageUri = "http://example.com/image.png"; // from Web

String imageUri = "file:///mnt/sdcard/image.png"; // from SD card

String imageUri = "content://media/external/audio/albumart/13"; // from content provider

String imageUri = "assets://image.png"; // from assets

String imageUri = "drawable://" + R.drawable.image; // from drawables (only images, non-9patch)
于 2013-11-11T10:11:02.203 回答
0

借助 Volley 库 WS 调用和图像下载和缓存,可以如此简单地使用它就像儿戏一样......将来尝试实现 Volley 只需几行代码就可以让您的生活更轻松:一些教程:

排球教程1

排球教程2

于 2013-11-11T10:15:41.893 回答