使用json在android listview中将图像从服务器从正方形更改为圆形

时间:2016-12-22 10:36:13

标签: android json listview bitmap

我从服务器获取图像到我的Listview但我得到方形图像而不是圆...我想要它圈.kindly help..i我是新手到android 这是我的SubMenu活动:

public class SubMenu extends Activity {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String RANK = "id";
    static String COUNTRY = "name";

    static String FLAG = "image";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.activity_sub_menu);
        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        // @Override
        //  protected void onPreExecute() {
        //  super.onPreExecute();
        // Create a progressdialog
        //   mProgressDialog = new ProgressDialog(SubMenu.this);
        // Set progressdialog title
        //   mProgressDialog.setTitle("Categories of Main categories.....");
        // Set progressdialog message
        //  mProgressDialog.setMessage("Loading...");
        //  mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        //  mProgressDialog.show();
        // }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonarray = JsonFunctions
                    .getJSONfromURL("http://cloud.granddubai.com/broccoli/menu_typeitem.php");

            try {
                // Locate the array name in JSON
//                    jsonarray = jsonobject.getJSONArray("main_menu_items");


                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();

                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("id", jsonobject.getString("id"));
                    map.put("name", jsonobject.getString("name"));

                    map.put("image", jsonobject.getString("image"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.list1);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(SubMenu.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
           // mProgressDialog.dismiss();
        }
    }
}

这是我的ImageLoader:

public class ImageLoader {

    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;
    // Handler to display images in UI thread
    Handler handler = new Handler();

    public ImageLoader(Context context) {
        fileCache = new FileCache(context);
        executorService = Executors.newFixedThreadPool(5);
    }

    final int stub_id = R.drawable.nicon1;

    public void DisplayImage(String url, ImageView imageView) {
        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);
        if (bitmap != null)
            imageView.setImageBitmap(bitmap);
        else {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }
    }

    private void queuePhoto(String url, ImageView imageView) {
        PhotoToLoad p = new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url) {
        File f = fileCache.getFile(url);

        Bitmap b = decodeFile(f);
        if (b != null)
            return b;

        // Download Images from the Internet
        try {
            Bitmap bitmap = null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl
                    .openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            conn.disconnect();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex) {
            ex.printStackTrace();
            if (ex instanceof OutOfMemoryError)
                memoryCache.clear();
            return null;
        }
    }

    // Decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f) {
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            FileInputStream stream1 = new FileInputStream(f);
            BitmapFactory.decodeStream(stream1, null, o);
            stream1.close();

            // Find the correct scale value. It should be the power of 2.
            // Recommended Size 512
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                        || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            FileInputStream stream2 = new FileInputStream(f);
            Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
            stream2.close();
            return bitmap;
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // Task for the queue
    private class PhotoToLoad {
        public String url;
        public ImageView imageView;

        public PhotoToLoad(String u, ImageView i) {
            url = u;
            imageView = i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;

        PhotosLoader(PhotoToLoad photoToLoad) {
            this.photoToLoad = photoToLoad;
        }

        @Override
        public void run() {
            try {
                if (imageViewReused(photoToLoad))
                    return;
                Bitmap bmp = getBitmap(photoToLoad.url);
                memoryCache.put(photoToLoad.url, bmp);
                if (imageViewReused(photoToLoad))
                    return;
                BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
                handler.post(bd);
            } catch (Throwable th) {
                th.printStackTrace();
            }
        }
    }

如何将其更改为圆圈??????

这是我的listview适配器:

public class ListViewAdapter extends BaseAdapter {

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    ImageLoader imageLoader;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapter(Context context,
                           ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
        imageLoader = new ImageLoader(context);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView id;
        TextView name;
        TextView population;
        ImageView image;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.list_item1, parent, false);
        // Get the position
        resultp = data.get(position);

        // Locate the TextViews in listview_item.xml
        id = (TextView) itemView.findViewById(R.id.idq);
        name = (TextView) itemView.findViewById(R.id.type1);


        // Locate the ImageView in listview_item.xml
        image = (ImageView) itemView.findViewById(R.id.subimg);

        // Capture position and set results to the TextViews
        id.setText(resultp.get(SubMenu.RANK));
        name.setText(resultp.get(SubMenu.COUNTRY));

        // Capture position and set results to the ImageView
        // Passes flag images URL into ImageLoader.class
        imageLoader.DisplayImage(resultp.get(SubMenu.FLAG), image);
        // Capture ListView item click
        /**itemView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Get the position
                resultp = data.get(position);
                Intent intent = new Intent(context, SingleItemView.class);
                // Pass all data rank
                intent.putExtra("rank", resultp.get(MainActivity.RANK));
                // Pass all data country
                intent.putExtra("country", resultp.get(MainActivity.COUNTRY));
                // Pass all data population
                intent.putExtra("population",resultp.get(MainActivity.POPULATION));
                // Pass all data flag
                intent.putExtra("flag", resultp.get(MainActivity.FLAG));
                // Start SingleItemView Class
                context.startActivity(intent);

            }
        });*/
        return itemView;
    }
}

