1

这个项目我已经在我的可绘制对象中完成了图像,但现在我想通过使用 Asynctask 从 JSON 获取图像 url 并显示它。我制作了提供如下 json 字符串的 php。

我想通过使用 JSON 中的 AsyncTask 来获取图像(url)的路径。我想使用来自 json 的数据而不是public mThumbId = {...};

 {"count":"28","data":
    [{"id":"1",
        "first_name":"man",
        "last_name":"woman",
        "username":"man",
        "password":"4f70432e636970de9929bcc6f1b72412",
        "email":"man@gmail.com",
        "url":"http://vulcan.wr.usgs.gov/Imgs/Jpg/MSH/Images/MSH64_aerial_view_st_helens_from_NE_09-64_med.jpg"},
    {"id":"2",
            "first_name":"first",
            "last_name":"Last Name",
            "username":"user",
            "password":"1a1dc91c907325c69271ddf0c944bc72",
            "email":"first@gmail.com",
            "url":"http://www.danheller.com/images/California/Marin/Scenics/bird-view-big.jpg"},
    {"id":"3",
            "first_name":"first",
            "last_name":"Last Name",
            "username":"user",
            "password":"1a1dc91c907325c69271ddf0c944bc72",
            "email":"0",
            "url":"http://www.hermes.net.au/bodhi/images/view/large/view_03.jpg"}]}

AndroidGridLayoutActivity

GridView gridView = (GridView) findViewById(R.id.grid_view);        
    gridView.setAdapter(new ImageAdapter(this));

    gridView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {

            Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
            i.putExtra("id", position);
            startActivity(i);
        }
    });

图像适配器

public class ImageAdapter extends BaseAdapter {
private Context mContext;

// Keep all Images in array
public Integer[] mThumbIds = {
        R.drawable.pic_1, R.drawable.pic_2,
        R.drawable.pic_3, R.drawable.pic_4,
        R.drawable.pic_5, R.drawable.pic_6,
        R.drawable.pic_7, R.drawable.pic_8,
        R.drawable.pic_9, R.drawable.pic_10,
        R.drawable.pic_11, R.drawable.pic_12,
        R.drawable.pic_13, R.drawable.pic_14,
        R.drawable.pic_15
};

// Constructor
public ImageAdapter(Context c){
    mContext = c;
}

public int getCount() {
    return mThumbIds.length;
}

public Object getItem(int position) {
    return mThumbIds[position];
}

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

public View getView(int position, View convertView, ViewGroup parent) {         
    ImageView imageView = new ImageView(mContext);
    imageView.setImageResource(mThumbIds[position]);
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
    return imageView;
}

}

全图像活动

Intent i = getIntent();
    int position = i.getExtras().getInt("id");
    ImageAdapter imageAdapter = new ImageAdapter(this);

    ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
    imageView.setImageResource(imageAdapter.mThumbIds[position]);
4

2 回答 2

0

You have to first extract the urls from json in a array and then use below code to load image as bitmap dynamically using Async Task.

Bitmap bm[]=new Bitmap[3];
ImageAdapter img;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        bm[0]=null;
        bm[1]=null;
        bm[2]=null;


 InputStream is= getDataFromServer();
      String asd=getResponseFromStream(is);
      try {
        JSONObject jsn=new JSONObject(asd);
        JSONArray jd=jsn.getJSONArray("data");
        for(int i=0;i<jd.length();i++)
        {
            JSONObject j_object=jd.getJSONObject(i);
            String url=j_object.getString("url");
            urls.add(url);
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


       img=new ImageAdapter(this);
        GridView gridView = (GridView) findViewById(R.id.grid_view);        
        gridView.setAdapter(img);
        new  ImageDownloader().execute();
        gridView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {

                Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
                i.putExtra("id", position);
                startActivity(i);
            }
        });

    }
    ProgressDialog prg;
    private class ImageDownloader extends AsyncTask<Integer, Integer, String>
    {
        @Override
        public void onPreExecute()
        {
            prg=ProgressDialog.show(LazyLoadActivity.this, null, 
                    "Loading...");
        }

        protected void onPostExecute(String result)
        {
            prg.hide();




        }
          protected void onProgressUpdate(Integer... progress) {
              img.notifyDataSetChanged();
             }
        protected String doInBackground(Integer... a)
        {
            for(int i=0;i<3;i++)
            {
                bm[i]=downloadBitmap(urls[i]);
                this.publishProgress(i);
            }
            return "";
        }
    }
    public Integer[] mThumbIds = {
            R.drawable.ic_launcher, R.drawable.ic_launcher,
            R.drawable.ic_launcher
    };

    public class ImageAdapter extends BaseAdapter {
        private Context mContext;

        // Keep all Images in array

        // Constructor
        public ImageAdapter(Context c){
            mContext = c;
        }

        public int getCount() {
            return mThumbIds.length;
        }

        public Object getItem(int position) {
            return mThumbIds[position];
        }

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

        public View getView(int position, View convertView, ViewGroup parent) {         
            ImageView imageView = new ImageView(mContext);
            if(bm[position]==null)
            imageView.setImageResource(mThumbIds[position]);
            else
                imageView.setImageBitmap(bm[position]);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
            return imageView;
        }

        }
Bitmap downloadBitmap(String url) {

        final HttpClient client = new DefaultHttpClient();
        final HttpGet getRequest = new HttpGet(url);

        try {
            HttpResponse response = client.execute(getRequest);
            final int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) { 
                Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); 
                return null;
            }

            final HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream inputStream = null;
                try {
                    inputStream = entity.getContent(); 
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    return bitmap;
                } finally {
                    if (inputStream != null) {
                        inputStream.close();  
                    }
                    entity.consumeContent();
                }
            }
        } catch (Exception e) {
            // Could provide a more explicit error message for IOException or IllegalStateException
            getRequest.abort();
            Log.e("ImageDownloader", "Error while retrieving bitmap from " + url);
        } finally {
            if (client != null) {
                //client.
            }
        }
        return null;
    }
于 2012-10-08T10:26:03.767 回答
0

我认为这个简单的链接将完全回答您的问题:

https://github.com/novoda/ImageLoader

还有我自己的实现:

https://github.com/iRail/BeTrains-for-Android/blob/master/src/tof/cv/mpp/adapter/TweetItemAdapter.java

编辑

你真正需要做的:

1)解析 JSON:网上有成千上万的教程,或者使用很棒的 GSON 库。

2) 一旦 JSON 被解析,你会得到一个对象数组。

3) 在您的适配器中,您可能需要扩展 ArrayAdapter。

4)在getView()方法中,分析我上面的2个链接并使用类似的东西:

imageLoader.DisplayImage(tweet.profile_image_url, activity, holder.image);

于 2012-10-08T09:43:00.867 回答