Android Error loading image view - android

I am trying to load an image in my imageview but it does not load any image for the link.
The link has the image but I still get empty blank space.
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
String url = "http://www.learn2crack.com/wp-content/uploads/2014/04/node-cover-720x340.png";
URL urlurl = new URL(url);
bitmap = BitmapFactory.decodeStream(urlurl.openConnection().getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
}else{
Toast.makeText(activity.getApplicationContext(), "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
XML
<ImageView
android:id="#+id/list_image"
android:layout_width="50dip"
android:layout_height="50dip"
/>

As you can see in the logcat stacktrace you have a network on mainthread exception becasue you are doing a network task on the 'main' thread which is also called the gui thread. You need to use an AsyncTask for this.
private class DownloadImageTask extends AsyncTask<Object, Void, Bitmap> {
#Override
protected Bitmap doInBackground(Object... args) {
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return bmp;
}
#Override
protected void onPostExecute(Bitmap result) {
//here do stuff with your bitmap data, also here you can interact with the gui
}
}
Also I recommend using an Image downloading library to download images off the web. They make it really easy to download images and you dont have to worry a lot about the tiny details.

Related

how to load 4 images from url in android?

I want to load four images in four imageview in android
I try this code and it is run vary good
but it is load one image>>>>>>>>
How can I do to load 4 images>> I think I need to use array but how??
public void onClick(View arg0) {
// TODO Auto-generated method stub
new LoadImage().execute("https://pbs.twimg.com/profile_images/630285593268752384/iD1MkFQ0.png");
}
});
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
b1.setImageBitmap(image);
pDialog.dismiss();
}else{
pDialog.dismiss();
Toast.makeText(MainActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
}
Use one of the ready made libraries... they have async loading, resizing, loading into target to get bitmap... no need to reinvent the wheel (unless it's for study purposes). You can use Picasso, Glide, Fresco... you choose. There is plenty documentation available. Loading is done asynchronously. So you can send multiple requests with multiple urls.

Saving image from URL using Picasso without change in size (using bitmap.compress() changes size)

I am using Picasso for my image handling and use it to download images from a backend server and save to the local device. I use Target to save the image
Picasso.with(context)
.load(url)
.into(target);
Since the target code gets a bitmap, I have to use bitmap.compress() to write the image to local disk and I use JPEF format with quality of 100 assuming this will preserve the original quality.
Reading this it seems like this might not be what I want. In one case, the image on the backend was 90kb and the image that was written was 370kb. The original image can be generated using an arbitrary quality value. What is the easiest way to save the image using Picasso without the size/quality changing?
Target target = new Target() {
#Override
public void onPrepareLoad(Drawable arg0) {
}
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom arg1) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
FileOutputStream out = null;
try {
out = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Void info) {
}
}.execute();
}
#Override
public void onBitmapFailed(Drawable arg0) {
}
};
UPDATE: more elegant solution here: https://github.com/square/picasso/issues/1025#issuecomment-102661647
Solved the problem using this solution.
In my PagerAdapter's instantiateItem() method, I run an AsyncTask that will download the image, save it to a file and then call Picasso with that image file.
PagerAdapter instantiateItem():
RemoteImageToImageViewAsyncTask remoteImageToImageViewAsyncTask =
new RemoteImageToImageViewAsyncTask(imageView, url, imagePath);
remoteImageToImageViewAsyncTask.execute();
RemoteImageToImageViewAsyncTask
public class RemoteImageToImageViewAsyncTask extends AsyncTask<Void, Void, Void> {
ImageView imageView;
String url;
File output;
public RemoteImageToImageViewAsyncTask(ImageView imageView, String url, File output) {
this.imageView = imageView;
this.url = url;
this.output = output;
}
#Override
protected Void doInBackground(Void... params) {
// Downloads the image from url to output
ImageDownloader.download(url, output);
return null;
}
#Override
protected void onPostExecute(Void params) {
Picasso.with(context)
.load(output)
.into(imageView);
}
}

Need to use a variable which used in for loop

