java - Android:如何处理嵌入在使用 JSON 检索的字符串中的 html <img/> 标签

标签 java android html json android-studio

我有一个显示文章的新闻网站,我在 android studio 中编写了一个 java 代码来从 URL like this 获取文章的内容。作为 JSON,到目前为止一切都很好。

但是在文章的描述中可能有照片,现在我想获取html <img />来自描述节点的标签,并在我的 android 应用程序中正确显示图像,它们出现在描述中。

如果有帮助,这是我的测试代码:

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;

import android.os.Bundle;
import android.app.Activity;
import android.text.Html;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.InputStream;


public class SingleContactActivity extends Activity {

    public static String myArticleUrl = "http://ana.fm/api/article/";
    TextView title;
    TextView desc;
    ImageView img;
    String ar_id;

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

        title = (TextView) findViewById(R.id.single_article_title);
        desc = (TextView) findViewById(R.id.single_article_desc);
        img = (ImageView) findViewById(R.id.single_article_cover_photo);

        ar_id = getIntent().getExtras().getString("id");

        myArticleUrl = myArticleUrl.concat(ar_id);

        new LoadAllArticles().execute();

    }

    // Load an image from a url
    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }


    // LOADING THE ARTICLE CONTENTS IN THE BACKGROUND
    class LoadAllArticles extends AsyncTask<String, String, Void> {

        private ProgressDialog progressDialog = new ProgressDialog(SingleContactActivity.this);
        InputStream inputStream = null;
        String result = "";
        HttpResponse httpResponse;
        HttpEntity httpEntity;

        protected void onPreExecute() {
            progressDialog.setMessage("Downloading article...");
            progressDialog.show();
            progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                public void onCancel(DialogInterface arg0) {
                    LoadAllArticles.this.cancel(true);
                }
            });
        }

        @Override
        protected Void doInBackground(String... params) {

            String url_select = myArticleUrl;

            // Set up HTTP Get
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url_select);

            try {


                httpResponse = httpClient.execute(httpGet);
                result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(Void v) {
            //parse JSON data
            try {

                JSONObject parent_obj = new JSONObject(result);
                JSONArray jArray= parent_obj.getJSONArray("article");
                JSONObject json = jArray.getJSONObject(0);



                String ar_title = json.getString("title");
                String ar_desc = json.getString("description");
                String ar_image = json.getString("inner_photo");


                String newTitle = Html.fromHtml(ar_title).toString();
                title.setText(newTitle);
                String newDesc = Html.fromHtml(ar_desc).toString();
                desc.setText(newDesc);

                if(ar_image != null) {
                    String img_url = "http://www.ana.fm/photos/articles/".concat(ar_image);
                    new DownloadImageTask(img).execute(img_url);
                }

                this.progressDialog.dismiss();
            } catch (JSONException e) {
                Log.e("JSONException", "Error: " + e.toString());
            } // catch (JSONException e)
        }
    }
}

这是 XML article.xml:

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

    <!-- Article Cover Photo -->
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/single_article_cover_photo"
        android:layout_gravity="center"
        android:layout_weight=".14"/>

    <!-- Article Title -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/single_article_title"
        android:layout_gravity="center"
        android:textColor="#acacac"
        android:layout_weight=".14"/>

    <!-- Article Description -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/single_article_desc"
        android:layout_gravity="center"
        android:layout_weight=".14"/>
    </LinearLayout>
</ScrollView>

有办法吗?

最佳答案

你可以尝试使用类:

public class UILImageGetter implements Html.ImageGetter {
Context c;
TextView container;

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

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

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

private class SimpleListener extends SimpleImageLoadingListener {
    UrlImageDownloader urlImageDownloader;

    public SimpleListener(UrlImageDownloader downloader) {
        super();
        urlImageDownloader = 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 > container.getWidth() ) {
            newWidth = container.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);

        urlImageDownloader.setBounds(0, 0, newWidth, newHeight);
        urlImageDownloader.drawable = result;

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

private class UrlImageDownloader extends BitmapDrawable {
    public Drawable drawable;

    public UrlImageDownloader(Resources res, String filepath) {
        super(res, filepath);
        drawable = new BitmapDrawable(res, filepath);
    }

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

如果你这样做,你必须导入库imageloader .在他们之后你写这个:

Spanned spanned = Html.fromHtml(ar_desc, new UILImageGetter(desc, this), null);
desc.setText(spanned);

此外,您还可以使用 WebView。

关于java - Android:如何处理嵌入在使用 JSON 检索的字符串中的 html <img/> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28521453/

相关文章:

javascript - 如何获取点击列表项的上下文以在 Nativescript 中的另一个页面中显示详细信息

android - 部分幻灯片android

java - Android:调用时 View 返回 null?

html - CSS 兄弟选择器替代方案

Java Swing、Corba 对象 - 如何在 DefaultListModel 中存储 Corba 对象?

java - Memcache实现设计

java - Java 中知道一个对象是否是其他对象的子类

java - TextArea Swing与JavaFX选择范围区别

javascript - 防止按钮重置文本框值

html - 底部 div 与顶部重叠