一尘不染

Android:如何处理嵌入在使用JSON检索的字符串中的html 标签

json

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

但是在文章中,描述中可能有照片,现在我想<img />从描述节点获取html 标签,并在我的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>

有没有办法做到这一点 ?


阅读 185

收藏
2020-07-27

共1个答案

一尘不染

您可以尝试使用该类:

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。

2020-07-27