Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 对于动态生成的图像,无法在文本视图中以Html.fromHtml()显示图像_Java_Android - Fatal编程技术网

Java 对于动态生成的图像,无法在文本视图中以Html.fromHtml()显示图像

Java 对于动态生成的图像,无法在文本视图中以Html.fromHtml()显示图像,java,android,Java,Android,我正在android studio中开发一个应用程序,其中的内容来自recyclerview中的Api。在api中有一个元素“content”,它发送所有html标记和图像,就像一个完整的页面。我必须在文本视图中显示该页面。我尝试过Htm.fromHtml方法,但它没有显示图像。我已经搜索了所有答案并获得了ImageGetter方法的解决方案,但我无法在ImageGetter的recycleradapter中显示动态内容。我必须将图像保存在我的应用程序的可绘制部分,并与正在解析的源URL相匹配。

我正在android studio中开发一个应用程序,其中的内容来自recyclerview中的Api。在api中有一个元素“content”,它发送所有html标记和图像,就像一个完整的页面。我必须在文本视图中显示该页面。我尝试过Htm.fromHtml方法,但它没有显示图像。我已经搜索了所有答案并获得了ImageGetter方法的解决方案,但我无法在ImageGetter的recycleradapter中显示动态内容。我必须将图像保存在我的应用程序的可绘制部分,并与正在解析的源URL相匹配。请帮忙。下面是我的代码

PageActivity.java

public class PageActivity extends AppCompatActivity {
    RequestQueue queue;
    String menuidpage;

    RecyclerView recyclerView;
    List<MenuFeeds> feedsList = new ArrayList<MenuFeeds>();
    String newimage = "http://www.groveus.com/micro/assets/uploads/page/";
    PageRecyclerAdapter adapter;
    private ProgressDialog pDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_page);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    Bundle bundle=getIntent().getExtras();
    menuidpage=bundle.getString("page_id");

    recyclerView = (RecyclerView) findViewById(R.id.recyclerviewpage);
    pDialog = new ProgressDialog(this);
    adapter = new PageRecyclerAdapter(this, feedsList);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    recyclerView.setAdapter(adapter);
    //Getting Instance of Volley Request Queue
    queue = NetworkController.getInstance(this).getRequestQueue();
    //Volley's inbuilt class to make Json array request

    pDialog.setMessage("Loding...");
    pDialog.show();
    String url = "http://www.groveus.com/micro/api/index.php/pages/view? 
    id="+menuidpage;

    JsonArrayRequest menuReq = new JsonArrayRequest(url, new 
    Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            pDialog.dismiss();

            for (int i = 0; i < response.length(); i++) {
                try {

                    JSONObject obj = response.getJSONObject(i);
                    MenuFeeds feeds = new MenuFeeds(obj.getInt("page_id"), 
   obj.getString("status"), obj.getString("title"), 
   newimage+obj.getString("image"),obj.getString("content"));

                    // adding movie to movies array
                    feedsList.add(feeds);


                } catch (Exception e) {
                    System.out.println(e.getMessage());
                } finally {
                    //Notify adapter about data changes
                    adapter.notifyItemChanged(i);
                }
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println(error.getMessage());
            pDialog.dismiss();

        }
    });
    //Adding JsonArrayRequest to Request Queue
    queue.add(menuReq);
}

@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;



    }
}
试试这个

使用piccaso加载图像

在build.gradle中添加以下库

implementation 'com.squareup.picasso:picasso:2.71828'
当您需要设置图像时,请按此方式使用piccaso

Picasso.get()
.load(your_image)
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.your_error_image_or_blank)
.into(your_imageView);

我在一个月前也遇到过类似的问题,我使用了它,它工作得很好:

String htmlData = listData.get(position).getValue();
               String showData = htmlData.replace("\n", "");

                URLImageParser p = new URLImageParser(holder.textt, context);
                Spanned htmlAsSpanned = Html.fromHtml(showData,p,null);

                holder.yourTextView.setText(htmlAsSpanned);
现在复制并粘贴以下两种方法:

第一种方法:

