使用Volley加载图像

时间:2016-03-05 06:01:46

标签: android android-volley

我希望在URL列表中显示图像时,如果没有来自服务端的图像URL,那么我想显示特定索引的默认图像。为此,我在Volley中使用array adapter进行图像加载。现在我的问题是当我使用默认图像时,图像没有正确显示,有时它与另一个图像重叠。当我没有使用默认图像时,它工作正常。这是我的代码,请告诉我这有什么问题?提前谢谢。

这是我的Adapter类,

 public class CustomLocalAlertAdapter extends ArrayAdapter<LocalListItem>
        implements AppConstants {

    Activity a;
    ViewHolder holder;

    ImageView mImageview;
    private Object mImageLoader;

    @SuppressWarnings("static-access")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        // return super.getView(position, convertView, parent);
        LocalListItem LocalList = getItem(position);

        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(
                    R.layout.activity_add_local_all_alert_details, parent,
                    false);

            holder = new ViewHolder();

            holder.missingTitle = (TextView) convertView
                    .findViewById(R.id.missingTitle);
            holder.missingDetails = (TextView) convertView
                    .findViewById(R.id.missingDetails);

            holder.missingImage = (NetworkImageView) convertView
                    .findViewById(R.id.missingImage);
            holder.suspectImage = (NetworkImageView) convertView
                    .findViewById(R.id.suspectImage);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        String allAlertSuspectDetails = "";

        String allAlertVehicleDetails = "";

        String allAlertPersonDetails = "";

        if (LocalList.title.equalsIgnoreCase("missing_vehicle_report")) {

            allAlertPersonDetails = "";
            allAlertSuspectDetails = "";
            holder.missingTitle.setText("Missing Vehicle");

            allAlertVehicleDetails = "\n" + "Year: " + LocalList.Year + "\n"
                    + "Make: " + LocalList.Make + "\n" + "Model: "
                    + LocalList.Model + "\n" + "Color: " + LocalList.Color
                    + "\n" + "LisencePlateNo: " + LocalList.LisencePlateNo
                    + "\n" + "Vin: " + LocalList.Vin + "\n" + "Place: "
                    + LocalList.Place;

            holder.suspectImage.setVisibility(View.GONE);

        } else {

            holder.suspectImage.setVisibility(View.VISIBLE);

            allAlertVehicleDetails = "";

            holder.missingTitle.setText("Missing Person");

            allAlertPersonDetails = "\n" + "Name: " + LocalList.personName
                    + "\n" + "Height: " + LocalList.height + "\n"
                    + "Unique Mark: " + LocalList.uniqueMark + "\n"
                    + "Last seen: " + LocalList.lastSeen + "\n"
                    + "Date Missing: " + LocalList.dateMissing + "\n"
                    + "Police department: " + LocalList.policeDept + "\n"
                    + "Police dept.phone: " + LocalList.policePhn + "\n" + "\n";

            if (LocalList.suspectName.equalsIgnoreCase("")
                    || LocalList.suspectName.equalsIgnoreCase("null")
                    || LocalList.suspectName.equalsIgnoreCase(" ")) {
                allAlertSuspectDetails = "";

                holder.suspectImage.setVisibility(View.GONE);

            } else {
                allAlertSuspectDetails = "Suspect name: "
                        + LocalList.suspectName + "\n" + "Vehicle Color: "
                        + LocalList.vehicleColor + "\n" + "Vehicle Year: "
                        + LocalList.vehicleYear + "\n" + "Vehicle Make: "
                        + LocalList.vehicleMake + "\n" + "Vehicle Model: "
                        + LocalList.vehicleModel;
            }
        }


        holder.missingDetails.setText(allAlertVehicleDetails
                + allAlertPersonDetails + allAlertSuspectDetails);

        if (LocalList.title.equalsIgnoreCase("missing_vehicle_report")) {
            if (LocalList.vehicleImg.trim().equalsIgnoreCase(
                    "")) {

                holder.missingImage.setImageResource(R.drawable.no_image_found);
            } else {

                holder.missingImage.setImageUrl(LocalList.vehicleImg,
                        VolleySingleton.getInstance(getContext())
                                .getImageLoader());
            }
        } else {
            if (LocalList.personImage.trim().equalsIgnoreCase(
                    "")) {
                holder.missingImage.setImageResource(R.drawable.no_image_found);

            } else {

                holder.missingImage.setImageUrl(LocalList.personImage,
                        VolleySingleton.getInstance(getContext())
                                .getImageLoader());
            }
            if (LocalList.suspectImage.trim().equalsIgnoreCase(
                    "")) {
                holder.suspectImage.setImageResource(R.drawable.no_image_found);

            } else {

                holder.suspectImage.setImageUrl(LocalList.suspectImage,
                        VolleySingleton.getInstance(getContext())
                                .getImageLoader());
            }

        }

        return convertView;

    }

    public static class ViewHolder {

        TextView missingTitle;
        TextView missingDetails;
        NetworkImageView missingImage;
        NetworkImageView suspectImage;
    }

    public CustomLocalAlertAdapter(Context context,
            ArrayList<LocalListItem> ListItem, Activity a) {
        super(context, 0, ListItem);
        // TODO Auto-generated constructor stub
        this.a = a;

    }

}

