将图像从URL加载到ListView

时间:2017-02-23 09:49:24

标签: android-layout listview arraylist android-imageview

我正在尝试制作列表视图。我没有使用自定义数组适配器在没有从url加载照片的情况下成功完成了。但是,如何在不使用自定义数组适配器的情况下实现从URL加载图像?

我正在尝试使用此thread中的工作代码,但是持有人会出错。

错误部分

icon = new ImageDownloaderTask(holder.imageView).execute(doctorPhoto);

DoctorsActivity.java

public class DoctorsActivity  extends AppCompatActivity {

    private JSONArray arrayAdapter;
    private static final String URL_FOR_BALANCE = "http://192.168.1.28/api2/doctors.php";

    String cancel_req_tag = "login";

    private ListView lv;
    ArrayList<HashMap<String, String>> contactList;
    Bitmap icon = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doctors);

        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setCustomView(R.layout.toolbar_doctors);

        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#003764")));
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);

        SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
        final String pid = sharedPreferences.getString(Config.UID_SHARED_PREF, null);

        contactList = new ArrayList<>();
        lv = (ListView) findViewById(R.id.list);

        StringRequest strReq = new StringRequest(Request.Method.POST,
                URL_FOR_BALANCE, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    if (!error) {

                        JSONArray contacts = jObj.getJSONArray("user");


                        for (int i = 0; i < contacts.length(); i++) {
                            JSONObject c = contacts.getJSONObject(i);

                            String doctorTitle = c.getString("title");
                            String doctorName = c.getString("first_name");
                            String doctorSurname = c.getString("last_name");
                            String doctorPhoto = c.getString("photo"); //image URL
                            String doctorMobile = c.getString("mobile");

                            String doctorFullName = doctorTitle+" "+doctorName+" "+doctorSurname;

                            icon = new ImageDownloaderTask(holder.imageView).execute(doctorPhoto);

                            // tmp hash map for single contact
                            HashMap<String, String> contact = new HashMap<>();

                            // adding each child node to HashMap key => value
                            contact.put("photo", icon);
                            contact.put("doctor", doctorFullName);
                            contact.put("mobile", doctorMobile);

                            // adding contact to contact list
                            contactList.add(contact);
                        }

                        ListAdapter adapter = new SimpleAdapter(
                                DoctorsActivity.this, contactList,
                                R.layout.activity_doctors_list_item, new String[]{"photo", "doctor",
                                "mobile"}, new int[]{R.id.photo,
                                R.id.doctor, R.id.mobile});

                        lv.setAdapter(adapter);



                    } else {

                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting params to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("uid", pid);
                params.put("lang", Locale.getDefault().getDisplayLanguage());
                return params;
            }
        };
        // Adding request to request queue
        AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq,cancel_req_tag);
    }
    class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {

        private final WeakReference<ImageView> imageViewReference;

        public ImageDownloaderTask(ImageView imageView) {
            imageViewReference = new WeakReference<ImageView>(imageView);
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            return downloadBitmap(params[0]);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (isCancelled()) {
                bitmap = null;
            }

            if (imageViewReference != null) {
                ImageView imageView = imageViewReference.get();
                if (imageView != null) {
                    if (bitmap != null) {
                        imageView.setImageBitmap(bitmap);
                    } else {
                        Drawable placeholder = null;
                        imageView.setImageDrawable(placeholder);
                    }
                }
            }
        }

        private Bitmap downloadBitmap(String url) {
            HttpURLConnection urlConnection = null;
            try {
                URL uri = new URL(url);
                urlConnection = (HttpURLConnection) uri.openConnection();

                final int responseCode = urlConnection.getResponseCode();
                if (responseCode != HttpURLConnection.HTTP_OK) {
                    return null;
                }

                InputStream inputStream = urlConnection.getInputStream();
                if (inputStream != null) {
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    return bitmap;
                }
            } catch (Exception e) {
                urlConnection.disconnect();
                Log.w("ImageDownloader", "Errore durante il download da " + url);
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }
            return null;
        }
    }

}

2 个答案:

答案 0 :(得分:0)

对于想要使用带有图像的listView的每个人,这是我更正的工作自定义适配器:

@Configuration
@EnableCouchbaseAuditing
@EnableConfigurationProperties({CouchbaseProperties.class})
@EnableCouchbaseRepositories(basePackages = "com....")
public class CouchbaseConfiguration extends AbstractCouchbaseConfiguration {
  ...
}

答案 1 :(得分:0)

为什么不使用像https://github.com/bumptech/glide这样的第三方库?

相关代码:

// ...

new Glide
    .with(convertView.getContext())
    .load(url)
    .centerCrop()
    .placeholder(R.drawable.noimage)
    .crossFade()
    .into(bmImage);

holder.tvName.setText(doctorList.get(position).getName());
holder.tvMobile.setText(doctorList.get(position).getMobile());
// ...
相关问题