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

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)

Related

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?
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

Convert image URL to drawable resource id in android

I'm using the KenBurnsView library with this code:
mHeaderPicture.setResourceIds(R.drawable.picture0, R.drawable.picture1);
As you can see it takes drawable resource ids.
What I want to do is covert all photos URLS to drawable resource ids.
Photo urls like this:
http://example.com/image.jpg
http://example.com/image2.jpg
http://example.com/image3.jpg
http://example.com/image4.jpg
I tried this code here and it didn't work:
Bitmap drawable_from_url(String url) throws java.net.MalformedURLException, java.io.IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection)new URL(url) .openConnection();
connection.setRequestProperty("User-agent","Mozilla/4.0");
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return x;
}
I have read a LOT of questions and answers all over the web and I didn't find a good tutorial or solution.
Try to drop this library into your project. Its a useful library.
http://square.github.io/picasso/
Sample Usage:
Picasso.with(context).load("http://example.com/image.jpg").into(imageView);
How to get the drawable from imageView:
Drawable myDrawable = imageView.getDrawable();
You can't convert a Bitmap to a resource id. Resource ids are only for resources in your APK. You'll have to edit or extend the KenBurnsView class to accept Bitmap objects e.g by adding a function like this:
public void setBitmaps(Bitmap... bitmaps) {
for (int i = 0; i < mImageViews.length; i++) {
mImageViews[i].setImageBitmap(bitmaps[i]);
}
}
Then you can pass the Bitmaps that you load with drawable_from_url()
You just forgot to add setDoInput to connection
public 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;
}
}
Add asynchronous task ...
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
.execute(url);
}
public void onClick(View v) {
startActivity(new Intent(this, IndexActivity.class));
finish();
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView mHeaderPicture;
public DownloadImageTask(ImageView mHeaderPicture){
this.mHeaderPicture= mHeaderPicture;
} protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
mHeaderPicture.setImageBitmap(result);
}
}`
Make sure you have the following permissions set in your AndroidManifest.xml to access the internet.
<uses-permission android:name="android.permission.INTERNET" />

invalid url when downloading jpg image to android

I am getting a nullPointerException when trying to download a jpg file. It is done in an AsyncTask method and I can't trace the program flow in the debugger probably because it is
asynchronous. My trace reveals that 2 records were read before it stopped. I am using port 8000 as my local server and the url it stops on is
http://10.0.2.2:8000/my_album/5_irises.jpg".
Is there something special about downloading jpegs versus png files or is my url coded incorrectly? Is the underscore a problem in the url? Also, do I have to close the connection after each download?
begin of loop {
........
new AccessImages().execute(urlstring);
} ......end of loop
private class AccessImages extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urladds){
return downloadImage(urladds[0]);
}
protected void onPostExecute(Bitmap bm) {
bitmap_photo[itemcount] = bm;
itemcount++;
}
}
private Bitmap downloadImage(String url) {
Log.d("downloadImage", url);
Bitmap bmap = null;
InputStream inStream = null;
// Drawable drawable = null;
try {
inStream = openHttpConnection(url);
Log.d("inStream", String.valueOf(inStream));
// drawable = Drawable.createFromStream(inStream, "src");
Log.d("before bmap", url);
bmap = BitmapFactory.decodeStream(inStream);
Log.d("after bmap", url);
inStream.close();
}
catch (IOException el) {
el.printStackTrace();
}
return bmap;
}
private InputStream openHttpConnection(String urlString) throws IOException {
InputStream inStream = null;
int checkConn = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
try {
Log.d("try openhttpconnection", urlString);
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
checkConn = httpConn.getResponseCode();
if (checkConn == HttpURLConnection.HTTP_OK) {
inStream = httpConn.getInputStream();
Log.d("instream", urlString);
}
}
catch (Exception ex) {
throw new IOException("Error connecting");
}
return inStream;
}
I just found out the NullPointerException was at this instruction:
inStream.close();
What would cause that?
Ok. Now I corrected for the inStream not being null but now I am getting NullPointerException from the following instruction: bitmap_photo[itemcount] = bm;
if(bm != null)
{
bitmap_photo[itemcount] = bm;
itemcount++;
}
Can't I check for a null value in a bitmap or is the array the problem? I should add that I created the bitmap_photo array as follows: Is this a problem?
Bitmap [] bitmap_photo;

BitmapFactory.decodeStream(input) always return null

I have a probleme here.
I have some image url in a list
agenda.get(i).getPicture() // always return a good image url
In a Thread i do this :
for (int i = 0; i < agenda.size(); i ++)
{
Log.e("TEST", " = " +agenda.get(i).getPicture());
Bitmap newBitmap = getBitmapFromURL(agenda.get(i).getPicture()); // getPicture return the url
imagelist.add(i,newBitmap);
}
And getBitmapFromURL return null cause of :
BitmapFactory.decodeStream(input)
in :
private Bitmap getBitmapFromURL(final String src) {
Runnable r=new Runnable()
{
public void run() {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(input);
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
};
return myBitmap;
}
Now if someone has an idea plz !
Thanks
EDIT !
It's possible that
InputStream input = connection.getInputStream();
fail too... I don't know why

Android imageview only accepts some jpg's

I have an image view in my app. when I try to make it show a jpg file exported from 3ds max, it works. But if it comes from Photoshop, it just does nothing. Why is that? If it is at all important my app gets the image from my server with the following code:
public static Bitmap getWebImage(String URL)
{
URL myImageURL = null;
Bitmap bitmap = null;
try {
myImageURL = new URL(URL);
} catch (MalformedURLException error) {
error.printStackTrace();
}
try {
HttpURLConnection connection = (HttpURLConnection)myImageURL .openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
Can you check the color settings of your JPG files? Most likely your JPG files from photoshop is in CMYK rather than RGB, and Android simply doesn't support CMYK.
Would it be possible for you to upload the two pictures for comparison?
public static Bitmap getWebImage(String URL)
{
URL myImageURL = null;
Bitmap bitmap = null;
try {
myImageURL = new URL(URL);
} catch (MalformedURLException error) {
error.printStackTrace();
}
try {
HttpURLConnection connection = (HttpURLConnection)myImageURL .openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}

Categories

Resources