如何使用android baseadapter加载图像?

时间:2013-10-01 09:42:49

标签: android listview baseadapter

我的项目没有错误,但在加载时,Listview中不会加载图像。

以下是示例图片

sample at the first working image

但是在拖动ListView之后,所有图像都会加载。

sample draggened image load

请帮助。抱歉英文不好。

Categoryadapter.java

package com.medyasef.dernek.tjod;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by olkunmustafa on 26.09.2013.
 */
public class CategoryAdapter extends BaseAdapter {
    private String LOG_NAME = "HATA";
    private List<Categoryicerikler> list_view;
    private HashMap<Integer,Bitmap> bitmaplist;
    private Context mContext;
    private Categories categories = new Categories();


    public CategoryAdapter(List<Categoryicerikler> list_view, Context mContext) {
        this.list_view = list_view;
        this.mContext = mContext;
        bitmaplist = new HashMap<Integer, Bitmap>();

        for (int i = 0; i < list_view.size() ; i++) {
            Categoryicerikler bitmap_icerikler = list_view.get(i);
            setBitmapFromURL(bitmap_icerikler.getCategory_post_image(),i);
        }
    }
    /*
    Burada resimleri çekmek için thread oluşturuyoruz.
    Resim linkini ve ImageView'i veriyoruz ve ekrana basmasını sağlıyoruz.
     */
    public void setBitmapFromURL(final String src,final int value) {
        new Thread(
                new Runnable()
                {
                    @Override
                    public void run() {
                        HttpURLConnection connection= null;
                        try {
                            URL url = new URL(src);
                            connection = (HttpURLConnection) url.openConnection();
                            connection.setRequestMethod("GET");
                            connection.setDoInput(true);
                            connection.setDoOutput(true);
                            connection.connect();
                            InputStream input = connection.getInputStream();
                            final Bitmap myBitmap = BitmapFactory.decodeStream(input);
                            try {
                                bitmaplist.put(value,myBitmap);
                            }
                            catch (Exception e){
                                Log.d(LOG_NAME,e.getMessage());
                                Log.d(LOG_NAME,"Resim ekleme işlemi başarısız.");
                            }


                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        finally {
                            connection.disconnect();
                        }
                    }
                }).start();
    }

    @Override
    public int getCount() {
        return list_view.size();
    }

    @Override
    public Object getItem(int position) {
        return list_view.get(position);
    }

    @Override
    public long getItemId(int position) {
        return list_view.indexOf(getItem(position));
    }

    @Override
    public View getView(int position, View convertview, ViewGroup viewGroup) {
        Categoryicerikler categoryicerikler = list_view.get(position);
        ViewHolder holder = null;

        if(convertview==null){
            Log.d(LOG_NAME,"sonuc");
            convertview = LayoutInflater.from(mContext).inflate(R.layout.categories,viewGroup,false);
            holder = new ViewHolder();
            holder.txtTitle = (TextView) convertview.findViewById(R.id.category_posttitle);
            holder.txtDate  = (TextView) convertview.findViewById(R.id.category_postdate);
            holder.imageView  = (ImageView) convertview.findViewById(R.id.category_image);
            convertview.setTag(holder);
            Categories.categoryAdapter.notifyDataSetChanged();
        }
        else {
            holder = (ViewHolder) convertview.getTag();
        }

        holder.txtTitle.setText(categoryicerikler.getCategory_posttitle());
        holder.txtDate.setText(categoryicerikler.getCategory_postdate());
        try {
        holder.imageView.setImageBitmap(bitmaplist.get(position));
        }
        catch (Exception e){

        }

        return convertview;
    }

    /*private view holder class*/
    private class ViewHolder {
        ImageView imageView;
        TextView txtTitle;
        TextView txtDate;
    }
}

Categoryicerikler.java

    package com.medyasef.dernek.tjod;

import android.graphics.Bitmap;
import android.widget.ImageView;

/**
 * Created by olkunmustafa on 26.09.2013.
 */
public class Categoryicerikler {
    private String category_posttitle;
    private String category_postdate;
    private String category_post_content;
    private String category_post_image;

    public Categoryicerikler( String category_posttitle, String category_postdate, String category_post_content,String post_image) {
        this.category_posttitle = category_posttitle;
        this.category_postdate = category_postdate;
        this.category_post_content = category_post_content;
        this.category_post_image = post_image;
    }

    public String getCategory_posttitle() {
        return category_posttitle;
    }

    public void setCategory_posttitle(String category_posttitle) {
        this.category_posttitle = category_posttitle;
    }

    public String getCategory_postdate() {
        return category_postdate;
    }

    public void setCategory_postdate(String category_postdate) {
        this.category_postdate = category_postdate;
    }

