-1
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.empty_photo, 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();
    }
}

}

在我的应用程序中,我的图像 URL 正在显示LogCat但无法显示图像,并且其临时图像也未显示。我应该怎么做才能让它工作?分享你的建议。谢谢你。:-)

1.设备图片

这是图像

2.Logcat镜像

在此处输入图像描述

4

1 回答 1

1

我不知道您为什么要编写自己的代码来下载图像,

https://github.com/nostra13/Android-Universal-Image-Loader

这里是库,它会从 url 下载你的图片,将它们分配给 imageviews,还会缓存图片,当你将来需要图片时,它会在本地缓存中搜索并提供给你的应用程序,而无需一次又一次地下载。

于 2013-11-11T07:40:50.160 回答