0

I am fetching data from JSON with volley. In the data displayed in bookContent, there are <img> tags in varying positions.

I'm using Universal Image Loader to Load the images in the <img> tags.

This is my Activity.

BookDetails

public class BookDetails extends AppCompatActivity{

    private final String TAG = "BookDetails";

    private JSONObject bookData;

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


    TextView bookTitle, bookAuthorDate, bookContent;
    View firstView, secView;
    CircularNetworkImageView authorImg;
    ImageLoader AuthImgLoader;


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

        showDialog();

        bookTitle = (TextView) findViewById(R.id.dbook_title);
        bookAuthorDate = (TextView) findViewById(R.id.author_date);
        bookContent = (TextView) findViewById(R.id.dbook_content);
        authorImg = (CircularNetworkImageView) findViewById(R.id.author_img);
        firstView =  findViewById(R.id.dviewtop);
        secView =  findViewById(R.id.dviewbottom);

        DisplayImageOptions defaultoptions = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .build();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
                .defaultDisplayImageOptions(defaultoptions)
                .writeDebugLogs()
                .build();


        mImageLoader = com.nostra13.universalimageloader.core.ImageLoader.getInstance();
        mImageLoader.init(config);

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



        if (savedInstanceState != null) {

            try {
                String bookDataStr = savedInstanceState.getString("bookData");
                bookData = new JSONObject(bookDataStr);

                parseBook(bookData);
            } catch (JSONException e) {
                e.printStackTrace();
            }


        } else {
            if (NetworkCheck.isAvailableAndConnected(this)) {
                //Calling method to load books
                loadBook();
            } else {
                internetDialog.show();
            }
        }
    }


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

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


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

        final JsonObjectRequest jsonObjReq = new JsonObjectRequest( DetailConfig.GET_DURL + book_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);
                        }

                        bookData = response;

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

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


                    }
                });

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

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

    //This method will parse json data of book
    private void parseBook(JSONObject jsonObject) {

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


            try {
                String title = jsonObject.getString(DetailConfig.TAG_DPOST_TITLE);
                bookTitle.setText(Html.fromHtml(title));

                JSONObject pAuthor = jsonObject.getJSONObject("author");
                String author = pAuthor.getString("name");
                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_DPOST_CONTENT);
                Spanned spanned = Html.fromHtml(content, new UILImageGetter(bookContent, this), null);
                bookContent.setText(spanned);

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

        //Unhiding views
        bookTitle.setVisibility(View.VISIBLE);
        bookAuthorDate.setVisibility(View.VISIBLE);
        bookContent.setVisibility(View.VISIBLE);
        authorImg.setVisibility(View.VISIBLE);
        firstView.setVisibility(View.VISIBLE);
        secView.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("bookData", bookData.toString());
    }


}

Below, I use this piece of code I got from the accepted answer in this question to load the images in bookContent.

This class uses Universal Image Loader.

UILImageGetter

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);
        if (Build.VERSION.SDK_INT >= 21) {
        urlDrawable.mDrawable = c.getResources().getDrawable(R.drawable.default_thumb,null);
        } else {
            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);
            }
        }
    }
}

Everything works fine, the JSON is properly parsed and displayed, the images are loaded but there is a problem.

The loaded images are affecting the vertical lines that are displayed in bookContent. If there are many vertical lines, some part of it is cut off. And if the bookContent has very few vertical lines, a large empty space is left at the bottom of the TextView. However, if I don't load the images, the bookContent appears fine, no cut-offs, no extra space.

Please, how do I fix it?

Community
  • 1
  • 1
X09
  • 3,827
  • 10
  • 47
  • 92

1 Answers1

0

I go the answer to this problem from dcow's comment in this question. What I did is that I removed

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

and wrote

container.setText(container.getText()); under

container.setText(container.getText());.

Community
  • 1
  • 1
X09
  • 3,827
  • 10
  • 47
  • 92