这是我的VolleySingleton课程,

    public class VolleySingleton {
    private static VolleySingleton instance;
    private RequestQueue requestQueue;
    private static ImageLoader imageLoader;

    private VolleySingleton(Context context) {
        requestQueue = Volley.newRequestQueue(context);
        imageLoader = new ImageLoader(requestQueue,
                new ImageLoader.ImageCache() {
                    private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);

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

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

    public static VolleySingleton getInstance(Context context) {
        if (instance == null) {
            instance = new VolleySingleton(context);
        }
        return instance;
    }

    public RequestQueue getRequestQueue() {
        return requestQueue;
    }

    public static ImageLoader getImageLoader() {
        return imageLoader;
    }
}

1 个答案:

答案 0 :(得分:0)

首先按如下方式创建一个文件MultipartRequest:

public class MultipartRequest extends Request<String> {
private MultipartEntityBuilder entity = MultipartEntityBuilder.create();
private final Response.Listener<String> mListener;
private final File file;
private final HashMap<String, String> params;

public MultipartRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener, File file, HashMap<String, String> params)
{
    super(Method.POST, url, errorListener);

    mListener = listener;
    this.file = file;
    this.params = params;
    buildMultipartEntity();
    buildMultipartEntity2();

}



private void buildMultipartEntity()
{
    entity.addBinaryBody(KEY_IMAGE, file, ContentType.create("image/jpeg"), file.getName());
    entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));

    try
    {
        for ( String key : params.keySet() ) {
            entity.addPart(key, new StringBody(params.get(key)));
        }
    }
    catch (UnsupportedEncodingException e)
    {
        VolleyLog.e("UnsupportedEncodingException");
    }
}

@Override
public String getBodyContentType()
{
    return entity.build().getContentType().getValue();
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> headers = super.getHeaders();

    if (headers == null
            || headers.equals(Collections.emptyMap())) {
        headers = new HashMap<String, String>();
    }

    headers.put("Accept", "application/json");

    return headers;
}

@Override
public byte[] getBody() throws AuthFailureError
{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try
    {
        entity.build().writeTo(bos);
    }
    catch (IOException e)
    {
        VolleyLog.e("IOException writing to ByteArrayOutputStream");
    }
    return bos.toByteArray();
}
/**
 * copied from Android StringRequest class
 */
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
    String parsed;
    try {
        parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
    } catch (UnsupportedEncodingException e) {
        parsed = new String(response.data);
    }
    return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}

@Override
protected void deliverResponse(String response) {
    mListener.onResponse(response);
}}

在您的活动中,只需按照以下方式制作多部分请求:

 public void uploadImage()
{
    try {
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Loading...");
        pDialog.show();

           HashMap params = new HashMap<String, String>();

            params.put(KEY_NAME, name);
        MultipartRequest sr = new MultipartRequest( UPLOAD_URL, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                if ((pDialog != null) && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                Log.d("file", f + "");
                Log.d("", ".......response====" + response.toString());

                ////////
                try {
                    JSONObject object = new JSONObject(response);
                    String serverCode = object.getString("code");
                    if (serverCode.equalsIgnoreCase("0")) {

                    }
                    if (serverCode.equalsIgnoreCase("1")) {
                        try {

                            if ("1".equals(serverCode)) {
                                JSONObject object1 = object.getJSONObject("data");

                            }
                        }