I'm trying to make a simple function that grabs an image from an http connection. It was working before, now it's throwing some errors. I didn't make any changes to the code. Also the Input stream isn't null. It's returning expected data.
D/skia: ---- read threw an exception
D/skia: --- SkAndroidCodec::NewFromStream returned null
I/ERROR: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
This is my Code for reference inside of an async task:
#Override
protected Bitmap doInBackground(String... url){
try {
InputStream in = openHttpConnection(url[0]);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
return bitmap;
} catch (IOException e) {
Log.i("ERROR", e.toString());
return null;
}
}
private static InputStream openHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
httpConn.disconnect();
} catch (Exception e) {
Log.i("ERROR", e.toString());
throw new IOException("Error connecting");
}
return in;
}
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
After this statement bitmap is null. It will always be if you ask decodeStream to just decode the bounds.
Later you try to compress that null bitmap with `bitmap.Compress().
It does not matter if that would be in a static function.
Just dont call it if bitmap==null.
Related
I need to download icons from the OpenWeatherMap website, build a URL, download the image, save it to local storage and also check to see if they already exist. HTTPUtils is underlined in red and when I looked it up, it's no longer being used. The Bitmap code was given to use by the professor.
#Override
protected String doInBackground(String... args) {
try {
URL url = new URL(TEMPS);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inputStream = conn.getInputStream();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
//this is what talks to the xml on the website
xpp.setInput(inputStream, "UTF-8");
while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
if (xpp.getEventType() == XmlPullParser.START_TAG) {
if (xpp.getName().equals("temperature")) {
curr = xpp.getAttributeValue(null, "value");
//tell android to call onProgressUpdate with 25 as parameter
publishProgress(25);
min = xpp.getAttributeValue(null, "min");
publishProgress(50);
max = xpp.getAttributeValue(null, "max");
publishProgress(75);
} else if (xpp.getName().equals("weather")) {
icon = xpp.getAttributeValue(null, "icon");
}
}
xpp.next();
}
//Start of JSON reading of UV factor:
//create the network connection:
URL UVurl = new URL(UV);
HttpURLConnection UVConnection = (HttpURLConnection) UVurl.openConnection();
inputStream = UVConnection.getInputStream();
//create a JSON object from the response
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
String result = sb.toString();
//now a JSON table:
JSONObject jObject = new JSONObject(result);
double aDouble = jObject.getDouble("value");
Log.i("UV is:", ""+ aDouble);
uv = aDouble;
//*****This is where I need help
Bitmap image = null;
URL imageUrl = new URL(IMAGE);
HttpURLConnection connection = (HttpURLConnection) imageUrl.openConnection();
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
image = BitmapFactory.decodeStream(connection.getInputStream());
}
image = HTTPUtils.getImage(IMAGE);
FileOutputStream outputStream = openFileOutput(icon + ".png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 80, outputStream);
outputStream.flush();
outputStream.close();
public boolean fileExistance(String weatherIcons){
File file = getBaseContext().getFileStreamPath(weatherIcons);
return file.exists();
Log.i("File name:", ""+ file);
}
FileInputStream fis = null;
try {
fis = openFileInput("C:/Users/kathy/AndroidStudioProjects/AndroidLabs/app/src/main/res/drawable");
} catch (FileNotFoundException e) {
Log.e("Download this file", e.getMessage());
}
Bitmap bm = BitmapFactory.decodeStream(fis);
publishProgress(100);
Thread.sleep(2000); //pause for 2000 milliseconds to watch the progress bar grow
} catch (Exception ex) {
}
return null;
}
While I don't really understand which package HTTPUtils comes from, I think relying on the standard classes from the JDK and Android SDK is the way to go.
try {
// Get an open Stream to the image bytes
final InputStream stream = new URL(IMAGE).openStream();
// Wrap the Stream in a buffered one for optimization purposes
// and decode it to a Bitmap
try (final InputStream bufferedInputStream = new BufferedInputStream(stream)) {
final Bitmap image = BitmapFactory.decodeStream(bufferedInputStream);
// Process the image
}
} catch (final IOException e) {
// Handle the Exception
}
You might want to extract an helper method, which simply returns the instantiated Bitmap variable.
Below is the code of getInputStream() defined in URLConnection
public InputStream getInputStream() throws IOException {
throw new UnknownServiceException("Does not support writing to the input stream");
}
I'm using this to get an inputstream object in my code
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.connect();
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} catch (IOException e) {
// TODO: Handle the exception
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// function must handle java.io.IOException here
inputStream.close();
}
}
return jsonResponse;
}
inputStream = urlConnection.getInputStream();
How does this statement work because in its definition it is throwing a UnknownServiceException()
I have Facebook graph requests working and seem to have no problem whatsoever, However I have been trying for a while to retrieve the profile picture. But everytime I run it the bitmap seems to turn out null.
public static Bitmap DownloadImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("IMAGE", "Error getting bitmap", e);
}
return bm;
}
For Example, If I feed it this string:
String testString = "graph.facebook.com/849993771766163/picture?type=large";
The bitmap will return null every single time..
What am I doing wrong? I suspect I am getting the url wrong but I have tried everything
Try replacing
bm = BitmapFactory.decodeStream(bis);
with
bm = Bitmap.createBitmap(BitmapFactory.decodeStream(bis));
You may also need to create a scaled bitmap first and then set it to your final bitmap before setting it to a view.
I am using a 'get' method on HttpsUrlConnection. When i am testing my code on eclipse (Windows) it works fine. When i compress it to a jar file and use it on android studio it gives me '405 - method not allowed'. What's mean, I am running the method with bad verb (expected GET).
This is how i set the http method type:
conn.setRequestMethod("GET");
I am setting the http method to 'get' and when i debug it - conn.getRequestMethod = GET and conn.delegate.getRequestMethod = POST.
The error response is - {"Message":"The requested resource does not support http method 'POST'."}
EDITED - code added:
public static HttpsURLConnection getClient(URL url, LoginToken securityToken, RequestMethod methodType, String requestFormat, String responseFormat) throws IOException, SecurityTokenException {
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.addRequestProperty("Accept-Charset", "UTF-8");
conn.addRequestProperty("Content-Type", requestFormat);
conn.addRequestProperty("Accept", responseFormat);
conn.addRequestProperty("User-Agent", "***SDK/1.0");
conn.setRequestProperty("Cache-Control", "no-cache");
if(securityToken != null) {
LoginToken.ValidateToken(securityToken);
conn.addRequestProperty("Authorization", String.format("Bearer %1$s", new Object[]{securityToken.getTemporarySecurityCode()}));
}
conn.setRequestMethod(methodType.toString());
conn.setUseCaches(false);
conn.setDoOutput(true);
return conn;
}
public Boolean IsCompleted() throws SecurityTokenException, CommandFailedException {
LoginToken.ValidateToken(this.getSecurityToken());
HttpsURLConnection conn = null;
Gson gson = (new GsonBuilder()).create();
String json;
try {
URL url = new URL(String.format("https://api.***.com/%1$s/detector/%2$s/status", new Object[]{"v1", this.getPID()}));
conn = ***Client.getClient(url, this.getSecurityToken(), RequestMethod.GET, "application/json", "text/plain");
Throwable response1;
BufferedInputStream inputStream;
if(conn.getResponseCode() != 200) {
response1 = null;
inputStream = null;
String response2;
try {
BufferedInputStream inputStream1 = new BufferedInputStream(conn.getErrorStream());
try {
response2 = HttpURLConnectionHelper.convertStreamToString(inputStream1);
} finally {
if(inputStream1 != null) {
inputStream1.close();
}
}
} catch (Throwable var41) {
if(response1 == null) {
response1 = var41;
} else if(response1 != var41) {
response1.addSuppressed(var41);
}
throw response1;
}
BadLoginResponse response4 = (BadLoginResponse)gson.fromJson(response2, BadLoginResponse.class);
if(response4 == null) {
throw new RuntimeException("Unable to process server response.");
}
throw new CommandFailedException(response4.getMessage(), conn.getResponseCode());
}
Throwable response = null;
response1 = null;
try {
inputStream = new BufferedInputStream(conn.getInputStream());
try {
json = HttpURLConnectionHelper.convertStreamToString(inputStream);
} finally {
if(inputStream != null) {
inputStream.close();
}
}
} catch (Throwable var43) {
if(response == null) {
response = var43;
} else if(response != var43) {
response.addSuppressed(var43);
}
throw response;
}
} catch (IOException var44) {
throw new RuntimeException(var44.getMessage());
} finally {
if(conn != null) {
conn.disconnect();
}
}
How can i fix it?
Thanks BNK!
The solution was to remove conn.setDoOutput(true)
This question already has answers here:
"java.net.MalformedURLException: Protocol not found" read to html file
(2 answers)
Closed 9 years ago.
I am using following code and it keeps giving me malformedurlexception error. The funny part is I have copied it from another project which the same code is working properly. I was wondering if anyone can see what the problem might be. The section of code which is giving the error is in OpenHttpConnection function and at start where it says:
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
I appreciate any help I can get.
Bitmap bitmapOrg = null;
bitmapOrg = DownloadImage("http://www.bagherpour.com/apache_pb.gif");
public Bitmap DownloadImage(String txt)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(txt);
bitmap = BitmapFactory.decodeStream(in);
in.close();
return bitmap;
} catch (IOException e1) {
e1.printStackTrace();
Log.d("bitMap",e1.toString());
return null;
}
}
public InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
Change to:
URL rul = new URL("httpwww.bagherpour.com/apache_pb.gif")