如何在arraylist中添加凌空图像请求?

时间:2015-08-19 16:13:50

标签: android android-volley

我有下面的代码2,Volley请求设置图像,array list adapter显示静态图像。

我需要帮助才能在数组列表中添加凌空请求,我想要在arraylist中显示的凌空图像

如何做到这一点,你可以帮我吗?

(注意我已经有一个phpscript,发送给我json图像的路径网址)

代码:main_activity

 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  RequestQueue mRequestQueue;

  final String IMAGE_URL =
            "http://developer.android.com/images/training/system-ui.png";
  mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);

//Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap

//Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());

//Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network);

//Start the queue
mRequestQueue.start();


ImageLoader mImageLoader = new ImageLoader(mRequestQueue, new LruBitmapCache(
            LruBitmapCache.getCacheSize(mContext)));
mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader);


CustomListAdapter adapter=new CustomListAdapter(this, itemname, imgid);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);

list.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
        // TODO Auto-generated method stub
        String Slecteditem= itemname[+position];
        Toast.makeText(getApplicationContext(), Slecteditem, Toast.LENGTH_SHORT).show();

    }
});

}

arraylistadapter

package com.example.p;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomListAdapter extends ArrayAdapter<String> {

    private final Activity context;
    private final String[] itemname;
    private final Integer[] imgid;

    public CustomListAdapter(Activity context, String[] itemname, Integer[] imgid) {
        super(context, R.layout.mylist, itemname);
        // TODO Auto-generated constructor stub

        this.context=context;
        this.itemname=itemname;
        this.imgid=imgid;
    }

    public View getView(int position,View view,ViewGroup parent) {
        LayoutInflater inflater=context.getLayoutInflater();
        View rowView=inflater.inflate(R.layout.mylist, null,true);

        TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
        TextView extratxt = (TextView) rowView.findViewById(R.id.textView1);

        txtTitle.setText(itemname[position]);
        imageView.setImageResource(imgid[position]);
        extratxt.setText("Description "+itemname[position]);
        return rowView;

    };
}

和Lrubitmapcache

package com.example.p;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.util.DisplayMetrics;
import com.android.volley.toolbox.ImageLoader.ImageCache;

public class LruBitmapCache extends LruCache<String, Bitmap>
        implements ImageCache {

    public LruBitmapCache(int maxSize) {
        super(maxSize);
    }

    public LruBitmapCache(Context ctx) {
        this(getCacheSize(ctx));
    }

    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight();
    }

    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }

    // Returns a cache size equal to approximately three screens worth of images.
    public static int getCacheSize(Context ctx) {
        final DisplayMetrics displayMetrics = ctx.getResources().
                getDisplayMetrics();
        final int screenWidth = displayMetrics.widthPixels;
        final int screenHeight = displayMetrics.heightPixels;
        // 4 bytes per pixel
        final int screenBytes = screenWidth * screenHeight * 4;

        return screenBytes * 3;
    }
}

2 个答案:

答案 0 :(得分:3)

我认为为了你的目的,你应该使用Picasso或Glide,而不是Volley。

Volley这是一件了不起的事情,但对于带有图片加载的列表,最好使用更具体的图片加载库。

以下是Glide和Picasso工具的链接:

答案 1 :(得分:1)

在其他帖子中你问我帮忙。 我的图像来自休息服务器,因为Json字符串Base64编码。然后我做下一个:

  public View getView(int position, View convertView, ViewGroup parent) {
        final ObjectLogados o = items.get(position);
        final ViewHolder holder;
        View vi = convertView;
        if (vi == null){
            LayoutInflater inflater = context.getLayoutInflater();
            vi = inflater.inflate(R.layout.singlerowlog, null);// e' preciso fazer o inflate pois a view nao ainda nao esta em activity alguma
            holder = new ViewHolder();
            holder.ivImgMedLog= (ImageView) vi.findViewById(R.id.ivp_imagemedlog) ;
            holder.tv_usuario = (TextView) vi.findViewById(R.id.tv_hnomemedlogado);
            vi.setTag(holder);

        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.tv_usuario.setText(o.getUsuario());
        String imageKey="MED"+String.valueOf(o.getNr_usuario());
        final Bitmap bitmap = Common.getInstance().getBitmapFromMemCache(imageKey);
        if (bitmap != null) {
            holder.ivImgMedLog.setImageBitmap(bitmap);
        }else {
            holder.ivImgMedLog.setImageDrawable(context.getResources()
                    .getDrawable(R.drawable.empty));
            downloadimage(holder.ivImgMedLog,o.getNr_usuario());
        }

        return vi;
    }

    static class ViewHolder {
        TextView tv_usuario;
        ImageView ivImgMedLog;

    }

    private void downloadimage(final ImageView imageView,final int nr){
        //final ImageView imageView=imV;
        String url=Common.getServerURL() + "\"RetrieveImageStaff\"";
        JSONArray ja = new JSONArray();
        ja.put(nr);

        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("_parameters", ja);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, url,
                jsonBody, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                JSONObject anEntry = null, entries = null;
                String ims = "";
                try {   // TODO Auto-generated method stub
                    JSONArray LResult = response.getJSONArray("result");
                    String s = LResult.get(0).toString();
                    anEntry = new JSONObject(s);
                    ims = anEntry.getString("imagem");
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


                Bitmap decodedByte = null;
                try {
                    if (!TextUtils.isEmpty(ims)) {
                        byte[] decodedString = Base64.decode(ims, Base64.DEFAULT);
                        decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                        if (imageView != null) {
                            if (decodedByte != null) {
                                imageView.setImageBitmap(decodedByte);
                                Common.getInstance().addBitmapToMemoryCache("MED"+String.valueOf(nr), decodedByte);
                            } else {
                                imageView.setImageDrawable(imageView.getContext().getResources()
                                        .getDrawable(R.drawable.empty));
                            }
                        }
                    } else {
                        imageView.setImageDrawable(imageView.getContext().getResources()
                                .getDrawable(R.drawable.empty));
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO Auto-generated method stub
                //Log.v(TAG, error.getMessage());
                Toast.makeText(context, "Erro adquirindo imagem...." + error.getMessage(), Toast.LENGTH_SHORT).show();
                error.printStackTrace();
            }
        });
        jr.setRetryPolicy(new DefaultRetryPolicy(Common.DEFAULT_TIMEOUT_MS,
                Common.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        Common.getInstance().addToReqQueue(jr, "jreq"); //reqQueue.add(jr);
    }

您可以更改使用截击的请求并获取图像。因此,您可以将https://developer.android.com/training/volley/request.html#request-image中所述的代码更改为类似于:

的代码
ImageView mImageView;
String url = "http://i.imgur.com/7spzG.png";
mImageView = (ImageView) findViewById(R.id.myImage);
...

// Retrieves an image specified by the URL, displays it in the UI.
ImageRequest request = new ImageRequest(url,
    new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(Bitmap bitmap) {
            mImageView.setImageBitmap(bitmap);
        }
    }, 0, 0, null,
    new Response.ErrorListener() {
        public void onErrorResponse(VolleyError error) {
            mImageView.setImageResource(R.drawable.image_load_error);
        }
    });
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(request);