BitmapFactory.decodeStream not working - android

I'm having a bit of a problem with decodeStream returning null. It seems to be a fairly common problem around, but it's usually pinned down to one of two problems:
An OutOfMemory exception thrown by attempting to load a large bitmap in it's entirety.
Attempting to use the same input stream twice.
However, I'm not doing either. The code to run it is simply
stream = new java.net.URL(url).openStream();
Bitmap image = BitmapFactory.decodeStream(stream);
stream.close();
with the URL set to here. image is null after this code is complete. This issue's been driving me completely insane - it works fine on PNGs but seems to fall apart under every BMP I can give it, so any help would be appreciated.

Ultimately, the answer was found here, using an InputStream returned by a BufferedHTTPEntity. While it seems needlessly complex, I can only assume that simply getting a stream from the URL object directly doesn't return a stream of the appropriate type, and so it wasn't reading out all the data properly.
Cross-posting the code in case the question is erased:
private static InputStream fetch(String address) throws MalformedURLException,IOException {
HttpGet httpRequest = new HttpGet(URI.create(address) );
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream instream = bufHttpEntity.getContent();
return instream;
}

Related

Android - HTTP GET Request huge size of JSON response

I have a big JSON input (download the file) API and I don´t know how to parse this data. I need:
Save this data (entire JSON input) to text file or database. What is the best way for this?
Load this data from text file or database and create JSONArray from JSON tag "list" (first tag)
The solution should be fast and support Android 2.3. What you have recomend for this? Any ideas?
My code:
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(urls[0]);
HttpResponse httpResponse;
httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
... and what next ?...
FYI:
EntityUtils throws OutOfMemoryException
EDIT:
I try to save data to file like this:
InputStream inputStream = httpEntity.getContent();
FileOutputStream output = new FileOutputStream(Globals.fileNews);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, len);
}
And it´s OK. I load data:
FileInputStream fis = null;
StringBuffer fileContent = new StringBuffer("");
fis = new FileInputStream(Globals.fileNews);
byte[] buffer = new byte[1024];
while (fis.read(buffer) != -1) {
fileContent.append(new String(buffer));
}
But how convert StringBuffer to JSONObject? fileContent.ToString() is not ideal, sometimes I get OutOfMemoryException.
First of all: Dispose the HttpClient. Google discourages it:
Unfortunately, Apache HTTP Client does not, which is one of the many
reasons we discourage its use.
Source: developer.android.com
A good replacement is Google Volley. You have to build the JAR yourself but it just works like charm. I use for my setups Google Volley with OkHttp-Stack and GSON requests.
In your case you would write another Request which just writes the response out to the SD-card chunk by chunk. You don't buffer the string before! And some logic to open an input-stream from the file you wrote and give it to your JSON Deserializer. Jackson and GSON are able to handle streams out of the box.
Of course everything works with Android 2.3.
Don't, I repeat, don't try to dump the whole serialized stuff into a string or something. That's almost a OutOfMemoryException guarantee.

Getting null bitmap while trying to get Facebook image using Facebook ID

This is the code I'm using.
String imageURL;
Bitmap bitmap = null;
imageURL = "http://graph.facebook.com/" + fbID + "/picture?type=";
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(imageURL)
.getContent());
} catch (Exception e) {
e.printStackTrace();
}
when i use this URL in browser it shows image, but when trying to get it in bitmap it gives null.
I've checked many question, but nothing help me.
This code works for me with HTTPGet:
HttpGet httpRequest = new HttpGet(URI.create(linkUrl) );
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
bmap = BitmapFactory.decodeStream(bufHttpEntity.getContent());
httpRequest.abort();
This problem is due to the fact that, Facebook uses its graph API url merely as a redirection endpoint. If you copy paste a facebook profile picture URL such as
http://graph.facebook.com/subinsebastien/picture
What actually happens is that, Facebook redirects you to the actual image URL. Thus, when you try to open an input stream with the graph API url, you wont actually get a bitmap, rather a redirect response is what you get. In my case, this is where I'm being redirected to.
https://scontent-b.xx.fbcdn.net/hprofile-prn1/l/t5.0-1/48771_100000333400619_475851971_q.jpg
Thus, I would rather suggest you to use an actual HTTPGet to get the bitmap first.

Android multipart/x-mixed-replace - decode bitmap from inputstream returns null

I'm reading a stream but when I'm trying to decode it (converting into a bitmap) I'm getting null, no exception is thrown.
This is my code:
HttpGet httpRequest = new HttpGet(URI.create(link));
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
Bitmap bitmap = BitmapFactory.decodeStream(bufHttpEntity.getContent());
The InpuStream which I get from bufHttpEntity.getContent() is not null, it has 38 KB data.
All I know about the stream server is that the header has content-type: multipart/x-mixed-replace;boundary=<boundary-name>
If I'm opening the link in a browser, it is working, I can see the image, but when I'm trying to convert it into a Bitmap I'm getting null.
Have a look at the docs of BitmapFactory.decodeStream():
The decoded bitmap, or null if the image data could not be decoded.
And I guess that's what causes the issue. multipart means the content can contain multiple files, separated by the boundary and individual headers. Even if there is only one file, it will be framed by the header, and a boundary at the start and the end. I honestly don't know what multipart/x-mixed-replace;boundary=<boundary-name> means in detail.
The HttpEntity does not remove the boundary, and thus the Bitmap cannot be decoded.
Try to save the content to a file, and view that in a HEX viewer. You'll then know how you have to "convert" the received data so you can decode the bitmap.

Android - downloading compressed answer from http

I am trying to get compressed data from server. The guy that programmed the server told me, that he uses ZLIB library on his iPhone, and the gzcompress on server. I was trying to find any suitable way to get that data, but it ends up with info "java.io.IOException: unknown format (magic number 9c78)" while creating GZIPInputStream object. Finally I've reached point, where I had data as a String. It was compressed, so I used that answer to decompress: https://stackoverflow.com/a/6963668/419308 . But that code doesn't work. "in.read()" returns -1 at the beginning.
Anyone has any idea why there's -1 ? Or maybe a better way to get the compressed data?
EDIT:
I tried adding file to project and reading from that file. in.read() didn't return -1
EDIT2: According to jJ's answer I've tried this code:
HttpGet request = new HttpGet( urlTeam );
HttpResponse response = new DefaultHttpClient().execute( request );
HttpEntity entity = response.getEntity();
InputStream stream = AndroidHttpClient.getUngzippedContent( entity );
InputStreamReader reader = new InputStreamReader( stream );
BufferedReader buffer = new BufferedReader( reader );
StringBuilder sb = new StringBuilder();
sb.delete( 0, sb.length() );
String input;
while ( ( input = buffer.readLine() ) != null )
{
sb.append( input );
}
But the answer is still compressed (or unreadable)
on android you should use either HttpURLConnection which handles decompression (and http encoding headers) for you from GingerBread on or AndroidHttpClient (for older android versions) that has helper methods like getUngzippedContent and modifyRequestToAcceptGzipResponse.
This is a good summary Android HTTP clients

reading encoded string HTTP request to android

I have a RESTful WCF service that I am using to retrieve encoded photos and display them in android (trying to anyway). The problem I am having is that the InputStream or possibly something else stops reading the characters before the end.
The response is just an XML string, I intend to parse it myself so no need to worry about that. What I need to know is what in the following code is stopping the input stream from reading characters into my buffer.
HttpEntity responseEntity = response.getEntity();
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
Have you implemented the HttpURLConnection class.. this would cause this behavior.
http://developer.android.com/reference/java/net/HttpURLConnection.html

Categories

Resources