public class URLDrawable extends BitmapDrawable {
    protected Drawable drawable;
     @Override
    public void draw(Canvas canvas) {
        if(drawable != null) {
            drawable.draw(canvas);
        }
    }
}
///第二种方法:

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


    /***
     * Construct the URLImageParser which will execute AsyncTask and refresh the container
     * @param t
     * @param c
     */
    public URLImageParser(TextView t, Context c) {
        this.c = c;

        this.container = t;
    }

    public Drawable getDrawable(String source) {
        URLDrawable urlDrawable = new URLDrawable();

        // get the actual source
        ImageGetterAsyncTask asyncTask =
                new ImageGetterAsyncTask( urlDrawable);

        asyncTask.execute(source);

        // return reference to URLDrawable where I will change with actual image from
        // the src tag
        return urlDrawable;
    }

    public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
        URLDrawable urlDrawable;

        public ImageGetterAsyncTask(URLDrawable d) {
            this.urlDrawable = d;
        }

        @Override
        protected Drawable doInBackground(String... params) {
            String source = params[0];
            return fetchDrawable(source);
        }

        @Override
        protected void onPostExecute(Drawable result) {
            // set the correct bound according to the result from HTTP call
            urlDrawable.setBounds(0, 0, 0 + result.getIntrinsicWidth(), 0
                    + result.getIntrinsicHeight());

            // change the reference of the current drawable to the result
            // from the HTTP call
            urlDrawable.drawable = result;

            // redraw the image by invalidating the container
            URLImageParser.this.container.invalidate();
            URLImageParser.this.container.setHeight((URLImageParser.this.container.getHeight()
                    + result.getIntrinsicHeight()));



        }

        /***
         * Get the Drawable from URL
         * @param urlString
         * @return
         */
        public Drawable fetchDrawable(String urlString) {
            try {
                InputStream is = fetch(urlString);
                Drawable drawable = Drawable.createFromStream(is, "src");
                drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0
                        + drawable.getIntrinsicHeight());
                return drawable;
            } `enter code here`catch (Exception e) {
                return null;
            }
        }

        private InputStream fetch(String urlString) throws MalformedURLException, IOException {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet request = new HttpGet(urlString);
            HttpResponse response = httpClient.execute(request);
            return response.getEntity().getContent();
        }
    }
}
公共类URLImageParser实现Html.ImageGetter{
上下文c;
文本视图容器;
/***
*构造URLImageParser,它将执行AsyncTask并刷新容器
*@param t
*@param c
*/
公共URLImageParser(文本视图t,上下文c){
这个.c=c;
这个容器=t;
}
公共可绘制getDrawable(字符串源){
URLDAWABLE URLDAWABLE=新的URLDAWABLE();
//获取实际来源
ImageGetterAsyncTask异步任务=
新的ImageGetterAsyncTask(URLDawable);
asyncTask.execute(源代码);
//返回对URLDrawable的引用,其中我将根据实际图像进行更改
//src标签
返回可提取;
}
公共类ImageGetterAsyncTask扩展异步任务{
URLDrawable URLDrawable;
公共ImageGetterAsyncTask(URLDawable d){
this.urlDrawable=d;
}
@凌驾
受保护的可抽出式doInBackground(字符串…参数){
字符串源=参数[0];
返回可提取的(源);
}
@凌驾
受保护的void onPostExecute(可提取结果){
//根据HTTP调用的结果设置正确的绑定
urlDrawable.setBounds(0,0,0+result.getIntrinsicWidth(),0
+result.getIntrinsicHeight());
//将当前绘图的参考更改为结果
//从HTTP调用
urlDrawable.drawable=结果;
//通过使容器无效来重新绘制图像
URLImageParser.this.container.invalidate();
urlmageparser.this.container.setHeight((urlmageparser.this.container.getHeight)()
+result.getIntrinsicHeight());
}
/***
*从URL获取可绘制的内容
*@param-urlString
*@返回
*/
公共可提取可提取(字符串urlString){
试一试{
InputStream is=fetch(urlString);
Drawable Drawable=Drawable.createFromStream(是“src”);
setBounds(0,0,0+drawable.getIntrinsicWidth(),0
+getIntrinsicHeight());
回拉;
}`enter code here`catch(例外情况e){
返回null;
}
}
私有InputStream获取(字符串urlString)引发错误的InputStream异常,IOException{
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpGet请求=新的HttpGet(urlString);
HttpResponse response=httpClient.execute(请求);
返回response.getEntity().getContent();
}
}
}

