使用Asynctask

时间:2015-06-01 09:13:15

标签: android android-asynctask bitmapimage

我有一个图像通过JSON字符串发送给我。我想在我的Android应用程序中将该字符串转换为图像,然后在我的imageview中显示该图像。我有一个问题,我使用的是Asynctask,这是我在doInBackground方法中的代码:

protected Boolean doInBackground(final String... args){

        JsonParser jsonParser = new JsonParser();
        JSONArray json = jsonParser.getJSONFromUrl(url);
        if(json!=null){
            for (int i = 0; i < json.length(); i++){
                try{
                    JSONObject c = json.getJSONObject(i);
                    String displayImageFromUrl = c.getString(imageUrl);
                    String clearUrl = displayImageFromUrl.substring(displayImageFromUrl.indexOf(",")+1);
                    byte[] decodingString = Base64.decode(clearUrl, Base64.DEFAULT);
                    bitmap = BitmapFactory.decodeByteArray(decodingString, 0 , decodingString.length);

                    String showCreatedDate = c.getString(createdDate);
                    String showArticleTitle = c.getString(articleTitle);
                    HashMap<String, String> map = new HashMap<String, String>();

                    map.put(createdDate, showCreatedDate);
                    map.put(articleTitle, showArticleTitle);

                    jsonlist.add(map);

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }else{

        }
        return null;
    }

这是我在onPostExecute()方法中的代码:

        protected void onPostExecute(final Boolean success){
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        Log.d("image please",bitmap.toString());
        ImageView showImage = (ImageView) findViewById(R.id.imageShow);
        showImage.setImageBitmap(bitmap);
        ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.activity_news,
                new String[] {createdDate, articleTitle},
                new int[] { R.id.createDate, R.id.articleTitle});
        setListAdapter(adapter);

        lv = getListView();
    }

不幸的是,nothings出现在我的logcat中。你能帮助我吗? 我错过了什么?

3 个答案:

答案 0 :(得分:1)

这是一个伪代码。如果你在项目中使用它,它应该工作。

//my image (android logo)
private String base64 = "iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAACgUlEQVRIiZ2Wv4vUQBTHP2/ZBFlEFrGS44iniLCggggWh4yVoIX4F9gIFtYiFgqWNgqChfoXHBYWXuWJF05rwe0UMWE5RI7lEJUguSPPYvJjkk32xAcbvjPz8n3v++ZlZqHDYuMRG/9+bPxBt4+/LzLevdj4XS5I54olOK/oCSAUWFY4al/RSJANRY0gX4IwfdvF0Z8XQCEW5AnwCBiInUMQFE1AJqAX53F0KoiNfxp4CQSNoA4SgInA1SBMP7Tx9NrJvSHoCmgPeAhk6lCLVTEWeCZwGHQlMt7BfwoQGR+FWyDHgc/Ac9BUZsTqWNEXQApyDLjdttkzJYqNPwT9CLKojkOBCyXFfjh4U5BTQZhuz1UAGoAsdJBgt1jQolAlZkHRpSbbTBcpMhW4WY4cDQXO1WR1LBnwvcknAJHxLwncAcbAuqJP5yuwtM0n6A2QC6AnQR4cCdPVfv7yNYVlgXOgnwSpdcRsL0utp6okZAG4rogPfANWiz3o5eJn9kQ6cJvlgQqOfvkAeq78lo8Jt4/2Kl7u06sFqLJzO74tf2nxajZCtdaz02XOGZBVCtyjwWItc9QWLM7YCVCX1kZWS6LTtEZtrShRVgivcDlu4HklshVwAxQ7Ps1zSID0/0tECiT5eOoquAv6DmSi6AHq3VDDe9gmcEWQRdDXzRoAEBt/CXgFHAKGQHFE/gF+5ngA7M9xprAt6BTkchCmX12+mQ8rdzgLjBQ2nBK9sXM6UvSxU5aJwAg40ySHjiszCNMESCLjJc5pkwThzhQgMt6vwlftXbEVhDttVPPvZGDX6ZXdEtmTs/QJwrSToPXKrEzWgB/5b91ZeA+6BfwG7fxHAfAXfJIQh9RXB18AAAAASUVORK5CYII=";

//somewhere in code
imageView = (ImageView) view.findViewById(R.id.imageView);//layout params are wrap and wrap

//weak reference is for safe using imageView when app i.e will exit and task will still be running
weakReferenceImageView = new WeakReference<ImageView>(imageView);

new AsyncTask<Void, Void, Bitmap>() {
    @Override
    protected Bitmap doInBackground(Void... params) {

        byte[] encode = Base64.decode(base64.getBytes(), 0);
        Bitmap bitmap = BitmapFactory.decodeByteArray(encode, 0, encode.length);
        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);

        if (bitmap != null) {                                      
            if (weakReferenceImageView != null) {                  
                ImageView weak = weakReferenceImageView.get();
                if (weak != null) {                           
                    weak.setImageBitmap(bitmap);              
                }                                                  
            }                                                      
        }                                                          

    }
}.execute();

如果解码错误,返回的位图将为空。 如果有效,请尝试使用我的图像(非常小)。如果它有效,则意味着你的基于64的图像有问题。

修正了一个例子,将weakReference添加为一个很好的编码样本。

答案 1 :(得分:0)

ImageView image = (ImageView) findViewById(R.id.image);
String image_url = "http://api.androidhive.info/images/sample.jpg";
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
imgLoader.DisplayImage(image_url, loader, image);

使用网址上的库。 http://www.androidhive.info/2012/07/android-loading-image-from-url-http/ ImageLoader.java,FileCache.java和Utils.java

答案 2 :(得分:0)

只需使用Picasso

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

不可能比这更容易。