Get Image from Url Unable to Decode Stream: fileNotFoundException - android

I know this issue as been ask many times but i've tried many solutions and no one works.
On Android, I'm trying to get an image from URL to put it in an image view.
Unfortunately, I get the following error :
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: http:/lorempixel.com/1920/1920/business (No such file or directory)
When I try to reach this URL from the browser of the emulator, it works.
I've already tried the following solutions :
Load image from url
How to get image from url website in imageview in android
how to set image from url for imageView
My actual code is the following :
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView imgView;
public DownloadImage(ImageView imgView){
this.imgView = imgView;
}
#Override
protected Bitmap doInBackground(String... urls) {
return download_Image(urls[0]);
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null)
imgView.setImageBitmap(result);
}
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();
Log.e("CON ", "HTTP connection OK");
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap download_Image(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection("http://lorempixel.com/1920/1920/business");
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
}
In the main activity my code is :
ImageView img = (ImageView) findViewById(R.id.imageView);
DownloadImage download = new DownloadImage(img);
download.execute(url);
In the manifest I've added :
<uses-permission android:name="android.permission.INTERNET" />
What can I do ?

This works perfect:
String urlPath = "http://anyWebsite.com/images/12"
Bitmap bm = BitmapFactory.decodeStream((InputStream) new URL(urlPath).getContent());
myImageView.setImageBitmap(bm);

Related

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;

Downloaded image shown blank in imageview

