android:display image in listview - android

I am trying to display an image in listview from url using JSON parsing. the image url displays correctly in log. when i am trying to download image and display in list getting NullPointerException in bmImage.setImageBitmap(result);
i am using following code can anyone tell me the solution..
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
Bitmap bt_img = null;
try {
FileInputStream in = new FileInputStream(urls[0]);
InputStream in = new java.net.URL(urls[0]).openStream();
bt_img = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return bt_img;
}
protected void onPostExecute(Bitmap result) {
try {
bmImage.setImageBitmap(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}

If you are getting a nullPointerException on the bmImage variable, it means it has not been initialized. As in the code you provide you are not getting its reference, you have to be passing it to the AsyncTask.
What is the code where you pass the bmImage reference, invoking your AsyncTask? The problem seems to be in that code, not in the AsyncTask itself.

1) best way is use Lazy Loding
and
2) second way is try this code,
try {
URL imageURL = new URL(imgUrl);
qrBitmap = BitmapFactory.decodeStream(imageURL.openStream());
image.setImageBitmap(qrBitmap);
} catch (Exception e) {
Log.d("QRDisplay", e.getMessage());
}

You have to use the Universal Image Loader for getting the images from the server.
this link help to u
https://github.com/nostra13/Android-Universal-Image-Loader

Related

Display Images in Recyclerview without using any library [duplicate]