    public String getCategory_post_content() {
        return category_post_content;
    }

    public void setCategory_post_content(String category_post_content) {
        this.category_post_content = category_post_content;
    }

    public String getCategory_post_image() {
        return category_post_image;
    }

    public void setCategory_post_image(String category_post_image) {
        this.category_post_image = category_post_image;
    }
}

Categories.java

package com.medyasef.dernek.tjod;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.Html;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

/**
 * Created by olkunmustafa on 25.09.2013.
 */
public class Categories extends Activity {
    private List<Categoryicerikler> content_list;
    public static CategoryAdapter categoryAdapter;
    private ListView main_category;
    private static HashMap<Integer,Bitmap> bitmaplist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_categories);
        main_category = (ListView) findViewById(R.id.main_category);
        new GetCategory().execute();
    }

    private class GetCategory extends AsyncTask<Void,Void,String> {

        @Override
        protected void onPreExecute() {
            Toast.makeText(Categories.this, "İslem Baslıyor Bekleyiniz", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected String doInBackground(Void... voids) {
            /*
            Burada internete bağlanıp json veriyi string cinsinden çekiyoruz.
             */
            InternetConnection internetcon = new InternetConnection();
            String json_result = internetcon.get_json_data();
            return json_result;
        }

        @Override
        protected void onPostExecute(String data) {
            /*
            Gelen string veriyi json_to_list_view metoduna veriyorum
            Bu metot gelen json verisinin içeriklerini doldurarak bana birt liste dönderir.
             */
            try {
                content_list = GetJson.json_to_list_view(data);
            } catch (JSONException e) {
                Log.d("Json_Error","Json çekilirken hata oluştu");
            }
            categoryAdapter = new CategoryAdapter(content_list,Categories.this);
            main_category.setAdapter(categoryAdapter);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

如果您只是想在列表视图中加载图片,我建议您使用Picasso

它简单,快速,几乎可以为您自动完成所有操作。您也不必关心取消活动销毁请求。所以我想如果您只想将图像加载到ListView中的ImageView中,这对您来说是最好的开始。

例如在您的适配器中,您可以使用:

Picasso.with(context)
    .load(url)
    .placeholder(R.drawable.placeholder)
    .error(R.drawable.error)
    .into(imageView);

其中imageview是listview单元格的ImageView

答案 1 :(得分:0)

使用通用image loader library,然后按照以下方式

 ---------------------------------------------------------
    1 - options = new DisplayImageOptions.Builder()
            .showStubImage(R.drawable.physicalgift_normal)
            .cacheInMemory()
            .cacheOnDisc()
            .displayer(new RoundedBitmapDisplayer(10))
            .build();
            imageLoader=ImageLoader.getInstance();
            ImageLoaderConfiguration imgconfig=ImageLoaderConfiguration.createDefault(context);
            imageLoader.init(imgconfig);
    ----------------------------------------------------------

    2 - String url=list.get(position).getThumbUrl();
            if(url != null && url !="")
                imageLoader.displayImage(Utils.getEncodedUrl(url), holder.img, options);

    ------------------------------------------------------------
    3 - SubCatAdapter adapter = new SubCatAdapter(SubCategoryActivity.this,
                    mlist);
            list.setAdapter(adapter);
------------------------------------------------------------
    full example is here


    public class SubCatAdapter extends BaseAdapter {
        private ArrayList<SubcategoryData> list;
        private LayoutInflater inflator;
        public ImageLoader imageLoader;
        private DisplayImageOptions options;

        public SubCatAdapter(Context context, ArrayList<SubcategoryData> mlist) {
            super();
            this.list = mlist;
            this.inflator = LayoutInflater.from(context);
            options = new DisplayImageOptions.Builder()
            .showStubImage(R.drawable.physicalgift_normal)
            .cacheInMemory()
            .cacheOnDisc()
            .displayer(new RoundedBitmapDisplayer(10))
            .build();
            imageLoader=ImageLoader.getInstance();
            ImageLoaderConfiguration imgconfig=ImageLoaderConfiguration.createDefault(context);
            imageLoader.init(imgconfig);
        }

        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

            View view = convertView;
            ViewHolder holder = null;

            if (convertView == null) {
                view = inflator.inflate(R.layout.row_subcat, null);

                holder = new ViewHolder();
                holder.txt_Name = (TextView) view.findViewById(R.id.txt_name);
                holder.img=(ImageView)view.findViewById(R.id.img_row);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.txt_Name.setText(list.get(position).getName());
            String url=list.get(position).getThumbUrl();
            if(url != null && url !="")
                imageLoader.displayImage(Utils.getEncodedUrl(url), holder.img, options);

            return view;
        }

        static class ViewHolder {
            TextView txt_Name;
            ImageView img;

        }
    }