I used several different methods for downloading image from a web server , display it in image view. I am facing the same problem the image is being shown as blank in the imageview after downloading. I am not getting where i am wrong. I am using emulator.
this is my code for downloading images
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();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
static Bitmap DownloadImage(String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
This is my code for displaying image
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// perform long running operation operation
Bitmap message_bitmap = null;
// Should we download the image?
if ((image_url != null) && (!image_url.equals("")))
{
message_bitmap =
ImageDownloader.DownloadImage(image_url);
}
// If we didn't get the image, we're out of here
if (message_bitmap == null) {
Log.d("Image", "Null hai");
}
return null;
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
pDialog.dismiss();
iv.setImageDrawable(message_bitmap);
Log.d("Image", "Displayed");
}
/* (non-Javadoc)
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
// Things to be done before execution of long running operation.
pDialog = new ProgressDialog(CommonUtilities.this);
pDialog.setMessage(Html.fromHtml("Please Wait..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
}
I used this code for loading img form url
ImageView v_thumburl = (ImageView) rowView
.findViewById(R.id.v_thumb_url);
thumburl = temp.getString(temp.getColumnIndex("thumburl"));
Drawable drawable = LoadImageFromWebOperations(thumburl);
v_thumburl.setImageDrawable(drawable);
private Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
System.out.println("Exc=" + e);
return null;
}
}

Image not showing on image view

I am trying to set image on imageview but image is not show.
I am reading image url from json data and then trying to set it on ImageView but my image is not visible. No any exception occur.
Here is my code
HotelList.class
static final String TAG_DISHIMAGEURL = "dishimageurl";
......
String imageUrl = dishResult.getString(TAG_DISHIMAGEURL);
map.put(TAG_DISHIMAGEURL, imageUrl);
.....
dishimageurl1 = hm.get(TAG_DISHIMAGEURL).toString();
intent.putExtra("background", dishimageurl1);
HotelDetails.class
......
String dishimageurl = bundle.getString("background");
Bitmap bimage= getBitmapFromURL(dishimageurl);
imageView.setImageBitmap(bimage);
....
public Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
Toast.makeText(this, "showing image", Toast.LENGTH_LONG).show();
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
Toast.makeText(this, "showing exception", Toast.LENGTH_LONG).show();
return null;
}
}
I don't understand what happen with this code. No any exception but my image is not visible.
Please give me any reference.
Please Use below code for get image from url and display into imageview.
public class image extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap = DownloadImage("http://www.gophoto.it/view.php?i=http://1.bp.blogspot.com/-2LTvCCufBKc/T3L3KgcTj2I/AAAAAAAABbQ/Ki60e1LU9sE/s1600/Sachin%2BTendulkar.png");
RelativeLayout mRlayout1 = (RelativeLayout) findViewById(R.id.mRlayout1);
Drawable d=new BitmapDrawable(bitmap);
mRlayoutLogin.setBackgroundDrawable(d);
}
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) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
}
you can view image by using this code.
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It seems you are downloading the image from UI thread. this will block the UI thread and will give you not responding error. as an easy way, you can use a library like Universal Image Loader
Universal Image Loader - GitHub
this will manage the image loading for you and avoid problems like incorrect urls, Out Of Memory error.

Android: Http GET request failing to connect

I'm new to Android programming and could really use some help with a program I'm writing to establish a Http connection and display an image.
I'm using the 'Beginning Android Application Development' book by Wei-Meng Lee. The code compiles and there are no errors flagging up but every time I run the program the 'error connecting' message appears and no image is displayed.
I've looked at various samples of code for GET requests but can't find anything that works with my code.
Any help that anyone can offer would be greatly appreciated as I am struggling to see any solution so far.
The last line of code about uses-permission was included in the Manifest.
ImageView image;
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) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
}
catch (IOException e1) {
Toast.makeText(this, e1.getLocalizedMessage(), Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
return bitmap;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network);
Bitmap bitmap = DownloadImage("http://www.mayoff.com/5-01cablecarDCP01934.jpg");
image = (ImageView) findViewById(R.id.image);
image.setImageBitmap(bitmap);
}
<uses-permission
android:name="android.permission.INTERNET" />
Maybe problem is you having because of api version. you must use AsyncTask class for accessing web functions.
This may be related to the fact that in apis 11 and above accessing the net in Main thread is not allowed you may have to use ASYNC task.
example for using ASYNC task;
class InternetFileCheack extends AsyncTask<Object, Void, Boolean> {
private Button btn;
private String fileURL;
Context c;
public InternetFileCheack (Button imv, String url, Context ctx) {
this.btn = imv;
this.fileURL = url;
this.c = ctx;
}
#Override
protected Boolean doInBackground(Object... params) {
Boolean sonuc = null;
try {
URL u = new URL(fileURL);
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("HEAD");
huc.connect();
int code = huc.getResponseCode();
if (code == HttpURLConnection.HTTP_OK) {
sonuc = true;
} else {
sonuc = false;
}
} catch (Exception e) {
sonuc = false;
}
return sonuc;
}
#Override
protected void onPostExecute(Boolean result) {
btn.setEnabled(result);
if (result) {
Toast.makeText(c, "", Toast.LENGTH_LONG).show();
btn.setVisibility(View.VISIBLE);
} else {
btn.setVisibility(View.GONE);
}
}
}

with android set wallpaper from url i dont understand

Hi everyone I've check the post on the set wallpaper from URL but I am really new to programing and I still do not undertand it, could someone provide me with an example, basically I have an image on a server and I want to push a button and set it as the phone wallpaper thank you again for the help
public class TestingThree extends Activity {
ImageView image;
private class BackgroundTask extends AsyncTask
<String, Void, Bitmap> {
protected Bitmap doInBackground(String...url) {
//--- download an image ---
Bitmap bitmap = DownloadImage(url[0]);
return bitmap;
}
protected void onPostExecute(Bitmap bitmap) {
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bitmap);
}
}
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)
{
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
}
catch (IOException e1){
Toast.makeText(this,e1.getLocalizedMessage(),
Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
return bitmap;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.wallpaper);
new BackgroundTask().execute("http://myglobaljournal.com/images/imagetest.jpg");
Button setWallpaper = (Button) findViewById(R.id.button3);
setWallpaper.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
WallpaperManager wManager;
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeFile(null);
wManager = WallpaperManager.getInstance(getApplicationContext());
wManager.setBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
am trying to implement it to the button at the bottom where i pull the image from the link and set it directly as a wallpaper
thank you again
try this:
ImageView image;
private class BackgroundTask extends AsyncTask
<String, Void, Bitmap> {
protected Bitmap doInBackground(String...url) {
//--- download an image ---
Bitmap bitmap = DownloadImage(url[0]);
return bitmap;
}
protected void onPostExecute(Bitmap bitmap) {
ImageView image = (ImageView) findViewById(R.id.imageView1);
bitmaptwo=bitmap;
image.setImageBitmap(bitmap);
}
}
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)
{
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
}
catch (IOException e1){
Toast.makeText(this,e1.getLocalizedMessage(),
Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
return bitmap;
}
public Bitmap bitmaptwo;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.wallpaper);
new BackgroundTask().execute("http://myglobaljournal.com/images/imagetest.jpg");
Button setWallpaper = (Button) findViewById(R.id.button3);
setWallpaper.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
WallpaperManager wManager;
try {
// bitmap = BitmapFactory.decodeFile(null);
wManager = WallpaperManager.getInstance(getApplicationContext());
wManager.setBitmap(bitmaptwo);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
Required Permission:
<uses-permission android:name="android.permission.SET_WALLPAPER"/>

Categories

Resources