如何正确显示返回的json对象中找到的<img/>标记

时间:2016-04-17 00:08:06

标签: android json android-volley

我正在使用凌空从网上获取json。其中一个json对象(“内容”)有&lt; img&gt;嵌入在字符串中的标签返回。

使用下面的代码,我已成功解析并显示了对象,但“内容”中的图像未显示。 所以我希望图像显示在“内容”对象中找到的位置。

FruitDetails

public class FruitDetails extends AppCompatActivity {

    private final String TAG = "FruitDetails";


    TextView fruitTitle, fruitContent;
    NetworkImageView authorImg;
    ImageLoader AuthImgLoader;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fruit_details);

        fruitTitle = (TextView) findViewById(R.id.dfruit_title);
        fruitContent = (TextView) findViewById(R.id.dfruit_content);
        authorImg = (NetworkImageView) findViewById(R.id.author_img);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        if (savedInstanceState != null) {
            fruitTitle.setText(savedInstanceState.getString("fruitTitle"));
            fruitContent.setText(savedInstanceState.getString("fruitContent"));
        } else {

                loadFruit();

        }
    }

    private void loadFruit() {
        Log.d(TAG, "loadFruit called");

        final ProgressBar progressBar;
        progressBar = (ProgressBar) findViewById(R.id.progress_circle);
        progressBar.setVisibility(View.VISIBLE);


        int news_id = getIntent().getIntExtra("FruitId", -1);
        Log.d(TAG, "You clicked fruit id " + news_id);

        final JsonObjectRequest jsonObjReq = new JsonObjectRequest( DetailConfig.GET_DURL + news_id, null,


                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("Debug", response.toString());

                        //Dismissing progressbar;
                        if (progressBar != null) {
                            progressBar.setVisibility(View.GONE);
                        }

                        //Calling method to parse json array
                        parseFruit(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d("", "Error: " + error.getMessage());
                    }
                });

        //Creating request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to queue
        requestQueue.add(jsonObjReq);
    }

    //This method will parse json data of fruit
    private void parseFruit(JSONObject jsonObject) {

        Log.d(TAG, "Parsing fruit array");


            try {
                String title = jsonObject.getString(DetailConfig.TAG_DFRUIT_TITLE);
                fruitTitle.setText(Html.fromHtml(title));

                JSONObject pAuthor = jsonObject.getJSONObject("author");
                String authorimg = pAuthor.getString("avatar");

                AuthImgLoader = VolleyRequest.getInstance(getApplicationContext()).getImageLoader();
                AuthImgLoader.get(authorimg, ImageLoader.getImageListener(authorImg, R.drawable.ic_author, R.drawable.ic_author));
                authorImg.setImageUrl(authorimg, AuthImgLoader);


                String content = jsonObject.getString(DetailConfig.TAG_DFRUIT_CONTENT);
                fruitContent.setText(Html.fromHtml(content));

            } catch (JSONException w) {
                w.printStackTrace();
            }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("fruitTitle", fruitTitle.getText().toString());
        outState.putString("fruitContent", fruitContent.getText().toString());

    }

}

我见过the accepted answer to similar question但是我在尝试实施它时遇到了问题它一直告诉我“无法解析符号urlDrawable

UILImageGetter

    import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.view.View;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;



public class UILImageGetter implements Html.ImageGetter{
    Context c;
    TextView conatiner;
    UrlImageDownloader urlDrawable;

    public UILImageGetter(View textView, Context context) {
        this.c = context;
        this.conatiner = (TextView) textView;
    }

    @Override
    public Drawable getDrawable(String source) {
        urlDrawable = new UrlImageDownloader(c.getResources(), source);
        urlDrawable.mDrawable = c.getResources().getDrawable(R.drawable.default_thumb);

        ImageLoader.getInstance().loadImage(source, new SimpleListener(urlDrawable));
        return urlDrawable;
    }

    private class SimpleListener extends SimpleImageLoadingListener {
        UrlImageDownloader mUrlImageDownloader;

        public SimpleListener(UrlImageDownloader downloader) {
            super();
            mUrlImageDownloader= downloader;
        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            int width = loadedImage.getWidth();
            int height = loadedImage.getHeight();

            int newWidth = width;
            int newHeight = height;

            if (width > conatiner.getWidth()) {
                newWidth = conatiner.getWidth();
                newHeight = (newWidth * height) / width;
            }

            if (view != null) {
                view.getLayoutParams().width = newWidth;
                view.getLayoutParams().height = newHeight;
            }

            Drawable result = new BitmapDrawable(c.getResources(), loadedImage);
            result.setBounds(0, 0, newWidth, newHeight);

            mUrlImageDownloader.setBounds(0, 0, newWidth, newHeight);
            mUrlImageDownloader.mDrawable = result;

            conatiner.setHeight((conatiner.getHeight() + result.getIntrinsicHeight()));
            conatiner.invalidate();
        }

    }

    private class UrlImageDownloader extends BitmapDrawable {
        public  Drawable mDrawable;

        public UrlImageDownloader(Resources resources, String filepath) {
            super(resources, filepath);
            mDrawable = new BitmapDrawable(resources, filepath);
        }

        @Override
        public void draw(Canvas canvas) {
            if (mDrawable != null) {
                mDrawable.draw(canvas);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

最简单的一个是,如果Json对象只是一个具有以下语法的字符串(没有img标记中的空格):

<img src= "https://www.myWebstie/images/myimgx92dp.png" />

和!!!你知道它不会发生变化然后你可以将它变为子串:

String response = "this is your image link";
int x = response.length();
x -= 3;
String subString = new String(response.substring(10, x));

所以例如10对于img标签+ src =在字符串的开头,3对于字符串末尾的结束标记。

至于你的例子,你应该注意到有时在img标签中还有其他信息,比如宽度和高度,所以请确保你没有它的链接子串,并从中了解你的应用程序应该有多大(不要忘记)那是px与dp的差异)。

我查看了您在此处发布的内容。

如果这是您尝试解析的网站,我建议找一个解析html对象的第三方库。

似乎jsoup似乎可以做到这一点,但我之前从未使用它或Html.ImageGetter,尽管jsoup似乎是你添加内容的更好选择。

您只需要尝试两种方法,然后检查哪种解决方案更适合您。

同时检查this

请注意,如果您要下载并显示多个图像甚至视频,您也应该使用凌空下载(在您检索完所有图像链接后)。

如果它只是前面提到的一张图片而且内容只是例如我仍然建议只是将其子串。

答案 1 :(得分:0)

我只是使用上面的 UILImageGetter ,然后来到 FruitDetails 并写了

protected com.nostra13.universalimageloader.core.ImageLoader mImageLoader;

onCreate 之前

在onCreate中,我写了

mImageLoader = com.nostra13.universalimageloader.core.ImageLoader.getInstance(); mImageLoader.init(ImageLoaderConfiguration.createDefault(this));

然后我也改变了

fruitContent.setText(Html.fromHtml(content));

FruitDetails

Spanned spanned = Html.fromHtml(content, new UILImageGetter(fruitContent, this), null); fruitContent.setText(spanned);

这解决了我的问题。