Search code examples
androidtwittertweetstwitter-fabrictwitter-feed

Android Studio - Get tweet image from twitter - Fabric


  • I'm getting a twitter feed in my Android Studio app, using Fabric
  • for each tweet that has an image attactched, I wish to display the image
  • how can I extract either a url to the image or a byte[]?

I have found what looks like an array of bytes, but when I attempt to decode it using bitmaps decodeByteArray, it returns null

                            String mediaString = t.entities.media.toString();
                            String[] mediaArray = mediaString.split("(?=@)");
                            byte[] mediaBytes = mediaArray[1].getBytes();

can anybody help me find a way to retrieve the image so I can display it?


Solution

  • Image url

    String mediaImageUrl = tweet.entities.media.get(0).url;
    Bitmap mediaImage = getBitmapFromURL(mediaImageUrl);
    Bitmap mImage = null;
    

    Decode the image

    private Bitmap getBitmapFromURL(final String mediaImageUrl) {
    
        try {
            Thread t = new Thread() {
                public void run() {
                    try {
                        URL url = new URL(mediaImageUrl);
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.setDoInput(true);
                        connection.connect();
                        InputStream input = connection.getInputStream();
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inScaled = false;
                        mImage = BitmapFactory.decodeStream(input, null, options);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            t.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return mImage;
    }