如何在android studio中的gridview中使用图像路径加载图像?

时间:2015-11-29 11:34:48

标签: android gridview android-asynctask

如何使用从mysql数据库获取的imagepath显示图像到gridview。我尝试了很多但无法做到。

这是我的asynctask代码:

public class sampling_info extends AsyncTask<String, String, JSONObject> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(SamplingActivity.this);
        pDialog.setMessage("Product..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... params) {
        // TODO Auto-generated method stub

        String doc = dcname.toString();
        ArrayList<NameValuePair> namevaluepair = new ArrayList<NameValuePair>();
        namevaluepair.add(new BasicNameValuePair("docname", doc));


        JSONObject json = jParser.makeHttpRequest(URL_SAMPLING, "POST",
                namevaluepair);


        return json;
    }

    protected void onPostExecute(JSONObject json) {
        // dismiss the dialog once done
        pDialog.dismiss();

        if (json != null) {
            try {

                JSONArray jarray = json.getJSONArray("product_entered");

                Log.d("jarray in sampling : ", "" + jarray.toString());

                for (int i = 0; i < jarray.length(); i++) {

                    JSONObject jobj = jarray.getJSONObject(i);

                    String docname = jobj.getString("docname");
                    String imagep= jobj.getString("image_path");

                    GridItem gItem= new  GridItem();

                    gItem.setTitle("sagar");
                     gItem.setImage(imagep);

                     mgrid.add(gItem);

                    Log.d("jobj : ", "" + jobj);
                    Log.d("jobj docname", "" + docname);
                }

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

            gridAdapter = new GridViewAdapter(SamplingActivity.this, R.layout.grid_item_layout,mgrid);
            gridview.setAdapter(gridAdapter);
        }

    }

我这个asynctask从数据库中获取imagepath并将其存储在 imagep 变量中并将其传递给 GridItem类

这是我的网格类:

public class GridItem {
private Bitmap image;
private String title,image1;

public GridItem(Bitmap image) {
    this.image=image;
}

public Bitmap getImage() {
    return image;
}

public Bitmap setImage(String image) {  // this is where am trying to set my image but can't do.
    try {


    } catch (Exception e) {

    }
    return null;
}

这是我的适配器类:

public GridViewAdapter(Context mContext, int layoutResourceId,
                       ArrayList<GridItem> mGridData) {
    super(mContext, layoutResourceId, mGridData);
    this.layoutResourceId = layoutResourceId;
    this.mContext = mContext;
    this.mGridData = mGridData;
}

/**
 * Updates grid data and refresh grid items.
 *
 * @param mGridData
 */
public void setGridData(ArrayList<GridItem> mGridData) {
    this.mGridData = mGridData;
    notifyDataSetChanged();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    //ViewHolder holder;
ImageView   imageView = (ImageView) row
            .findViewById(R.id.grid_item_image);

    if (row == null) {
        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        //  holder = new ViewHolder();
        //imageView = (ImageView) convertView;
        TextView titleTextView = (TextView) row
                .findViewById(R.id.grid_item_title);


   imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

    } else {

    }

    GridItem item = mGridData.get(position);

    imageView.setImageBitmap(item.getImage());



    return row;
  }

2 个答案:

答案 0 :(得分:2)

我建议您使用Universal Image Loader

首先,将“lib”目录中的jar文件的最新版本包含到项目中

适配器中的

ImageLoader imageLoader = null;
DisplayImageOptions options;
适配器承包商中的

    imageLoader = ImageLoader.getInstance();
    options = new DisplayImageOptions.Builder()
            /*.displayer(new RoundedBitmapDisplayer((int) 27.5f))*/
            .showImageOnLoading(R.drawable.thumb_square)
            .showImageForEmptyUri(R.drawable.thumb_square)
            .showImageOnFail(R.drawable.thumb_square)
            .cacheInMemory(true)
            .cacheOnDisc(true)
            .considerExifParams(true)
            .imageScaleType(ImageScaleType.NONE)
            .bitmapConfig(Bitmap.Config.RGB_565)
            /*.postProcessor(new BitmapProcessor() {
                @Override
                public Bitmap process(Bitmap bitmap) {
                    int w = bitmap.getWidth();
                    int h = bitmap.getHeight();
                    float r = ((float)h / (float)w);
                    ExceptionHelpers.dLog("POST_PROCESSOR", "width : " + w + " , height : " + h + " , R1 : " + r + " , W : " + UIHelpers.width + " , Percent W : " + UIHelpers.setPercentW(r));
                    return Bitmap.createScaledBitmap(bitmap, UIHelpers.width, UIHelpers.setPercentW(r), false);
                }
            })*/
            .build();

和getView:

String imgURL = "http://www.website.com/images/image_path.png";
imageLoader.init(ImageLoaderConfiguration.createDefault(mContext));
imageLoader.displayImage(imgURL, holder.img_view, options);

答案 1 :(得分:0)

首先不要将位图存储在modelClass中,或者你可以添加sd卡路径或图像的实时网址(http://...

加载图片: - 我建议你使用Glide库 代码示例:

Glide.with(context)
        .load(url) // pass your image url
        .centerCrop()
        .placeholder(R.drawable.loading_spinner)
        .crossFade() //animate the image
        .into(myImageView);