i am working on my android application and trying to download an Image from web server (Local Host IIS7).but unfortunately my app doesn't work.actually when i run my app it doesn't show any picture inside the ImageView .
I compiled my app but i didn't find any error in logCat! it seemed every thing was ok.there was only one exotic message :
Choreographer skipped 32 frames
but according to my Research , i think it cant impact my application.
one more thing i think , onPostExcute is not Run.but i cant find the reason.
Here is my code :
public class Ads extends Activity {
private 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){
Log.d("NetWorking",ex.getLocalizedMessage());
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImag(String URL){
Bitmap bitmap=null;
InputStream in=null;
try{
in=OpenHttpConnection(URL);
bitmap=BitmapFactory.decodeStream(in);
in.close();
}catch(IOException e1){
Log.d("NetworkActivity",e1.getLocalizedMessage());
}
return bitmap;
}
public class DownloadImages extends AsyncTask<String,Void,Bitmap>{
protected Bitmap doInBackground(String...urls){
return DownloadImag(urls[0]);
}
protected void onPostExcute(Bitmap result){
try{
Log.d("Setting ImgView","Ok");
ImageView img=(ImageView)findViewById(R.id.imageView1);
img.setImageBitmap(result);
}
catch(Exception ex){
Log.d("Setting ImgView","Error");
}
}
}
/** Called when the activity first created */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ads);
Log.d("Start-Working", "ok");
new DownloadImages().execute("http://10.0.2.2:80/Urgence/document/img/my.jpg");
}
}
what should i do ?!
you can use one library for faster image loading,
it cache image with quality you ask for.
Universal-Image-Loader
it's easy to implement as snippet given in page.
You also can get bitmap like....
// Load image, decode it to Bitmap and return Bitmap synchronously
Bitmap bmp = imageLoader.loadImageSync(imageUri);
Related
I have just such a problem, the following small code image downloader where params[0]- url and params[2] - file name, this design works well on Android 5.0+, but on older versions, I get an error:
-javax.net.ssl.SSLException: Connection closed by peer
#Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
InputStream is = null;
try {
is = new URL(params[0]).openStream();
} catch (IOException e) {
e.printStackTrace(); // Exception there
}
bitmap = BitmapFactory.decodeStream(is);
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
OutputStream outStream = null;
File file = new File(Constans.DATA_APPLICATION_PATH+"/photo/"+params[1].replace("\"","").trim());
try {
// make a new bitmap from file
outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
file.deleteOnExit();
return bitmap;
}
`
You have problem with SSL authorization, which will come for sure if you are using self signed certificates.
So the way to make android app to connect to URL is to skip the SSL verification (Only if we are sure about the connection)
For this you can add this class and execute it inside onCreate method
new NukeSSLCerts().nuke();
It will skip certificate verification by trusting all certificates.
I have a Parse Android app for which I am implementing Facebook sign up. Currently I am stuck on grabbing images to set as profile pictures of new ParseUser's. I have successfully used the Facebook Graph API to retrieve the correct URL (I have checked this by plugging it into a browser, where I am shown the right profile picture), but I now need a way to turn that URL into a byte array (byte[]) so that I can save the ParseFile field of our ParseUser's profile picture. I have already looked at all these SO questions:
• java.net.URL read stream to byte[]
• Efficiently read file from URL into byte[] in Java
• Get image with given url and convert it to byte array
None of these have worked. I am currently trying to use the Apache IOutils, like in the solution from the second link. Here is my current code for the AsyncTask:
private class SetProfPicWithURL extends AsyncTask<URL, Integer, byte[]> {
#Override
protected byte[] doInBackground(URL... imageURL) {
Log.i("SetProfPicWithURL", "invocation, URL: " + imageURL[0]);
InputStream is = null;
byte[] bytes = null;
try {
is = imageURL[0].openStream();
bytes = IOUtils.toByteArray(is);
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (is != null) try {
is.close();
if(bytes == null){Log.e("LoginActivity", "bytes is null int SetProfPicWithURL");}
final ParseFile imageFile = new ParseFile("image.jpg", bytes);
imageFile.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.i("LoginActivity", "getCurrentUser.put");
ParseUser.getCurrentUser().put(ParseUtils.PARSE_PROFILE_IMAGE, imageFile);
ParseUser.getCurrentUser().saveInBackground();
} else {
e.printStackTrace();
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
return bytes;
}
}
Now when this code executes, I get no error logs, and a ParseFile is created. However, no profile pictures load within the app, and when I click to examine the file in the dashboard, I get this error message:
The file “tfss-0280f98d-7180-4528-9d24-3ec47d3b25d4-image.jpg” could
not be opened because it is empty.
Honestly, I'm at a loss. I've spent significantly more time on this one photo issue than any other part of implementing the Facebook login. And the way our database is set up, it is really not ideal to create another field to save the URL and load with Picasso. Any help with this issue is truly appreciated!
Directly save your imagefile as profile picture like this :
final ParseFile imageFile = new ParseFile("image.jpg", bytes);
ParseUser.getCurrentUser().put(ParseUtils.PARSE_PROFILE_IMAGE, imageFile);
ParseUser.getCurrentUser().saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.i("LoginActivity", "Profile saved succesfully");
} else {
e.printStackTrace();
}
}
});
EDIT :
Use this to get image byte array from url.
try {
java.net.URL img_value = new java.net.URL(imageURL);
Bitmap mIcon = BitmapFactory
.decodeStream(img_value.openConnection()
.getInputStream());
if (mIcon != null)
imgByteArray = encodeToByteArray(mIcon);
} catch (Exception e) {
e.printStackTrace();
}
public byte[] encodeToByteArray(Bitmap image) {
Log.d(TAG, "encodeToByteArray");
Bitmap b= image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imgByteArray = baos.toByteArray();
return imgByteArray ;
}
OK, so I'm writing an Android app, and am trying to download a Bitmap and set it as an ImageView. The code is below for the relevant parts:
private class GetContactInfo extends AsyncTask<String, Void, ContactInfo[]> {
#Override
protected ContactInfo[] doInBackground(String... url) {
// Instantiate what is needed
URL json = null;
//Set the JSON URL
try {
json = new URL(url[0]);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
// Use Jackson library to read out the data from the contacts page
try {
contacts = mapper.readValue(json, ContactInfo[].class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Add everything into the bitmap ArrayList
for (int i = 0; i < contacts.length; i++) {
String imageURL = contacts[i].getSmallImageURL();
// Download the Bitmap and add it to the ArrayList
try {
bitmap.add(downloadBitmap(imageURL));
} catch (IOException e) {
e.printStackTrace();
}
}
// Return statement
return contacts;
}
public Bitmap downloadBitmap(String imageURL) throws IOException {
URL url = new URL(imageURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream stream = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(stream);
if (bitmap == null) {
Log.e("Null", "Bitmap null");
}
return bitmap;
}
The log never catches that bitmap is null, or at least it doesn't show it (I see in the stack trace that there are 4 more errors, but they never show up and I'm not sure how to expand it to show the other errors.)
The NullPointerException comes at the bitmap.add(downloadBitmap(imageURL)); line. So somehow my downloadBitmap function is returning a null result. Any ideas?
Edit: I'm not sure if this matters, but the images in the URLs are .jpeg files.
Edit 2: Put this in the comments so I will edit it into my post as well, bitmap is declared as a Global Variable like so ArrayList<Bitmap> bitmap; This is so I can later use it in my onPostExecute method.
As you said the error is at line
bitmap.add(downloadBitmap(imageURL));
which means culprit is your bitmap variable and not downloadBitmap(imageURL) method.
Also, in your edit you have mentioned that you have declared bitmap as a global variable - ArrayList bitmap;
In order to access(add bitmap onjects to it) this globally declared variable you must initialize it.
In your onCreate do -
bitmap = new ArrayList<Bitmap>();
and the NPE must go.
While you are downloading images from the Internet, you should use an async request. In downloadBitmap the connection is downloading in another thread, but the main thread has returned bitmap immediately, whether or not the downloading is accomplished.
Where did you initialized bitmap? As far as I can tell, it is null and you are using that null object, so Null Pointer Exception come out. That's from the information you provided. If the error is occurred inside the function, it's the different matter.
Good day,
I'm trying to retrieve an image using Jsoup but I'm unsure as to what exactly I should be getting from the website. I've used the following code to read from the website and have been able to get the images particular title and the URL it links to but not the image.
I want to set this image to the ImageView that I have in the activity. Here's my code thus far:
// Get the required stuff from the webpage
Document document = null;
try {
document = Jsoup.connect(URL).get();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Element info = document.select("div.featurebox").first();
// Caption on image
docInfo = info.text();
// URL of image
imageURL = info.attr("data-url");
// Retrieve the actual image
Element featureImage = document.select("div.featurebox-image").first();
// Unsure what to get here
It should be noted that the image isn't stored as a normal img-src way. The particular div class I'm looking at is this:
<div class="featurebox-image" style="background:url(http://img.mangastream.com/cdn/feature/02.jpg) center center;">
<div class="featurebox-caption">
<strong>History's Strongest Disciple Kenichi <em>544</em></strong> - Witch </div>
</div>
So I'm after the actual image from that URL.
How do i go about this?
Thanks
Thanks to Hardip Patel for providing the start. Here is what I did:
I took Hardips code and changed it to the following:
Element featureImage = document.select("div.featurebox-image")
.first();
String temp = featureImage.getElementsByAttribute("style")
.toString();
// URL of image
imageStrg = temp
.substring(temp.indexOf("(") + 1, temp.indexOf(")"));
After that it took alittle looking about StackOverflow to find out how to set it. I initially tryed to set it using the URL using the setImageURI() method, but that was throwing an error. See here for why. Instead I used that SoH's answer to create a bitmap from the URL:
// Method to return a bitmap from an images URL
private Bitmap getImageBitmap(String url) {
Bitmap bm = null;
try {
// See what we are getting
Log.i(TAG, "" + url);
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(TAG, "Error getting bitmap", e);
}
return bm;
}
After that I just had to set the Bitmap from earlier and update the image view using the ASyncTask's onPostExecute() method:
imageOne = getImageBitmap(imageStrg);
#Override
protected void onPostExecute(String result) {
// Write the result (document title) to the textview
super.onPostExecute(result);
// Update the textview with results
if (result == null) {
txtVwDocTitleValue.setText("Nothing to report...");
} else {
txtVwDocTitleValue.setText(result);
txtVwDocURLValue.setText(imageURL);
// Set the views image
imgVwManga1.setImageBitmap(imageOne);
}
// Destroy the progress bar
stopProgressDialog();
}
Cheers all!
See if this works :-
String temp = featureImage.getAttribute("style");
String url = temp.substring(temp.indexOf("(")+1,temp.indexOf(")"));
Try this
Document doc = Jsoup.connect("www.mywebsite.com").get();
Elements images = doc.select("img[src~=(?i)\.(png|jpe?g|gif)]");
I am trying to download image from server. Few are downloading and few and creating problem. I don't know why.
I have downloaded and show image to user on the same location. Here is the file which is able to download.
http://www.mongreldog.co.nz/unilogo/Backgrounds_20399.png
When I am trying to download following image. This image is opening in browser but not downloading in android
http://www.mongreldog.co.nz/unilogo/Twitter-Ryan_Giggs_Imogen_Thomas_Guard-Footballer_Affair_UK_Manchester%20United_M_785.jpg
Its give exception
java.io.FileNotFoundException: http://www.mongreldog.co.nz/unilogo/Twitter-Ryan_Giggs_Imogen_Thomas_Guard-Footballer_Affair_UK_Manchester United_M_785.jpg
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:521)
at src.com.mongreldog.appsupport.Utils.downloadImage(Utils.java:77)
at src.com.mongreldog.ViewFullCompAndCommentActivity$3.performInBackground(ViewFullCompAndCommentActivity.java:607)
at src.com.mongreldog.appsupport.HeavyWorker.doInBackground(HeavyWorker.java:44)
at src.com.mongreldog.appsupport.HeavyWorker.doInBackground(HeavyWorker.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
Here is my code.
public static Bitmap downloadImage(String imageURLStr) {
Bitmap bitmap = null;
InputStream in = null;
try {
URL url = new URL(imageURLStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
in = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (SocketTimeoutException e) {
bitmap = null;
e.printStackTrace();
} catch (IOException e) {
bitmap = null;
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
bitmap = null;
} catch (OutOfMemoryError e) {
e.printStackTrace();
bitmap = null;
}
return bitmap;
}
Use URL Encoder to encode the image URL, as you can see the URL have white spaces in the log report.
public static Bitmap downloadImage(String imageURLStr) {
imageURLStr = URLEncoder.encode(imageURLStr, "utf-8");
//... rest of your code.
}
Edit: as you reported of issue '+' instead of %20
you can use
public static Bitmap downloadImage(String imageURLStr) {
imageURLStr = imageURLStr.replaceAll(" ", "%20");
//... rest of your code.
}
For source check here
I try to use URLEncoder.encode() to encode the URL. Its strange that it convert " " with "+".
Please try Uri.encode(imageURL). I just try it and its working perfectly.
I have tested that in android.
Looks like the file name is not being parsed correctly (the space between 'Manchester' and 'United').
Use URLEncoder.encode() to encode the URL.
Your second URL is very instable. It may return 404 in the most cases even in Chome. I have seen the picture only once.