但我没有图像视图。它必须在textview中加载。您可以检查此api以获取参考:。您可以在这里发现,有一个名为“content”的元素,其中完整的Html页面与img标记一起出现。我想在textview中也显示这些图像。感谢您的回答,但是我在@Override protected void onPostExecute(Drawable result){//这一部分中遇到了这个错误,根据HTTP调用urlDrawable.setBounds的结果设置正确的绑定(0,0,0+result.getIntrinsicWidth(),0+result.getIntrinsicHeight());它显示了对空对象引用调用虚拟方法“int-android.graphics.drawable.drawable.getIntrinsicWidth()”的尝试onPostExecute()的参数是什么方法??您提供的代码,我已经复制并粘贴了。根据上面提供的代码,我应该发送哪些参数?当前参数是result。只需复制并粘贴我的两个给定方法,然后使用我的Html.fromHtml()即可这是用3个参数代替你的方法。如果你复制并粘贴正确,那么就不会有任何空指针异常,就像你提到的那样,因为我们使用的是我上面提到的方法中正确的变量…所以不要更改任何变量的名称并粘贴它,因为它是固定的,而且效果很好。这段代码应该被接受。非常感谢你。
public class URLDrawable extends BitmapDrawable {
    protected Drawable drawable;
     @Override
    public void draw(Canvas canvas) {
        if(drawable != null) {
            drawable.draw(canvas);
        }
    }
}
public class URLImageParser implements Html.ImageGetter {
    Context c;
    TextView container;


    /***
     * Construct the URLImageParser which will execute AsyncTask and refresh the container
     * @param t
     * @param c
     */
    public URLImageParser(TextView t, Context c) {
        this.c = c;

        this.container = t;
    }

    public Drawable getDrawable(String source) {
        URLDrawable urlDrawable = new URLDrawable();

        // get the actual source
        ImageGetterAsyncTask asyncTask =
                new ImageGetterAsyncTask( urlDrawable);

        asyncTask.execute(source);

        // return reference to URLDrawable where I will change with actual image from
        // the src tag
        return urlDrawable;
    }

    public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
        URLDrawable urlDrawable;

        public ImageGetterAsyncTask(URLDrawable d) {
            this.urlDrawable = d;
        }

        @Override
        protected Drawable doInBackground(String... params) {
            String source = params[0];
            return fetchDrawable(source);
        }

        @Override
        protected void onPostExecute(Drawable result) {
            // set the correct bound according to the result from HTTP call
            urlDrawable.setBounds(0, 0, 0 + result.getIntrinsicWidth(), 0
                    + result.getIntrinsicHeight());

            // change the reference of the current drawable to the result
            // from the HTTP call
            urlDrawable.drawable = result;

            // redraw the image by invalidating the container
            URLImageParser.this.container.invalidate();
            URLImageParser.this.container.setHeight((URLImageParser.this.container.getHeight()
                    + result.getIntrinsicHeight()));



        }

        /***
         * Get the Drawable from URL
         * @param urlString
         * @return
         */
        public Drawable fetchDrawable(String urlString) {
            try {
                InputStream is = fetch(urlString);
                Drawable drawable = Drawable.createFromStream(is, "src");
                drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0
                        + drawable.getIntrinsicHeight());
                return drawable;
            } `enter code here`catch (Exception e) {
                return null;
            }
        }

        private InputStream fetch(String urlString) throws MalformedURLException, IOException {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet request = new HttpGet(urlString);
            HttpResponse response = httpClient.execute(request);
            return response.getEntity().getContent();
        }
    }
}