同时下载多个图像,并更新列表视图

时间:2014-05-21 08:56:26

标签: android listview

我正在开发一个Android应用程序,它将从服务器服务获取最新消息,然后在列表视图中显示。代码如下:

HomeFragment.java

@SuppressLint("NewApi")
public class HomeFragment extends Fragment {
    private ListView listView;
    EditText search;
    ImageButton btn;
    ProgressDialog mProgressDialog;
    private NewsHomeAdapter customNewsHomeAdapter;

    Context homeFragmentContext;

    final ArrayList<NewsItem> news_home_data = new ArrayList<NewsItem>();

    // child categories JSONArray
    JSONArray newsItems = null;

    public HomeFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_home, container, false);

        homeFragmentContext = container.getContext();
        listView = (ListView) rootView.findViewById(R.id.news_home_list);
        search = (EditText) rootView.findViewById(R.id.search);
        search.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN)
                        && (keyCode == KeyEvent.KEYCODE_ENTER)) {

                    String query_text = search.getText().toString().trim();

                    try {
                        query_text = URLEncoder.encode(query_text, "utf-8");
                    } catch (UnsupportedEncodingException e) {

                    }
                    String full_query = query_text;

                    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(search.getWindowToken(), 0);

                    Intent bussiness = new Intent(homeFragmentContext,
                            SearchNews.class);
                    Bundle basket_buss_category = new Bundle();

                    basket_buss_category.putString("SEARCH", full_query);
                    ;

                    bussiness.putExtras(basket_buss_category);

                    startActivity(bussiness);

                    return true;
                }
                return false;
            }


        });

        new GetNewsData().execute(TimeUtils.NEWS_HOME_URL);

        listView.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> a, View v, int position,
                    long id) {

                Intent cluster = new Intent(homeFragmentContext, NewsCluster.class);

                Bundle newslist = new Bundle();
                newslist.putString("NLIST",news_home_data.get(position).getCluster());
                cluster.putExtras(newslist);
                startActivity(cluster);


            }

        });

        btn = (ImageButton) rootView.findViewById(R.id.search_button);
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                String query_text = search.getText().toString().trim();
                if (query_text.equalsIgnoreCase("")) {

                    search.requestFocus();
                    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
                }

                else {

                    try {
                        query_text = URLEncoder.encode(query_text, "utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    String full_query = query_text;

                    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(search.getWindowToken(), 0);

                    Intent bussiness = new Intent(homeFragmentContext, SearchNews.class);
                    Bundle basket_buss_category = new Bundle();

                    basket_buss_category.putString("SEARCH", full_query);

                    bussiness.putExtras(basket_buss_category);

                    startActivity(bussiness);

                }

            }
        });

        return rootView;
    }

    private class GetNewsData extends
    AsyncTask<String, Void, ArrayList<NewsItem>> {

protected void onPreExecute() {
    super.onPreExecute();

    // shfaq Progress Dialogun, deri ne momentin qe te loadohen te
    // dheant
    mProgressDialog = new ProgressDialog(homeFragmentContext);
    mProgressDialog.setMessage("Loading...");
    mProgressDialog.setIndeterminate(false);
    mProgressDialog.show();
}

@Override
protected ArrayList<NewsItem> doInBackground(String... URL) {

    String categories_url = URL[0];
    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();
    // getting JSON string from URL
    newsItems = jParser.getJSONFromUrl(categories_url);
    Log.e("lsbsfbsfdbsfd", newsItems.toString());
    try {
        for (int i = 0; i < newsItems.length(); i++) {

            JSONObject c = newsItems.getJSONObject(i);

            Log.e("po fillo procesimin e ", String.valueOf(i));
            String tittle = c.getString(TimeUtils.TAG_TITLE);
            String desc = c.getString(TimeUtils.TAG_DESC);
            String source = c.getString(TimeUtils.TAG_SOURCE);
            String id = c.getString(TimeUtils.TAG_ID);
            String link = c.getString(TimeUtils.TAG_LINK);
            String published_time = c.getString(TimeUtils.TAG_PUB_TIME);
            String image_url = c.getString(TimeUtils.TAG_IMAGE_URL);
            String newsList = c.getString(TimeUtils.TAG_CLUSTER);
            // download the image;
            Bitmap bitmap = null;


             try { // Download Image from URL 
                 InputStream input = new
              java.net.URL(image_url) .openStream(); // Decode Bitmap

              bitmap = BitmapFactory.decodeStream(input); } catch
              (Exception e) {

              }


            news_home_data.add(new NewsItem(tittle, desc, source, id,
                    link, published_time, bitmap,newsList));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return news_home_data;
}

@SuppressLint("ResourceAsColor")
@Override
protected void onPostExecute(ArrayList<NewsItem> news_home_data) {
    customNewsHomeAdapter = new NewsHomeAdapter(homeFragmentContext,
            news_home_data);
    listView.setAdapter(customNewsHomeAdapter);
    // setting the nav drawer list adapter
    mProgressDialog.dismiss();
}
}

适配器如下所示。

NesHomeAdapter.java

package com.dev.apk.time.al;

public class NewsHomeAdapter  extends BaseAdapter{

    private ArrayList<NewsItem> news_data;

    private LayoutInflater layoutInflater;

    public NewsHomeAdapter(Context context, ArrayList<NewsItem> news_data) {
        this.news_data = news_data;
        layoutInflater = LayoutInflater.from(context);
    }

    public int getCount() {
        return news_data.size();
    }

    public Object getItem(int position) {
        return news_data.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.news_home_row, null);
            holder = new ViewHolder();
            holder.tittle = (TextView) convertView.findViewById(R.id.tittle);
            holder.source = (TextView) convertView.findViewById(R.id.source);
            holder.published_time = (TextView) convertView.findViewById(R.id.published_time);
            holder.news_image = (ImageView) convertView.findViewById(R.id.news_image);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.tittle.setText(((NewsItem) news_data.get(position)).getTittle());
        holder.source.setText(((NewsItem) news_data.get(position)).getSource());
        holder.published_time.setText(((NewsItem) news_data.get(position)).getPublishedTime());
        holder.news_image.setImageBitmap(((NewsItem) news_data.get(position)).getImage());


        return convertView;
    }

    static class ViewHolder {
         ImageView news_image;
         TextView tittle;
         TextView source;
         TextView published_time;

    }       
}

因为我有自定义列表视图。对于每一行,我都有一个图像,该图像是根据来自JSON的URL下载的。但我第一次有至少40个新闻,意味着40张图片。显示新闻需要花费太多时间。

有人可以帮我如何同时下载图片,然后更新listView,还是有办法显示新闻,标题,描述等,然后更新图片?

2 个答案:

答案 0 :(得分:0)

使用此库UrlImageViewHelper

致电

UrlImageViewHelper.setUrlDrawable(yourImageView, "http://example.com/image.png", R.drawable.your_loading_image);

在您的适配器中,它将首先创建列表并稍后下载图像,当图像下载时,它将显示your_loading_image,下载的图像将很快显示

编辑:
确切地说,类NewsItem中的getImage()函数返回的Image应该是图像的String url,并替换此行

holder.news_image.setImageBitmap(((NewsItem) news_data.get(position)).getImage());

UrlImageViewHelper.setUrlDrawable(holder.news_image, news_data.get(position).getImage(), R.drawable.your_loading_image);


我也遇到过这个问题,UrlImageViewHelper是解决这个问题的最简单的方法,只需导入库并使用一行就可以得到你想要的东西,不需要使用AsyncTask来加载图像来定义你自己的AsyncTask作为库本身

答案 1 :(得分:0)

我建议您在Android中使用AsyncTask。请查看http://developer.android.com/reference/android/os/AsyncTask.html

这将有助于您在后台运行并将您的进度或下载的图像发布到imageview上。

new AsyncTask<String,Void,Void>(){
@Override
protected Void doInBackground(String...arg){
   //download the image against the url, and run in the background as not on UI thread.
}

@Override
protected void onPostExecute(Void v){
    //Load the imageview with the downloaded image.
}

}.execute(url1,url2,url3);