I'm trying to download an image using a URL and a button in my app. When I'm running it on my phone, I,m not able to download the image. Can anyone please point out the problem with this. Thanks for the help in advance :)
This is my code.
public class MainActivity extends AppCompatActivity {
ImageView download;
public void downloadImage(View view){
DownloadImage image = new DownloadImage();
Bitmap result;
try {
result = image.execute("https://en.wikipedia.org/wiki/File:Bart_Simpson_200px.png").get();
download.setImageBitmap(result);
}
catch(Exception e)
{
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
download = (ImageView) findViewById(R.id.imageView);
}
public class DownloadImage extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... urls) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.connect();
InputStream in = urlConnection.getInputStream();
Bitmap Image = BitmapFactory.decodeStream(in);
in.close();
return Image;
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
you can download image from url in two ways
1.you can user Glide library to load image from url look the below code it can help you in simple way
compile this library
implementation 'com.github.bumptech.glide:glide:4.6.1'
than load image like this
Glide.with(MainActivity.this)
.load(url)
.apply(new RequestOptions().placeholder(R.drawable.booked_circle).error(R.drawable.booked_circle))
.into(imageview);
2 .try this if you dont want to use third party library
new DownloadImage(imamgeview).execute(url);
create a Async Task
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (ImageView ) bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
i hope that it will work in your case
You did not call the function
downloadImage(view);
In the oncreate (after the findviewbyid line)
Also check if the internet permision is in the Android Manifest file :
<uses-permission android:name="android.permission.INTERNET" />
Having said that you should use a library like Glide\Picasso\Ion etc... much better than asynctask for this purpuse
https://github.com/bumptech/glide - Glide
https://github.com/koush/ion - Ion
http://square.github.io/picasso/ - picasso
Hope it helped.

ImageView emptied on subsequent activity launches

I'm using this AsyncTask to load an image from a URL and populate an ImageView with that image:
new DownloadImageTask((ImageView) findViewById(R.id.headerIV)).execute(imageURL);
and
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
I noticed that whenever I background my app and relaunch the activity, the ImageViews are emptied. Various checks on the ImageViews show that they are null in onCreate(), and so if I want to show images again, I have to call the AsyncTask again, which eventually leads to out-of-memory exceptions. So, I'm wondering: Does the activity recycle/empty my ImageViews for some reasons on onPause() based on that code block I'm using?
Try this !!!!
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
Bitmap mIcon11;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
try {
mIcon11 = BitmapFactory.decodeStream((InputStream) new URL(urls[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
if (result != null) {
bmImage.setImageBitmap(result);
} else {
Toast.makeText(TestActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
Whenever your app comes to foreground the onResume() is called and the views are generated again, so that can be the reason for the null values.
You can use onResume() for the same. (For more info check out Activity life cycle)
Also as suggested by others, you can use Picasso or Universal Image Loader or other libraries for ease.
To start with you can refer below links:
https://www.simplifiedcoding.net/picasso-android-tutorial-picasso-image-loader-library/
http://javatechig.com/android/how-to-use-picasso-library-in-android
http://javatechig.com/android/universal-image-loader-library-in-android

Setting image from url

I have an image view in my Android app, where I have to set a simple image from url. I tried the below code, but it doesn't set the image from url.
try {
URL url = new URL("https://drive.google.com/...");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream stream = connection.getInputStream();
Bitmap teamBmpImage = BitmapFactory.decodeStream(stream);
teamImgView.setImageBitmap(teamBmpImage);
}
catch (Exception e) {
}
Could someone guide me to achieve this please?
UPDATED CODE: Which gives Nullpointer exception
public class AboutActivity extends ActionBarActivity {
ImageView teamImgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
teamImgView = (ImageView) this.findViewById(R.id.teamImageView);
new DownloadImageTask(teamImgView).execute("http://docs.oracle.com/javase/tutorial/2d/images/examples/strawberry.jpg");
}
class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//pd.show();
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
//pd.dismiss();
bmImage.setImageBitmap(result);
}
}
}
I guess you are executing your code on the MainThread, which leads to a NetworkOnMainThreadException in android. Try to execute your code asynchronous like in the example below
new AsyncTask<String, Integer, Bitmap>() {
#Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL(params[0]);
return BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bm) {
ImageView teamImgView = (ImageView) findViewById(R.id.teamImageView);
teamImgView.setImageBitmap(bm);
}
}.execute("https://drive.google.com/uc?....");
You can use Picasso library and here is a detailed tutorial on how to do this.
This is very simple example usage
Picasso.with(activityContext)
.load("https://drive.google.com/uc?....")
.placeholder(R.drawable.image_name)
.into(imageView);
As bojan says you can use Picasso library wich handles many common pitfalls of image loading on Android.
Picasso.with(context).load("http://myurl/myImage.png").into(imageView);
Picasso
Anyway, check out this threat too :)
How to load an ImageView by URL in Android?
Try following this link:
http://www.tutorialsbuzz.com/2014/11/android-volley-url-imageview.html
This will help you to load your image using Volley library which will do all the networking stuff on networking thread and set your image on main UI thread. It has also the LRUCache part which you can skip if you want.

Change a bitmap image in listView after listView was created

I have an AsyncTask that gets favicon base on a URL.
I am creating a listView, that has a favicon and a URL. at the moment even though I have the AsyncTask my UI waits for the asyncTask to finish before it shows the next activity.
I would like my activity to start with a default image that is stored in drawable, and that the AsyncTask will replace the images after it got each favicon.
Any ideas how to do it?
my AsyncTask:
private class DownloadImageTask extends AsyncTask<URL, Void, Bitmap> {
final AccountListModel model = new AccountListModel(daoSession);
protected Bitmap doInBackground(URL... urls) {
URL urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
mIcon11 = model.getBitmapFromURL(urldisplay);
//try to get image
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
faviconBitmap=result;
}}
the way I am currently creating my list view
for (Site site : model.getSites()) {
try {
String url = site.getDomain()
faviconBitmap= new DownloadImageTask().execute(new URL("http", "www."+ url.trim(),"/favicon.ico")).get();
if (faviconBitmap != null) {
Bitmap scaled = Bitmap.createScaledBitmap(faviconBitmap,32, 32, true);
accountsAndUsersList.add(newAccountListScreen(scaled,site.getName());
}
}
else {
Bitmap icon = BitmapFactory.decodeResource(getResources(),R.drawable.favicon);
Bitmap scaled = Bitmap.createScaledBitmap(icon, 32, 32, true);
accountsAndUsersList.add(new AccountListScreen(scaled,site.getName());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sitesToSortArray = new AccountListScreen[accountsAndUsersList
.size()];
accountsAndUsersList.toArray(sitesToSortArray);
AccountListAdapter adapter = new AccountListAdapter(this,
R.layout.account_list_row, sitesToSortArray);
listViewAccountList = (ListView) findViewById(R.id.activityAccountList);
listViewAccountList.setAdapter(adapter);
please let me know if you would like to see my adapter as well.
Thank you!

What to return for an Async Task

I have two functions that access the internet on the APP start. I've tried to use this post as a reference in order to have the popup dialog while my content loads.
The two functions I would use are:
getImage(); //Gets an image from the internet for an imageview
getJson(); //Where the app goes an parses a JSON object for a lazy load listview.
The problem I'm encountering with the post I referenced above is that I try to make the task return null but it causes the app to crash when I do this. So I have this:
private class DownloadTask extends AsyncTask<String, Void, Object> {
protected Object doInBackground(String... args) {
Log.i("MyApp", "Background thread starting");
try {
ImageView i = (ImageView) findViewById(R.id.currdoodlepic);
Bitmap bitmap = BitmapFactory
.decodeStream((InputStream) new URL(imageURL)
.getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
getJson("all");
return "replace this with your data object";
}
I'm not sure what to return.
The type return of the method doInBackground depend of what you need at the post execution :
void postExecute(Object result); // AsyncTask method
Parameter "result" is the return value of doInBackground. So if you need nothing you return NULL.
I found the exact answer here. Here is the code:
ImageView mChart = (ImageView) findViewById(R.id.imageview);
String URL = "http://www...anything ...";
mChart.setTag(URL);
new DownloadImageTask.execute(mChart);
The Task class:
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
...
}

Categories

Resources