I have an AsyncTask class and I have to use the variable to show pictures in an ImageView. I use jsoup library to parse html page and the problem is that I can't take my variable "bitmap" from doInBackground to onPostExecute method. How can I resolve my problem?
Here is the code :
private class ParseHTML extends AsyncTask<Void, Void, Void>{
String resultTextFmt;
Bitmap bm;
#Override
protected void onPreExecute(){
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("WebMD");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params){
try{
Document document = Jsoup.connect(mURL).get();
Elements description2 = document.select("h2[class=et_pt_title]");
Log.v("Data3", description2.toString());
resultTextFmt = description2.toString();
Elements divs = document.select("img");
Log.w("DIVS_PICS", divs.toString());
Bitmap bitmap;
for (Element div : divs) {
Log.d("web Stuff",div.text());
// Element myImage = div;
String iurl;
iurl = div.absUrl("src");
Log.w("ABSurl:",iurl.toString());
URL url = new URL(iurl);
bitmap = BitmapFactory.decodeStream(url.openStream()); // I need to get this var
}
bm = bitmap;
} catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
imgView.setImageBitmap(bm); // and put it here to show
textView.setText(Html.fromHtml(resultTextFmt));
mProgressDialog.dismiss();
}
}
You need to declare your AsyncTask like this:
private class ParseHTML extends AsyncTask<Void, Void, Bitmap>{
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(Void... params){
Bitmap returnValue = new Bitmap();
return returnValue;
}
#Override
protected void onPostExecute(Bitmap result){
imgView.setImageBitmap(result);
}
}
As you can see, you can parametrize result value as a Bitmap for doInBackground() at the Class definition. This way, you will also receive this value in onPostExecute() callback and handle the Bitmap there after composing it.
If you want to make it more sophisticated by also handling input args, or, for example, learn how to monitor the process, you have official documentation about AsyncTask here.

How to recycle a bitmap in a AsyncTask? Android

I am writing a small android application that uses an asyncTask to display an image from a web service. The code works but it has been brought to my attention that I should recycle this bitmap.
My question is, is there a way to recycle this bitmap after I am done using it?
I attempted a solution using the onStop() and either the bitmap didn't get recycled or the image wouldn't display at all.
Here is my OnCreate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Other unrelated things
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
imageUrl = bundle.getString("imageUrl");
displayImage();
}
And here is my AsyncTask
private void displayImage() {
new AsyncTask<String, Void, Bitmap>() {
protected Bitmap doInBackground(String... params) {
try {
return loadBitmap(params[0]);
} catch (Exception e) {
Logger.e(TAG, getString(R.string.error_loading_image_bitmap));
return null;
}
}
protected Bitmap loadBitmap(String urlSpec) throws IOException {
InputStream is = new URL(urlSpec).openStream();
try {
return BitmapFactory.decodeStream(is);
} finally {
is.close();
}
}
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
ImageView invoiceItemImageView = (ImageView) findViewById(R.id.some_id_here);
invoiceItemImageView.setImageBitmap(bitmap);
}
}
}.execute(imageUrl);
}
Override method View.onDetachedFromWindow() and recycle your Bitmap there.

View Images From Url and Place in ImageView when User selects

Am develop the Frame application. For that i want to display images(frames) from url. the url has more than 50 images. For that i use gridview but it lacks some points such as,
1.It speeds very slow to load images.
2.We declare the name and size of the images at code time so that we dont add images to the url after publishing the applicaton.
I need solution for these asap. Please anyone give me suggestion.
Use below link of lazy loading listview, this will help you.
Lazy Loading ListView
Use Above link Code and Add another activity and another layout for display selected image, if u have any issue than tell me, i will put full code here.
1.It speeds very slow to load images.
It will depend on You bandwidth and device Cache.
2. We declare the name and size of the images at code time so that we dont add images to the url after publishing the application.
You can have predefine URL so at code time you can append the image name to url.and once you have URL ready using AsyncTask download images one by one \
The below snippets will help you.
DownloadHelper.java
public interface DownloadHelper
{
public void OnSucess(Bitmap bitmap);
public void OnFailure(String response);
}
MainActivity.java
public class GalleryExample extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
DownloadHelper downloadHelper = new DownloadHelper()
{
#Override
public void OnSucess(Bitmap bitmap)
{
ImageView imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
}
#Override
public void OnFailure(String response)
{
Toast.makeText(context, response, Toast.LENGTH_LONG).show();
}
};
new MyTask(this,downloadHelper).execute("image url");
}
MyTask.java
public class DownloadTask extends AsyncTask<String, Integer, Object>
{
private Context context;
private DownloadHelper downloadHelper;
private ProgressDialog dialog;
public DownloadTask(Context context,DownloadHelper downloadHelper)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
dialog = new ProgressDialog(context);
dialog.setTitle("Please Wait");
dialog.setMessage("Fetching Data!!");
dialog.setCancelable(false);
dialog.show();
super.onPreExecute();
}
#Override
protected Object doInBackground(String... params)
{
URL aURL = new URL(myRemoteImages[position]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
return bm;
}
#Override
protected void onPostExecute(Object result)
{
dialog.dismiss();
if (result != null)
{
downloadHelper.OnSucess((Bitmap)result);
}
else
{
downloadHelper.OnFailure("Error in Downloading Data!!");
}
super.onPostExecute(result);
}
}

Categories

Resources