如何从服务器获取图像并显示到listview android?

时间:2015-07-25 11:18:03

标签: android listview

我是android的初学者,我想编写简单的应用程序来从服务器读取图像和数据并显示到listview中,我的listview xml文件是:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_gravity="center"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:src="@drawable/abc_btn_check_material" />

    <TextView
        android:id="@+id/textView1"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:text="TextView" />

</LinearLayout>

并使用此方法从服务器读取json数据:

....READ WITH ASYNCTASK
try {
                JSONArray jsonArray=new JSONArray(result);
                prgmNameList=new String[jsonArray.length()];
                prgmImages=new int[jsonArray.length()];

                for(int i=0;i<jsonArray.length();i++)
                {
                    JSONObject JsonObj=jsonArray.getJSONObject(i);
                    String TITLES=JsonObj.getString("title");
                    String imgURL=JsonObj.getString("img");
                    Log.d("BEHZAD TITLES=",TITLES);
                    .....I want read the image and show into the listview with title
}


我该如何解决这个计划?谢谢。

4 个答案:

答案 0 :(得分:2)

您必须使用本教程制作自己的自定义适配器 http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/

更重要的是,对于下载和缓存Image我建议你 https://github.com/nostra13/Android-Universal-Image-Loader

这是一个例子 http://sunil-android.blogspot.com/2013/09/lazy-loading-image-download-from.html

玩得开心! ;)

答案 1 :(得分:1)

您好,您可以创建一个BitmapDownloaderTask类来下载您的图像。

public class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {


    private String url;
    private String path, imgName;
    private final WeakReference<ImageView> imageViewReference;


    public BitmapDownloaderTask(ImageView imageView, String path, String imgName) {

        imageViewReference = new WeakReference<ImageView>(imageView);

        this.path = path;
        this.imgName = imgName;

    }//BitmapDownloaderTask


    @Override
    // Actual download method, run in the task thread
    protected Bitmap doInBackground(String... params) {
        // params comes from the execute() call: params[0] is the url.
        return getBitmapFromURL(params[0]);

    }//doInBackground


    @Override
    // Once the image is downloaded, associates it to the imageView
    protected void onPostExecute(Bitmap bitmap) {

        if (isCancelled()) {
            bitmap = null;
        }

        if (imageViewReference != null && bitmap != null) {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);

                //this is my custom method to save bitmap in the local storage
                Utility.saveBitmapToLocalStorage(bitmap, this.path, this.imgName);
            }
        }

    }//onPostExecute


    public static Bitmap getBitmapFromURL(String link) {
        /* this method downloads an Image from the given URL,
        *  then decodes and returns a Bitmap object
        */
        try {
            URL url = new URL(link);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);

            return myBitmap;

        } catch (IOException e) {
            e.printStackTrace();
            Log.e("getBmpFromUrl error: ", e.getMessage().toString());
            return null;
        }

    }//getBitmapFromURL


}//class

你可以像这样创建ListView(使用自定义适配器)

String[] strings = new String[]{"item 1","item 2","item 3"};

ListView mList = (ListView)rootView.findViewById(R.id.mListId);

MAdapter adapter = new MAdapter(this, R.layout.adapter_listview_mAdapter, strings);
mList.setAdapter(adapter);

最后在MAdapter类中,您可以使用BitmapDownloaderTask下载图像

public class MAdapter extends ArrayAdapter<YourModel> {


    public MAdapter(Context context, int resource, List<YourModel> items) {

        super(context, resource, items);

    }//MAdapter


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

        LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.adapter_listview_mAdapter, null);


        ImageView image = (ImageView)convertView.findViewById(R.id.imageId);

        YourModel model = getItem(position);

        BitmapDownloaderTask task = new BitmapDownloaderTask(image, "path", "folder_" + model.identifier);
            task.execute(url);
        }

        return convertView;

    }//getView


}//class

答案 2 :(得分:0)

只需创建一个URLConnection并为列表视图调整大小即可。所有代码都可以在这里找到:Best method to download image from url in Android。希望我能帮助你;)

答案 3 :(得分:0)

此处描述了如何创建自定义适配器和显示图像:

Using Picasso library with ListView

您可以选择另一个很棒的图书馆Glide

,而不是毕加索

它们都比使用Universal Image Loader更容易