Android layout 将图像从URL加载到ListView

Android layout 将图像从URL加载到ListView,android-layout,listview,arraylist,android-imageview,Android Layout,Listview,Arraylist,Android Imageview,我正在尝试创建一个列表视图。我成功地做到了这一点,没有从url加载照片,也没有使用自定义阵列适配器。但是,如何在不使用自定义数组适配器的情况下实现从url加载图像 我正试图使用此文件中的工作代码,但它为holder提供了一个错误 错误部分 icon = new ImageDownloaderTask(holder.imageView).execute(doctorPhoto); DoctorsActivity.java public class DoctorsActivity extends

我正在尝试创建一个列表视图。我成功地做到了这一点,没有从url加载照片,也没有使用自定义阵列适配器。但是,如何在不使用自定义数组适配器的情况下实现从url加载图像

我正试图使用此文件中的工作代码,但它为holder提供了一个错误

错误部分

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;
        }
    }

}
公共类DoctorsActivity扩展了AppCompatActivity{
私人JSONArray ArrayaAdapter;
_余额的私有静态最终字符串URL_=”http://192.168.1.28/api2/doctors.php";
字符串cancel_req_tag=“login”;
私有ListView lv;
ArrayList联系人列表;
位图图标=空;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_医生);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY\u SHOW\u CUSTOM);
getSupportActionBar().setCustomView(R.layout.toolbar_);
getSupportActionBar().setBackgroundDrawable(新的ColorDrawable(Color.parseColor(“#003764”));
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
SharedReferences SharedReferences=GetSharedReferences(Config.SHARED\u PREF\u NAME,Context.MODE\u PRIVATE);
最终字符串pid=SharedReferences.getString(Config.UID\u SHARED\u PREF,null);
contactList=新的ArrayList();
lv=(ListView)findViewById(R.id.list);
StringRequest strReq=新的StringRequest(Request.Method.POST,
URL\u用于\u余额,新响应。侦听器(){
@凌驾
公共void onResponse(字符串响应){
试一试{
JSONObject jObj=新的JSONObject(响应);
布尔错误=jObj.getBoolean(“错误”);
如果(!错误){
JSONArray contacts=jObj.getJSONArray(“用户”);
对于(int i=0;ivalue
联系人。放置(“照片”,图标);
联系人。输入(“医生”,医生全名);
联系人:put(“mobile”,doctorMobile);
//将联系人添加到联系人列表
联系人列表。添加(联系人);
}
ListAdapter=新的SimpleAdapter(
DoctorActivity.this,联系人列表,
R.layout.activity_doctors_list_项,新字符串[]{“photo”,“doctor”,
“mobile”},新int[]{R.id.photo,
R.id.doctor,R.id.mobile});
低压设置适配器(适配器);
}否则{
String errorMsg=jObj.getString(“error_msg”);
Toast.makeText(getApplicationContext(),
errorMsg,Toast.LENGTH_LONG).show();
}
}捕获(JSONException e){
e、 printStackTrace();
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Toast.makeText(getApplicationContext(),
error.getMessage(),Toast.LENGTH_LONG).show();
}
}) {
@凌驾
受保护的映射getParams(){
//将参数发布到登录url
Map params=新的HashMap();
参数put(“uid”,pid);
params.put(“lang”,Locale.getDefault().getDisplayLanguage());
返回参数;
}
};
//将请求添加到请求队列
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(streq,cancel_req_标记);
}
类ImageDownloaderTask扩展异步任务{
私有最终WeakReference imageViewReference;
公共图像下载任务(图像视图图像视图){
imageViewReference=新的WeakReference(imageView);
}
@凌驾
受保护位图doInBackground(字符串…参数){
返回下载位图(参数[0]);
}
@凌驾
受保护的void onPostExecute(位图){
如果(isCancelled()){
位图=空;
}
if(imageViewReference!=null){
ImageView=imageViewReference.get();
如果(imageView!=null){
if(位图!=null){
设置图像位图(位图);
}否则{
可绘制占位符=null;
imageView.setImageDrawable(占位符);
}
}
}
}
私有位图下载位图(字符串url){
HttpURLConnection-urlConnection=null;
试一试{
URL uri=新的URL(URL);
urlConnection=(HttpURLConnection)uri.openConnection();
public class DoctorAdapter extends ArrayAdapter<Doctors>{

    ArrayList<Doctors> doctorList;
    LayoutInflater vi;
    int Resource;
    ViewHolder holder;

    public DoctorAdapter(Context context, int resource, ArrayList<Doctors> objects) {
        super(context, resource, objects);
        vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Resource = resource;
        doctorList = objects;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        View v = convertView;

        if (v == null) {
            holder = new ViewHolder();
            v = vi.inflate(Resource, null);

            holder.imageview = (ImageView) v.findViewById(R.id.photo);
            holder.tvName = (TextView) v.findViewById(R.id.doctor);
            holder.tvMobile = (TextView) v.findViewById(R.id.mobile);

            holder.callButton = (Button) v.findViewById(R.id.btnCall);
            holder.callButton.setTag(holder);
            holder.callButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ViewHolder viewHolder = (ViewHolder) view.getTag();
                    String message= viewHolder.tvMobile.getText().toString();
                    Toast.makeText(view.getContext(), message, Toast.LENGTH_SHORT).show();
                }
            });

            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }

        holder.imageview.setImageResource(R.drawable.noimage);
        new DownloadImageTask(holder.imageview).execute(doctorList.get(position).getImage());
        holder.tvName.setText(doctorList.get(position).getName());
        holder.tvMobile.setText(doctorList.get(position).getMobile());
        return v;
    }

    static class ViewHolder {
        public ImageView imageview;
        public TextView tvName;
        public TextView tvMobile;
        public Button callButton;
    }

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }
        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }
}
// ...

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());
// ...