Android Studio - Get tweet image from twitter - Fabric - android

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?

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

i am getting image only if it is available like:
String mediaImageUrl = null;
if (tweet.entities.media != null) {
String type = tweet.entities.media.get(0).type;
if (type.equals("photo")) {
mediaImageUrl = tweet.entities.media.get(0).mediaUrl;
}
else {
mediaImageUrl = "'";
}
System.out.println("mediaImageUrl" + mediaImageUrl);
}
If u using type attributes u can easily differentiates image/video from userTimeLine

Related

get raw file data from url and display in ImageView

I would like to display an image from the URL that is providing me raw data for the image(png or JPG).
I checked this link but not much useful.
Here is my image link
I am processing the raw data but could not see the image. I am not sure how do I check that I got the right raw data.
here is my effort
private class DownloadImageTask extends AsyncTask<String, Void, Void> {
byte[] bytes;
Bitmap picture = null;
#Override
protected Void doInBackground(String... urls) {
// final OkHttpClient client = new OkHttpClient();
//
// Request request = new Request.Builder()
// .url(urls[0])
// .build();
//
// Response response = null;
//
// try {
// response = client.newCall(request).execute();
// } catch (IOException e) {
// e.printStackTrace();
// }
// assert response != null;
// if (response.isSuccessful()) {
// try {
// assert response.body() != null;
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// IOUtils.copy(response.body().byteStream(), baos);
// bytes = baos.toByteArray();
// picture = BitmapFactory.decodeStream(response.body().byteStream());
// } catch (Exception e) {
// Log.e("Error", Objects.requireNonNull(e.getMessage()));
// e.printStackTrace();
// }
//
// }
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
URL url = new URL(urls[0]);
byte[] chunk = new byte[4096];
int bytesRead;
InputStream stream = url.openStream();
while ((bytesRead = stream.read(chunk)) > 0) {
outputStream.write(chunk, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
bytes = outputStream.toByteArray();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (bytes != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
cameraView.setImageBitmap(bitmap);
}
// cameraView.setImageBitmap(picture);
}
}
The location of your problem/s in your workflow seems ill-determined.
You should first identify this.
(Plus, you did not specify if you are bound to a specific programming language).
For this sake, I suggest you:
Start using a raw image file that you know is correct, and test its processing.
There are quite a few raw image formats.
Judging from the tag android, I guess the following can help:
To capture a raw iamge into a file: How to capture raw image from android camera
To display in ImageView: Can't load image from raw to imageview
https://gamedev.stackexchange.com/questions/14046/how-can-i-convert-an-image-from-raw-data-in-android-without-any-munging
https://developer.android.com/reference/android/graphics/ImageFormat
https://www.androidcentral.com/raw-images-and-android-everything-you-need-know
Try getting a raw image from an URL that you can manage.
Apply this to the actual target URL.
This way you will know where your problem resides.
Without more info it is hard to "debug" your problem.
You can also inspect code in FOSS projects.
You could use a library named Picasso and do the following:
String url = get url from the Async Function and convert it to String
/*if you url has no image format, you could do something like this con convert the uri into a Bitmap*/
public Bitmap getCorrectlyOrientedImage(Context context, Uri uri, int maxWidth)throws IOException {
InputStream input = context.getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
onlyBoundsOptions.inDither = true;//optional
onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
try {
input.close();
} catch (NullPointerException e) {
e.printStackTrace();
}
/*trying to get the right orientation*/
if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1)) {
return null;
}
int originalSize = Math.max(onlyBoundsOptions.outHeight, onlyBoundsOptions.outWidth);
double ratio = (originalSize > maxWidth) ? (originalSize / maxWidth) : 1.0;
Matrix matrix = new Matrix();
int rotationInDegrees = exifToDegrees(orientation);
if (orientation != 0) matrix.preRotate(rotationInDegrees);
int bmpWidth = 0;
try {
assert bitmap != null;
bmpWidth = bitmap.getWidth();
} catch (NullPointerException e) {
e.printStackTrace();
}
Bitmap adjustedBitmap = bitmap;
if (bmpWidth > 0)
adjustedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return adjustedBitmap;
}
/*Then you has the image in Bitmap, you can use the solution below or if Picasso doesn't allows you to put Bitmap you can pass it directly to the ImageView as a Bitmap.*/
ImageView imageView = view.findViewById(R.id.imageViewId);
/*Then use Picasso to draw the image into the ImageView*/
Picasso.with(context).load(url).fit().into(imageView );
This is the dependency for build.gradle, not sure if is the last version but you could try.
implementation 'com.squareup.picasso:picasso:2.5.2'
Kind regards!
Identify the following questions:
Using URL to get bytes to load images
I wrote down what I can with reference to
class DownLoadImageTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imageView.setImageBitmap(bitmap);
}
#Override
protected Bitmap doInBackground(String... strings) {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(strings[0]).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
InputStream inputStream = response.body().byteStream();
return BitmapFactory.decodeStream(inputStream);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is the URL I use
https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/440px-Image_created_with_a_mobile_phone.png
https://upload.wikimedia.org/wikipedia/commons/3/3a/Cat03.jpg
I can test it. I hope it can help you

Android: Listview on fragmvent, set image from url

How to update ListViev with image from url
To download image I'm using:
downloadImage
public static Bitmap downloadImage(String iUrl) {
Bitmap bitmap = null;
HttpURLConnection conn = null;
BufferedInputStream buf_stream = null;
try {
Log.v(TAG, "Starting loading image by URL: " + iUrl);
conn = (HttpURLConnection) new URL(iUrl).openConnection();
conn.setDoInput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.connect();
buf_stream = new BufferedInputStream(conn.getInputStream(), 8192);
bitmap = BitmapFactory.decodeStream(buf_stream);
buf_stream.close();
conn.disconnect();
buf_stream = null;
conn = null;
} catch (MalformedURLException ex) {
Log.e(TAG, "Url parsing was failed: " + iUrl);
} catch (IOException ex) {
Log.d(TAG, iUrl + " does not exists");
} catch (OutOfMemoryError e) {
Log.w(TAG, "Out of memory!!!");
return null;
} finally {
if ( buf_stream != null )
try { buf_stream.close(); } catch (IOException ex) {}
if ( conn != null )
conn.disconnect();
}
return bitmap;
}
My ListView listen when button clicked, and then update ListView
try{
JSONObject jsonResponse = new JSONObject(response.toString());
JSONArray jsonMainNode = jsonResponse.getJSONArray("items");
//JSONArray Data = jsonResponse.getJSONArray("snippet");
for(int i = 0; i<jsonMainNode.length();i++){
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("kind");
String number = jsonChildNode.optString("etag");
JSONObject item = jsonMainNode.getJSONObject(i);
JSONObject snippet = item.getJSONObject("snippet");
String title = snippet.getString("title");
String channelTitle = snippet.getString("channelTitle");
String pubDate = snippet.getString("publishedAt");
JSONObject thumbs = snippet.getJSONObject("thumbnails");
JSONObject thumb = thumbs.getJSONObject("default");
final String ico = thumb.getString("url");
new Thread(new Runnable() {
public void run() {
bmp = ImageManager.downloadImage(ico);
}
}).start();
countryList.add(createEmployee(title,channelTitle,pubDate, bmp));
}
simpleAdapter.notifyDataSetChanged();
ListView Updting, but without image. If Im using Image from #drawable all its ok.
The problem is that the bitmap hasn't finished being downloaded before you try to use it. When you call start() on a thread instance, that method returns immediately on the thread it was called on, while the new thread goes off and executes the run method (its own or that of the Runnable provided as a constructor parameter).
As start() returns immediately, you go straight on to create the employee before the bitmap has downloaded. As a result, bmp is null and there's no image to display.
You need to set up your code so that once an image is downloaded it is set on the appropriate view.

Twitter sharing using Fabric SDK in android

I want to share the image and text on twitter using my App. I user Fabric SDK and follow the guidelines on their official website. Problem is my image is not stored in phone storage and its a URL link. so when I pass that URL its not showing like FB sharing.
Below I have posted the Tried code for now.
private void shareViaTwitt() {
final String myUrlStr = "http://i.stack.imgur.com/2FCsj.png";
URL url;
Uri uri = null;
try {
url = new URL(myUrlStr);
uri = Uri.parse(url.toURI().toString());
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
TweetComposer.Builder builder = new TweetComposer.Builder(getContext())
.text("Hi this is Sample twitter sharing")
.image(uri);
builder.show();
}
Thank you.
/*In their official site has said need put file type uri that stored in
phone/SD storage. So Here I just save it and get that uri and then pass it to
fabric builder.*/
private void shareViaTwitt() {
final String myUrlStr = "http://i.stack.imgur.com/2FCsj.png";
TweetComposer.Builder builder = null;
try {
Bitmap bm = getBitmapFromURL(myUrlStr);
Uri uri = getImageUri(getContext(), bm);
builder = new TweetComposer.Builder(getContext())
.text("Sample Text")
.image(uri)
.url(new URL(""https://www.newurl.....));
builder.show();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public static Bitmap getBitmapFromURL(String src) {
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

Why I am getting OutOfMemory Exception in Android? [duplicate]

I have question about this error.
I make favicon parser from URLs. I do this like:
public class GrabIconsFromWebPage {
public static String replaceUrl(String url) {
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile("https?://.+\\..+?\\/");
Matcher m = p.matcher(url);
while (m.find()) {
sb.append(m.group());
}
return sb.toString();
}
public static String getFavicon(String url) throws IOException {
try {
Document doc = Jsoup.connect(url).get();
Element element = doc.head().select("link[href~=.*\\.(ico|png)]").first();
if (element != null) {
if (element.attr("href").substring(0, 2).contains("//")) {
return "http:" + element.attr("href");
} else if (element.attr("href").substring(0, 4).contains("http")) {
return element.attr("href");
} else {
return replaceUrl(url) + element.attr("href");
}
} else {
return "";
}
} catch(IllegalArgumentException ex) {
ex.printStackTrace();
} catch(OutOfMemoryError er) {
er.printStackTrace();
}
return "";
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
and how I get bitmap from url
Bitmap faviconBitmap = GrabIconsFromWebPage.getBitmapFromURL(
GrabIconsFromWebPage.getFavicon(
bookmarkData.get(position).getUrl() // url from which I want to grab favicon
)
);
And this code after uploading 20 images give me OutOfMemoryError. How can I fix this? Or optimize? Cuz in my list where I show this icons, can be more than 20 or 40 favicons...
I think, you would use universal image loader
The method as given snippet
// Load image, decode it to Bitmap and return Bitmap synchronously
ImageSize targetSize = new ImageSize(80, 50);
// result Bitmap will be fit to this size
Bitmap bmp = imageLoader.loadImageSync(imageUri, targetSize, options);
And for out of memory bound you would add a line in manifest file
<application
...
android:largeHeap="true"
...
>
</application>
It was bad idea with parsing icons by myself. Google did it before us
http://www.google.com/s2/favicons?domain=(domain)

How to retrieve the image store on app engine using endpoints and how to show/display in Android app

I have uploaded image on app engine. I am retrieving image blob key in android app from app engine using endpoints. I am doing some code on android app to display image.
The code is
URL imageURL = null;
try
{
//use our image serve page to get the image URL
imageURL = new URL("http://yourapp.appspot.com/serveBlob?id=" + o.getImageKey());
} catch (MalformedURLException e)
{
e.printStackTrace();
}
try {
//Decode and resize the image then set as the icon
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inSampleSize = 1 / 2;
Bitmap bitmap = BitmapFactor.decodeStream((InputStream) imageURL.getContent());
Bitmap finImg = Bitmap.createScaledBitmap(bitmap, 50, 50, false);
icon.setImageBitmap(finImg);
} catch (IOException e)
{
e.printStackTrace();
}
but it gives me bitmap = null and throwing null pointer exception.
I am struck on this point from lat 4 days. Please help me.
Try this..
Bitmap bitmap = null;
try {
HttpURLConnection connection = (HttpURLConnection) imageURL
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);
Log.v("bitmap--", "" + bitmap);
icon.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
I got the answer.
First have to create Servlet on app engine side of my project.
Servlet is like this.
public class Serve extends HttpServlet
{
private BlobstoreService blobstoreService =BlobstoreServiceFactory.getBlobstoreService();
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
BlobKey blobKey = new BlobKey(req.getParameter("id"));
blobstoreService.serve(blobKey, resp);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
doGet(req, resp);
}
}
Then have to register servlet in web.xml
<servlet>
<servlet-name>Serve</servlet-name>
<servlet-class>com.xyz.Serve</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Serve</servlet-name>
<url-pattern>/ServeBlob</url-pattern>
</servlet-mapping>
Then create url using servlet in android code.
the code at android side is like this.
URL imageURL = new URL("http://xyz.appspot.com/ServeBlob?id="+blobKey);
HttpURLConnection connection = (HttpURLConnection) imageURL.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
xyz is your app engine project name on appspot.
blobKey should be the blob key of image store on AppEngine.
Now pass bitmap to image view like this.
ImageView img = (ImageView) findViewById(R.id....);
img.setImageBitmap(bitmap);

Categories

Resources