2 个答案:

答案 0 :(得分:1)

在listview项目布局中,而不是使用ImageView使用CircleImageView。

对于CircleImageView,请使用此库: https://github.com/hdodenhof/CircleImageView

答案 1 :(得分:0)

当您从JSONArray获取网址时,您可以使用Picasso,然后在图片上执行圆形转换,如下所示:

将相关性添加到您的应用级build.gradle

compile 'com.squareup.picasso:picasso:2.5.2'

呼叫的示例是:

Picasso.with(context).load(imageurl).transform(new CircleTransform()).into(imageview);

CircleTransform需要像这样添加:

import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;

import com.squareup.picasso.Transformation;

public class CircleTransform implements Transformation {
    @Override
    public Bitmap transform(Bitmap source) {
        int size = Math.min(source.getWidth(), source.getHeight());

        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;

        Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
        if (squaredBitmap != source) {
            source.recycle();
        }

        Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        BitmapShader shader = new BitmapShader(squaredBitmap,
                BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
        paint.setShader(shader);
        paint.setAntiAlias(true);

        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);

        squaredBitmap.recycle();
        return bitmap;
    }

    @Override
    public String key() {
        return "circle";
    }
}

修改

imageLoader.DisplayImage(resultp.get(SubMenu.FLAG), image);所在的行代替Picasso.with(context).load(resultp.get(SubMenu.FLAG)).transform(new CircleTransform()).into(image);

编辑2

如果路径为空,您可以在资源中使用Picasso的占位符功能和drawable。

Picasso.with(context).load(resultp.get(SubMenu.FLAG)).Placeholder(R.drawable.placeholderimage).transform(new CircleTransform()).into(image);`

如果路径永远不会为空,则需要通过记录从url获取的信息来检查您获得的Json

map.put("image", jsonobject.getString("image"));
Log.e("image_url", jsonobject.getString("image"));

这将显示在Android Studio左下角的Run标签或Android Monitor标签中。在使用代码加载之前,查看网址是否正常工作。

编辑3

因此我将信息从Activity传递到Adapter而不是HashMap的方式我使用模型。

所以不要添加arraylist.add(map);添加arrayList.add(new DataModel(jsonobject.getString("id"), jsonobject.getString("name"), jsonobject.getString("image"))

然后创建一个名为DataModel的类,它看起来像这样:

public class DataModel {

private String id;
private String name;
private String imageurl;

public DataModel(String id, String name, String imageurl) {
    this.id = id;
    this.name = name;
    this.imageurl = imageurl;
}

public String getId() {return id;}

public String getName() {return name;}

public String getImageUrl() { return imageurl; }

}

然后在ListViewAdapter中添加

代替resultP = data.get(position)执行DataModel dataModel = data.get(position);

然后setText和以前一样:

id.setText(dataModel.getId());
name.setText(dataModel.getName());
Picasso.with(context).load(dataModel.getImageUrl()).Placeholder(R.drawable.placeholderimage).transform(new CircleTransform()).into(image);

这对你有用。