In my app, when you click on the button then I am downloading the images from the url's. It displaying the images some time correctly but some time it display empty. *problem is some times bitmap object(i.e, "result" in code ) return null.*please can anybody help me.
Following is my code
try
{
String ImageUrl = ((eachReview)RB_Constant.revht.get(title_value)).UserImageUrl;
System.out.println("Image Url:"+ImageUrl);
if(ImageUrl != null)
{
DownLoadImageInAThreadHandler(ImageUrl,holder);
}
else
{
System.out.println("Image url is null then display the default image");
holder.userImage.setImageResource(R.drawable.defaultuserimage);
}
}
catch(Exception e){
System.out.println("Error from Userimage fetching.."+e.toString());
}
private void DownLoadImageInAThreadHandler(final String imgurl,final ViewHolder holder)
{
//Thread for getting the attributes values
Thread t = new Thread()
{
public void run()
{
try
{
Bitmap drawable = getDrawableFromUrl(imgurl);
System.out.println("Drawable(after downloading):"+drawable);
if(drawable != null)
{
holder.userImage.setImageBitmap(drawable);
}
else
{
System.out.println("after downloading drawable is null then set the default image");
holder.userImage.setImageResource(R.drawable.defaultuserimage);
}
}
catch(Exception exp)
{
System.out.println("Exception in DownLoadImageInAThread : " + exp.getMessage());
}
}
private Bitmap getDrawableFromUrl(String imageUrl)
{
try
{
URL myFileUrl = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
final Bitmap result = BitmapFactory.decodeStream(is);
is.close();
new Thread() {
public void run() {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if(result != null)
{
result.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
}
}
}.start();
return result;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
};
t.start();
}
Try making you getDrawableFromUrl as:
public static Drawable getDrawableFromUrl(String url) {
Drawable image = null;
try {
InputStream in = (java.io.InputStream) new java.net.URL(url).getContent();
if (in != null) {
image = Drawable.createFromStream(in, "image");
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return image;
}
Also do not compress image within same function. Try Doing it after you successfully receive an image. One thing more that write getDrawableFromUrl function out of the thread but in same class. Hope this works for you.
Related
Good morning,
I have following code to download bitmpa from server
/*SAVE IMAGE++++++++++++++++++++*/
public void saveImage(Context context, Bitmap b, String imageName) {
FileOutputStream foStream;
try {
foStream = context.openFileOutput(imageName, Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.JPEG, 100, foStream);
foStream.close();
UPDTV_FOTO.setBackgroundColor(Color.GREEN);
image.setImageBitmap(loadImageBitmap(getApplicationContext(), Giocatore));
UPDTV_FOTO.setText("Download "+Giocatore+ " Complete");
}
catch (FileNotFoundException e) {
Log.d("saveImage", "file not found");
e.printStackTrace();
// UPDTV_FOTO.setText("FILE NOT FOUND");
}
catch (IOException e) {
Log.d("saveImage", "io exception");
e.printStackTrace();
// UPDTV_FOTO.setText("SAVE IMAGE ERROR");
}
}
/*SAVE IMAGE+++++++++++++++++++++++++*/
/*DOWNLOAD IMAGE++++++++++++++++++++++*/
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
private String TAG = "DownloadImage";
private Bitmap downloadImageBitmap(String sUrl) {
Bitmap bitmap = null;
try {
InputStream inputStream = new URL(sUrl).openStream(); // Download Image from URL
bitmap = BitmapFactory.decodeStream(inputStream); // Decode Bitmap
inputStream.close();
} catch (Exception e) {
Log.d(TAG, "Exception 1, Something went wrong!");
e.printStackTrace();
// UPDTV_FOTO.setText("DOWNLOAD ERROR");
}
return bitmap;
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadImageBitmap(params[0]);
}
protected void onPostExecute(Bitmap result) {
saveImage(getApplicationContext(), result, Giocatore);
}
}
/*DOWNLOAD IMAGE++++++++++++++++++++++*/
/*LOAD IMAGE*+++++++++++++++++++++++++++++++++++++*/
public Bitmap loadImageBitmap(Context context, String imageName) {
Bitmap bitmap = null;
FileInputStream fiStream;
try {
fiStream = context.openFileInput(imageName);
bitmap = BitmapFactory.decodeStream(fiStream);
fiStream.close();
} catch (Exception e) {
Log.d("saveImage", "Exception 3, Something went wrong!");
e.printStackTrace();
// UPDTV_FOTO.setText("LOAD ERROR");
}
return bitmap;
}
/*LOAD IMAGE+++++++++++++++++++++++++++*/
if the bitmap I try to download is available on server all works fine with
new DownloadImage().execute(myurl);
else if is not available, my app crashes.
So I would like to check if bitmap is available on servere before starting download.
I try
if (URLUtil.isValidUrl(URL+FotoGiocatore)==true);
and also
How can I programmatically test an HTTP connection?
Check if file exists on remote server using its URL
You can also use below code to check if the image is present
URL url = new URL("YOUR URL");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
`int status = urlConnection.getResponseCode();`
and only start download if status==200
I'm trying to use WallpaperManager in a ViewPager. I've got a button which is supposed to set the current image in the ViewPager to wallpaper. My problem comes with the line of code wallpManager.setResource(newInt);... the integer it comes up with is always 0 (zero), and so the app crashes and LogCat says there's no Resource at ID #0x0. As a test to see if I'm getting the correct image URL I've done this:
String newStr = images[position];
CharSequence cs = newStr;
Toast.makeText(UILPager.this, cs, Toast.LENGTH_SHORT).show();
And the resulting Toast shows the correct image URL. I can't figure out how to convert the URL which is in the form of "http://www.example.com/image.jpg" to an Integer so that the WallpaperManager can use it. Here's what the whole button code looks like:
wallp_BTN.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
WallpaperManager wallpManager = WallpaperManager.getInstance(getApplicationContext());
String newStr = images[position];
int newInt = 0;
try{
newInt = Integer.parseInt(newStr);
} catch(NumberFormatException nfe) {
}
CharSequence cs = newStr;
try {
wallpManager.setResource(newInt);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(UILPager.this, cs, Toast.LENGTH_SHORT).show();
}
});
Set wallpaper from URL
try {
URL url = new URL("http://developer.android.com/assets/images/dac_logo.png");
Bitmap bitmap = BitmapFactory.decodeStream(url.openStream());
wallpaperManager.setBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Enjoy =)
A method wallpaperManager.setResource() requires resource id from your application. Example: I've ImageView with id "myImage" then call the method will look like as wallpaperManager.setResource(R.id.myImage).
In your case your id not valid.
Instead of wallpManager.setResource(0) you should use the wallpManager.setResource(R.drawable.yourimage) since it's expecting a drawable and there is none in your app with id = 0.
In your code
String newStr = images[position];
int newInt = 0;
try{
newInt = Integer.parseInt(newStr);
} catch(NumberFormatException nfe) {
}
Since newStr is never a number, always a url so NumberFormatException is caught always. Hence the value of newInt is always initialized to 0. Hence the error.
I realized that I have to download the image before I can set it as wallpaper! Thanks for your help AndroidWarrior and Owl. When I get the download code worked out, I'll post it. Owl showed me how to download the wallpaper:
//--- Wallpaper button
wallp_BTN.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
vpURL = new URL(images[position]);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
WallpaperManager wallpManager = WallpaperManager.getInstance(getApplicationContext());
try {
Bitmap bitmap = BitmapFactory.decodeStream(vpURL.openStream());
wallpManager.setBitmap(bitmap);
Toast.makeText(UILPager.this, "The wallpaper has been set!", Toast.LENGTH_LONG).show();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
//--- END Wallpaper button
... and I also figured out how to download the ViewPager image as well (I need to do both in different areas of my app):
//--- Wallpaper button
wallp_BTN.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String vpURLStr = images[position];
GetVPImageTask downloadVPImageTask = new GetVPImageTask();
downloadVPImageTask.execute(new String[] { vpURLStr });
}
});
//--- END Wallpaper button
//--- Download ViewPager Image AsyncTask
private class GetVPImageTask extends AsyncTask<String, Void, Bitmap> {
ProgressDialog getVPImageDia;
#Override
protected void onPreExecute() {
super.onPreExecute();
getVPImageDia = new ProgressDialog(UILNPPager.this);
getVPImageDia.setMessage("Grabbing the image...");
getVPImageDia.setIndeterminate(false);
getVPImageDia.show();
}
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
try {
getVPImageDia.dismiss();
getVPImageDia = null;
} catch (Exception e) {
// nothing
}
Toast.makeText(UILNPPager.this, "The image be Downloaded!", Toast.LENGTH_SHORT).show();
//downloaded_iv.setImageBitmap(result);
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
//--- END Download ViewPager Image AsyncTask
protected Bitmap doInBackground(String...params) {
// TODO Auto-generated method stub
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL(params[0]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
b1=bm;
bis.close();
is.close();
} catch (IOException e)
{
Log.e("DEBUGTAG", "Remote Image Exception", e);
}
return null;
}
// TODO Auto-generated method stub
super.onPostExecute(result);
i1.setImageBitmap(b1);
Animation rotation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.rotate);
i1.startAnimation(rotation);
//System.out.println("imageview is working");
try {
System.out.println("thread going to sleep");
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i1.setImageBitmap(b1);
}
i am showing an image from the internet in an imageview through a bitmap now i am having another image this bitmap in by updating the url but i am not able to show the this image only previous image is showing,and if i run this in a loop only the last image is shwoing?any suggestions
Call this from your OnCreate or from where ever you want to initial the download of code from network
new Thread(new Runnable() {
public void run() {
Drawable drawable = createDrawableFromURL(_mDrawingURL);
Message msgURL = new Message();
msgURL.arg2 = URL_CONSTANT;
msgURL.obj = drawable;
_handler_url.sendMessage(msgURL);
}
}).start();
} catch (JSONException e) {
e.printStackTrace();
}
}
This method will be used to download the image from internet:
private Drawable createDrawableFromURL(String urlString) {
Drawable image = null;
try
{
InputStream inputStream = new URL(urlString).openStream();
image = Drawable.createFromStream(inputStream, null);
inputStream.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
image = null;
} catch (IOException e) {
e.printStackTrace();
image = null;
}
return image;
}
After downloading the image, the imageview will be update with the image.:
private Handler _handler_url = new Handler(){
public void dispatchMessage(Message msg) {
switch (msg.arg2) {
case URL_CONSTANT:
Drawable drawable = (Drawable) msg.obj;
if(drawable!=null)
_mImageView.setImageDrawable(drawable);
break;
default:
break;
}
};
};
I'm using AsyncTask to perform an operation that connects to internet, download data, and then get a picture of the internet.
The image obtained from internet too, but when it takes the server to respond the application gets a FC.
How I can do to get the data AsyncTask although it takes the server?
Then I put the code I use to download the data:
class CargaImgs extends AsyncTask<Void, Void, Bitmap> {
final ProgressDialog progressDialog = new ProgressDialog(imagen.this);
protected void onPreExecute() {
progressDialog.setTitle("");
progressDialog.setMessage("Cargando Imagen...");
progressDialog.show();
}
protected Bitmap doInBackground(Void... params) {
return urlImageToBitmap(imageUrl(StrUrl));
}
protected void onPostExecute(Bitmap imagen) {
RawBmp = imagen;
sourceBmp = RawBmp;
sourceBmp = redimensionarImagenMaximo(sourceBmp, screen_w, screen_h);
imageWidth = sourceBmp.getWidth();
imageHeight = sourceBmp.getHeight();
showBmp = Bitmap.createBitmap(sourceBmp);
main.invalidate();
primera_carga = false;
progressDialog.dismiss();
}
}
private String imageUrl(String url) {
Document doc = null;
try {
doc = Jsoup.connect(url).get();
} catch (IOException e1) {
e1.printStackTrace();
}
Elements div_exterior = doc.getElementsByClass("inner");
for (Element subelementos : div_exterior) {
Elements imgs = subelementos.getElementsByTag("img");
StrUrlImage = imgs.get(1).attr("src");
if (StrUrlImage == StrUrlImage2) {
} else {
return imgs.get(1).attr("src");
}
}
return null;
}
public Bitmap urlImageToBitmap(String urlImage) {
Bitmap mIcon1 = null;
URL url_value;
try {
url_value = new URL(urlImage);
if (url_value != null) {
mIcon1 = BitmapFactory.decodeStream(url_value.openConnection()
.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mIcon1;
}
avoid using main.invalidate() as it paints(draw whole view again--each time you execute AsyncTask)
Rather, set bitmap to the desired view or invalidate that view only.
public Bitmap urlImageToBitmap(String urlImage) {
Bitmap mIcon1 = null;
URL url_value;
try {
url_value = new URL(urlImage);
if (url_value != null) {
URLConnection conn = url_value.openConnection();
conn.setConnectTimeout(10000);
mIcon1 = BitmapFactory.decodeStream(conn.getInputStream());
}
} catch (SocketTimeoutException e) {
e.printStackTrace();
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mIcon1;
}
And regarding postExecute, if there is exception in doInBackground, it will return null, and that may lead to null pointer exception. So handle that in post execute.
I want to set ImageView bitmap from our network drive. But i getting Unable to connect to server: Unable to log in to server (PASS): 141.11.11.247 error.
Here is my download ant setBitmap code for this :
public class ResimCek implements Runnable {
int resimID = 0;
public ResimCek(int parcaID) {
// store parameter for later user
resimID = parcaID;
}
public void run() {
try {
ImageView resim = (ImageView) findViewById(resimID);
Bitmap bitmap = BitmapFactory
.decodeStream((InputStream) new URL(
"file://141.11.11.247/foto_metod/Parca/"
+ Integer.toString(resimID) + ".jpg")
.getContent());
resim.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is my last code :
public class ResimCek implements Runnable {
int resimID = 0;
public ResimCek(int parcaID) {
// store parameter for later user
resimID = parcaID;
}
public void run() {
int resID = getResources().getIdentifier(Integer.toString(resimID) , "tag", getPackageName());
ImageView resim = (ImageView) findViewById(resID);
Drawable image = ImageOperations(getBaseContext(),"http://141.11.11.206/parca/" + Integer.toString(resimID) + ".jpg" ,"I" + Integer.toString(resimID) + ".jpg");
// ******************************************************
resim.setImageDrawable(image); // I GOT THE ERROR HERE!!!
}
}
private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(new URL(url).openConnection().getInputStream(),saveFilename);
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
Thanks for your help.
may be you forgot to declare internet permission in your manifest file, check it please.
Download FtpClient
And use username and password to login.
Look at this documentation, hope it will help you.