简体   繁体   中英

Cannot display images in Html.fromHtml() in text view for images coming dynamically

I am developing an app in android studio in which contents are coming form an Api in a recyclerview. In the api there is an element "content" that sends all html tags with images like a full page. I have to display that page in textview. I have tried Htm.fromHtml method but it is not displaying the images. I have searched all answers and got the solution of ImageGetter method, but I am not able to display dynamic content in the recycleradapter from ImageGetter. I have to keep the images in the drawable of my app and match the source URL that is being parsed. Please help. Below is my code.

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;



    }
}

PageRecyclerAdapter.java

public class PageRecyclerAdapter extends 
RecyclerView.Adapter<PageRecyclerAdapter.MyViewHolder> implements 
View.OnTouchListener
    {

private List<MenuFeeds> feedsList;
private Context context;
private LayoutInflater inflater;


public PageRecyclerAdapter(Context context, List<MenuFeeds> feedsList) {

    this.context = context;
    this.feedsList = feedsList;
    inflater = (LayoutInflater) 
    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View rootView = inflater.inflate(R.layout.list_layout5, parent, false);
    return new MyViewHolder(rootView);
    }

@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final MenuFeeds feeds = feedsList.get(position);
    //Pass the values of feeds object to Views
    //holder.idmenu.setText(feeds.getMenuId());
    //holder.title.setText(feeds.getFeedName());
   /* holder.description.setText(Html.fromHtml(feeds.getDescription(), 0, 
new Html.ImageGetter() {
        @Override
        public Drawable getDrawable(String s) {
            int id;

            if 
(s.equals("http://www.groveus.com/micro/assets/images/URINARY TRACT 
INFECTION 1.png")) {
                id = R.drawable.urin1;
            }
            else if 
(s.equals("http://www.groveus.com/micro/assets/images/URINARY TRACT 
INFECTION 2.png")) {
                id = R.drawable.urin2;
            }
            else if 
(s.equals("http://www.groveus.com/micro/assets/images/SKIN AND SOFT TISSUE 
INFECTION 1.png")) {
                id = R.drawable.skinsoft1;
            }
            else if 
(s.equals("http://www.groveus.com/micro/assets/images/SKIN AND SOFT TISSUE 
INFECTION 2.png")) {
                id = R.drawable.skinsoft2;
            }
            else if 
(s.equals("http://groveus.com/micro/assets/images/RESPIRATORY TRACT 
INFECTION.png")) {
                id = R.drawable.respo;
            }
            else if (s.equals("http://groveus.com/micro/assets/images/LOCAL 
BACTERIAL INFECTIONS.png")) {
                id = R.drawable.local;
            }
            else if 
(s.equals("http://groveus.com/micro/assets/images/URINARY TRACT INFECTION 
2nd 1.png")) {
                id = R.drawable.urine2nd1;
            }
            else if 
(s.equals("http://groveus.com/micro/assets/images/URINARY TRACT INFECTION 
2nd 2.png")) {
                id = R.drawable.urine2nd2;
            }
            else if 
(s.equals("http://groveus.com/micro/assets/images/table.png")) {
                id = R.drawable.table;
            }
            else if 
(s.equals("http://www.groveus.com/micro/assets/images/table 2.png")) {
                id = R.drawable.table2;
            }
            else {
                return null;
            }

            Drawable d = context.getResources().getDrawable(id);
            d.setBounds(0,0,1020,600);
            return d;
        }
    }, null));*/

    holder.description.setText(Html.fromHtml(feeds.getDescription()));

    holder.description.setOnTouchListener(this);
    holder.description.setMovementMethod(new ScrollingMovementMethod());
    holder.imageview.setImageUrl(feeds.getImgURL(), 
    NetworkController.getInstance(context).getImageLoader());
    // holder.ratingbar.setProgress(feeds.getRating());

    }

@Override
public int getItemCount() {
    return feedsList.size();
    }

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            view.getParent().requestDisallowInterceptTouchEvent(true);
            return false;
        }



        public class MyViewHolder extends RecyclerView.ViewHolder {

private TextView title,description;
private NetworkImageView imageview;
//private ProgressBar ratingbar;

public MyViewHolder(View itemView) {
    super(itemView);
    title = (TextView) itemView.findViewById(R.id.ImageNameTextView);

    description = (TextView) itemView.findViewById(R.id.desc);
    //idmenu = (TextView) itemView.findViewById(R.id.ImageNameTextView2);
    UrlImageParser p=new UrlImageParser(description,context);
    // Volley's NetworkImageView which will load Image from URL
    imageview = (NetworkImageView) itemView.findViewById(R.id.thumbnail);


        }
    }         
}

MenuFeeds.java

public class MenuFeeds
{
   private String  imgURL, feedName, description,page;
    //private String id;
   private int id;

public MenuFeeds(int menuid, String page, String name, String imgurl,String 
desc) {
    this.id=menuid;
    this.page=page;
    this.feedName = name;
    this.imgURL = imgurl;
    this.description = desc;
    //this.rating = rating;
    }

    public int getMenuId() {
    return id;
    }

    public String getPageID()
    {
        return page;
    }


    public String getDescription() {
        return description;
   }

    public String getImgURL() {
        return imgURL;
    }

    public String getFeedName() {
        return feedName;
    }
}

I also faced a similar problem month ago and used this and it works fine :

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);

Now copy and paste these 2 methods :

First method :

public class URLDrawable extends BitmapDrawable {
    protected Drawable drawable;
     @Override
    public void draw(Canvas canvas) {
        if(drawable != null) {
            drawable.draw(canvas);
        }
    }
}

///Second Method :

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();
        }
    }
}

try this

load your image using piccaso

add below library in your build.gradle

implementation 'com.squareup.picasso:picasso:2.71828'

when you need to set image use piccaso this way

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM