In my app iam trying to retrieve the images of the phonebook contact images and display in a list.below is my code
public InputStream getContactPhoto(Context context, String profileId){
try{
ContentResolver cr = context.getContentResolver();
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(profileId));
return ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
}catch(Exception e){
return null;
}
}
private Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
its working but somehow it not smooth, so wanna implement getting images using asynctask
Any suggestion on how to implement using the above code
If you're using, for example, an ImageView and want to load a picture (in this example, it retrieves an image from the SDCard), you could do this:
-Create a custom class that extends ImageView
public class SDImageView extends CacheableImageView {
...
}
-Create a method called load() (or whatever you want) with your needed parameters. In my case is the path of the image:
public final void loadImage(final String tpath) {
if (tpath == null) {
return;
}
SDLoadAsyncTask.load(this, tpath);
}
-Create a class that extends AsyncTask and implement the operations you want to do in the doInBackground method
private static class SDLoadAsyncTask extends AsyncTask<Void, Void, Bitmap> {
final SDImageView view;
final String path;
private SDLoadAsyncTask(SDImageView view, String path) {
this.view = view;
this.path = path;
}
#Override
protected final Bitmap doInBackground(Void... params) {
Bitmap bmp = null;
InputStream is = null;
try {
is = new FileInputStream(mContext.getExternalFilesDir(null) + "/" + path);
bmp = BitmapFactory.decodeStream(is);
} catch (Exception e) {
Utils.logMsg("Exception for img " + path, e);
} finally {
try {
is.close();
} catch (Exception e2) {
}
}
return bmp;
#Override
protected final void onPostExecute(Bitmap result) {
view.setImageBitmap(result);
}
}
Related
I create several picture objects that each download their own image. But frequently, the same image shows up for several (or all) of the objects.
public class Picture {
private String userID;
private String fileName;
private String baseURI;
private Bitmap img;
public Picture () {
this.userID = "";
this.fileName = "";
this.baseURI = "";
}
/**
* Retrieves the UUID of the User
*
* #return - String
*/
public String getUserID() {return userID;}
public void setUserID(String _userID) {userID = _userID;}
/**
* Retrieves the Filename of the Picture
*
* #return - String
*/
public String getFileName() {return fileName;}
public void setFileName(String fileName) {
this.fileName = fileName;
//Don't retrieve a file from the server if the filename is empty or it is a placeholder
if (fileName != "" && fileName != "NoNewPicure" && fileName != "NewPicture") {
new RetrieveImageTask(getFileNameURI(), img) {
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
setPreview(result);
}
}.execute();
}
}
private URI getFileNameURI() {
return URI.create(baseURI.concat(fileName));
}
private void setBaseURI(String baseURI) {
this.baseURI = baseURI;
}
/**
* Accesors for preview image
* #return - Image
*/
#Bindable
public Bitmap getPreview() {return img;}
public void setPreview(Bitmap img) {
this.img = img;
notifyPropertyChanged(BR.preview);
}
private static class RetrieveImageTask extends AsyncTask<URI, Void, Bitmap> {
static URI uriString;
static Bitmap myBitmap;
private Exception exception;
RetrieveImageTask(URI uri, Bitmap bitmap) {
uriString = uri;
this.myBitmap = bitmap;
}
protected Bitmap doInBackground(URI... src) {
try {
Log.e("src",uriString.toString());
URL url = new URL(uriString.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap","returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception",e.getMessage());
return null;
}
}
protected void onPostExecute(Bitmap result) {
//Do nothing
}
}
}
In code the images are called from a for loop:
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Picture pic = new Picture();
pic.fromJSON(json_data);
result.add(pic);
}
It appears as though when the Async task returns, several (or all) of the handlers fire. Any ideas on how to fix this? I've tried adding in this:
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
URI thisURI = getFileNameURI();
if (uriString.equals(thisURI)) {
setPreview(result);
}
}
But then only one Picture object actually gets an image.
The answer was quite simple after hearing Another brick in the wall. You can't have any pudding if you don't eat your meat! I can't have my bitmap if the file hasn't downloaded. But I CAN put my bowl where the pudding is going to be so that after I eat my meat, I can eat my pudding. I changed my AsynTask like such:
private class RetrieveImageTask extends AsyncTask<URI, Void, Boolean> {
public URI uriString;
public Picture pic;
RetrieveImageTask(URI uri) {
uriString = uri;
}
protected Boolean doInBackground(URI... src) {
try {
Log.e("src",uriString.toString());
URL url = new URL(uriString.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap","returned");
pic.setPreview(bitmap);
return true;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception",e.getMessage());
return null;
}
}
protected void onPostExecute() {
//Do nothing
}
}
Note the public variables in the class wrapper. Now when I call my task (code changed from above):
RetrieveImageTask task = new RetrieveImageTask(getFileNameURI());
task.pic = this;
task.execute();
my bowl will be where the pudding is going to be. IE. I put the calling object as a variable in the private AsyncTask class which populates what I need when it is finished running. :D My bowl of pudding is full after I eat my meat!!!!
I want to fill a listview with text and images.
I receive this information by my mysql database, in JSON format.
I have a field called "FOTO" and I store into this the path to the photo like: "http://....../1.png".
I get and android.os.NetworkOnMainThreadException using this code, but I don't know how to do different.
I parse the JSON and pass the values to the listadapter. I need to pass also the icon so the bitmap value, but I need to download it from the server.
public class DisplayListView extends AppCompatActivity {
final static String TAG = "sb.dl";
String json_string;
JSONObject jsonObject;
JSONArray jsonArray;
TeamAdapter teamAdapter;
ListView listView;
Bitmap icon = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_listview_layout);
teamAdapter = new TeamAdapter(this, R.layout.row_layout);
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(teamAdapter);
json_string = getIntent().getExtras().getString("json_data");
Log.d(TAG, "json_string " + json_string);
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("risposta");
int count = 0;
String nome, num, data;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
nome = JO.getString("NOME");
num = JO.getString("NUMERO");
data = JO.getString("DATA_NASCITA");
String url = JO.getString("FOTO");
icon = LoadImageFromWebOperations(url);
Team team = new Team(nome, num, data, icon);
teamAdapter.add(team);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("Simone", e.toString());
Log.d("Simone", e.getMessage());
}
}
public static Bitmap LoadImageFromWebOperations() {
try {
URL url = new URL("url");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return bmp;
} catch (Exception e) {
Log.d(TAG, "bitmap error: " + e.toString());
Log.d(TAG, "bitmap error: " + e.getMessage());
return null;
}
}
}
I had the same problem.
I solved with an AsyncTask that download the bitmaps.
I used this code:
class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = null;
imageView.setImageDrawable(placeholder);
}
}
}
}
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
final int responseCode = urlConnection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Errore durante il download da " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
}
you call it by:
new ImageDownloaderTask(holder.imageView).execute(urlPhoto);
Hope this help :)
try using picasso to load in your image.
http://square.github.io/picasso/
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
this will load the image into your imageview asynchronously.
get the library using the gradle import
compile 'com.squareup.picasso:picasso:2.5.2'
i am parsing a json string from which i get the url of image. then i pass that url to a method to get the image and display it in an imageview but the image does not loaded and throws an exception of java.net.MalformedURLException. when i try to pass the image url directly to the method then it gets loaded. so i dont know where is the error. Any help will be appreciated. thanks in advance. my code is below
public class CompanyDetailActivity extends Activity {
ImageView coverimage;
ImageView profileimage;
TextView fullname;
TextView tagline;
TextView industry;
TextView teamsize;
TextView about;
TextView year;
TextView location;
String Coverimage;
String Profimage;
String Fullname;
String Tagline;
String Industry;
String Teamsize;
String About;
String Year;
String Location;
// Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.companydetails);
coverimage = (ImageView) findViewById(R.id.CoverImage);
profileimage = (ImageView) findViewById(R.id.ProfileImage);
fullname = (TextView) findViewById(R.id.FullName);
tagline = (TextView) findViewById(R.id.TagLine);
industry = (TextView) findViewById(R.id.IndustryName);
teamsize = (TextView) findViewById(R.id.TeamSize);
about = (TextView) findViewById(R.id.CompanyAbout);
year = (TextView) findViewById(R.id.FoundYear);
location = (TextView) findViewById(R.id.Location);
new DetailsAsynTask()
.execute("http://www.mygmn.com/joblink/wp-admin/admin-ajax.php?action=joblink_searchcompanies&company_id=1180");
GetXMLTask task = new GetXMLTask();
task.execute(Coverimage);
}
public class DetailsAsynTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... arg0) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(arg0[0]);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
// to get response
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jObj = new JSONObject(data);
JSONObject MainObject = jObj.getJSONObject("data");
CompanyDetailsModel company = new CompanyDetailsModel();
Coverimage = company.setCoverImage(MainObject
.getString("cove_img"));
Profimage = company.setCompanyProfPicture(MainObject
.getString("company_profile_picture"));
Fullname = company.setCompanyFullName(MainObject
.getString("company_full_name"));
Tagline = company.setComapnyTagLine(MainObject
.getString("company_tagline"));
Industry = company.setCompanyInustry(MainObject
.getString("company_industry"));
Teamsize = company.setCompanyTeamSize(MainObject
.getString("company_teamsize"));
About = company.setCompanyAbout(MainObject
.getString("company_about"));
Year = company.setCompanyFoundYear(MainObject
.getString("company_foundyear"));
Location = company.setCompanyLocation(MainObject
.getString("company location"));
return true;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result == false) {
} else {
fullname.setText(Fullname);
tagline.setText(Tagline);
industry.setText(Industry);
teamsize.setText(Teamsize);
about.setText(About);
year.setText(Year);
location.setText(Location);
}
}
}
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
#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) {
coverimage.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;
}
}
}
java.net.MalformedURLException can come due to security reason .you have to add http:// or https:// with your url images.
You are running two asynctasks inside onCreate() method .As these are asynchronous your GetXMLTask was executed with String CoverImage as null .
So , moving this code :
GetXMLTask task = new GetXMLTask();
task.execute(Coverimage);
to the onPostExecute() Method of your Details asynctask will solve the problem .
ok, use this code
public class ImageLoading {
public enum BitmapManager {
INSTANCE;
private final Map<String, SoftReference<Bitmap>> cache;
private final ExecutorService pool;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
private Bitmap placeholder;
BitmapManager() {
cache = new HashMap<String, SoftReference<Bitmap>>();
pool = Executors.newFixedThreadPool(5);
}
public void setPlaceholder(Bitmap bmp) {
placeholder = bmp;
}
public Bitmap getBitmapFromCache(String url) {
if (cache.containsKey(url)) {
return cache.get(url).get();
}
return null;
}
public void queueJob(final String url, final ImageView imageView,
final int width, final int height) {
/* Create handler in UI thread. */
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
String tag = imageViews.get(imageView);
if (tag != null && tag.equals(url)) {
if (msg.obj != null) {
imageView.setImageBitmap((Bitmap) msg.obj);
} else {
imageView.setImageBitmap(placeholder);
Log.d(null, "fail " + url);
}
}
}
};
pool.submit(new Runnable() {
#Override
public void run() {
final Bitmap bmp = downloadBitmap(url, width, height);
Message message = Message.obtain();
message.obj = bmp;
Log.d(null, "Item downloaded: " + url);
handler.sendMessage(message);
}
});
}
public void loadBitmap(final String url, final ImageView imageView,
final int width, final int height) {
imageViews.put(imageView, url);
Bitmap bitmap = getBitmapFromCache(url);
// check in UI thread, so no concurrency issues
if (bitmap != null) {
Log.d(null, "Item loaded from cache: " + url);
imageView.setImageBitmap(bitmap);
} else {
imageView.setImageBitmap(placeholder);
queueJob(url, imageView, width, height);
}
}
private Bitmap downloadBitmap(String url, int width, int height) {
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
url).getContent());
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
cache.put(url, new SoftReference<Bitmap>(bitmap));
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Directly use this code,and where you are using downloading code ,use this code
ImageLoading.BitmapManager.INSTANCE.loadBitmap("http://"+image, holder.img, 150, 180);
Your URL is okay from your server response. Instead of loading the image manually try Picasso Library
with this library, you will just need to do-
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
I am writing an app with custom camera facility. In my custom camera after capturing i am drawing the captured image to canvas and providing free hand drawing over that captured imgae and then save option. At the time of saving i am save it as two images which means the one which contains free hand drawing and another one which contains no drawing. Saving is done by writing output stream and compressing bitmaps. The saving and compression of bitmaps done in two separate async tasks. The issue is that i can capture image up to 16 or 17 times but after that capturing and editing then pressing save button i am getting the exception "vm aborting Fatal signal 11 (SIGSEGV) at 0xdeadd00d (code=1)" .
Async Task one
public class SaveOriginalImage extends AsyncTask<String, Void, String> {
OutputStream dataOutputStream;
Bitmap bitMapOriginalImage;
String fileName;
Activity activityContext;
ProgressDialog progressDialog;
String sbCaption;
String fileType;
public SaveOriginalImage(Bitmap bitMap, String filePath,
Activity currentActivity, String fileCaption) {
this.bitMapOriginalImage = bitMap;
this.fileName = filePath;
this.activityContext = currentActivity;
this.sbCaption = fileCaption;
}
#Override
protected String doInBackground(String... params) {
try {
dataOutputStream = new FileOutputStream(fileName);
bitMapOriginalImage
.compress(CompressFormat.PNG, 100, dataOutputStream);
Collection.lastImageFilePath = fileName;
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
if (bitMapOriginalImage != null) {
bitMapOriginalImage.recycle();
bitMapOriginalImage = null;
}
}
}
Async Task 2
public class SaveFreeHandImage extends AsyncTask<String, Void, String> {
OutputStream dataOutputStream;
Bitmap bitMapToSave;
String fileName;
Activity activityContext;
ProgressDialog progressDialog;
String sbCaption;
String className;
String fileType;
public SaveFreeHandImage(Bitmap bitMap, String filePath,
Activity currentActivity, String fileCaption, String className) {
this.bitMapToSave = bitMap;
this.fileName = filePath;
this.activityContext = currentActivity;
this.sbCaption = fileCaption;
this.className = className;
}
#Override
protected String doInBackground(String... params) {
try {
dataOutputStream = new FileOutputStream(fileName);
bitMapToSave.compress(CompressFormat.PNG, 100, dataOutputStream);
Collection.lastImageFilePath = fileName;
try {
dataOutputStream.flush();
dataOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// super.onPostExecute(result);
progressDialog.dismiss();
HomeFinal.showCustomToast("Drawing saved to SD card ", 0, 0,
activityContext);
Collection.isNewImageAdded = false;
DrawingView.colorD = Color.parseColor("#000000");
if (DrawingView.paths != null) {
if (DrawingView.paths.size() >= 1) {
DrawingView.paths.clear();
}
}
if (bitMapToSave != null) {
if (!bitMapToSave.isRecycled()) {
bitMapToSave.recycle();
bitMapToSave = null;
}
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(activityContext, "", "Saving..");
}
}
I am testing on lenovo a-300h 7 inch tablet . Please give me solution. Thanks in advance.
i solved myself. It is because of excess use of bitmaps, after handling bitmaps it worked perfectly.
i want to display images from mysql server(testing in localhost) using imageurl,i have images in a filder on my server,in an android client app as gridview along with text.how do i use imageurl in my code?
mymainmenu.java
public class MainMenu extends Activity {
GridView gridView;
static final String[] MOBILE_OS = new String[] {
"Android", "iOS","Windows", "Blackberry" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu_list);
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(new ImageAdapter(this, MOBILE_OS));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(
getApplicationContext(),
((TextView) v.findViewById(R.id.grid_item_label))
.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
my imageadapter.java:
public class ImageAdapter extends BaseAdapter {
private Context context;
private final String[] mobileValues;
public ImageAdapter(Context context, String[] mobileValues) {
this.context = context;
this.mobileValues = mobileValues;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
// get layout from list.xml
gridView = inflater.inflate(R.layout.list, null);
// set value into textview
TextView textView = (TextView) gridView
.findViewById(R.id.grid_item_label);
textView.setText(mobileValues[position]);
// set image based on selected text
ImageView imageView = (ImageView) gridView
.findViewById(R.id.grid_item_image);
String mobile = mobileValues[position];
if (mobile.equals("Windows")) {
imageView.setImageResource(R.drawable.imggrid);
} else if (mobile.equals("iOS")) {
imageView.setImageResource(R.drawable.imggrid);
} else if (mobile.equals("Blackberry")) {
imageView.setImageResource(R.drawable.imggrid);
} else {
imageView.setImageResource(R.drawable.imggrid);
}
} else {
gridView = (View) convertView;
}
return gridView;
}
#Override
public int getCount() {
return mobileValues.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
I dnt know how to use the following in my code:
try {
URL url = new URL(imageFileURL);
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
img.setImageBitmap(bitmap);
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Put the image downloading code in a AsyncTask. Here is the explanation.
Execute one instance of asynctask in your getView method, i.e to fetch one image everytime.
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView mImageView;
public void setImageView(ImageView img) {
mImageView = img;
}
protected Bitmap doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}
Call task.setImageView(yourImageViewinGrid) before executing your AsyncTask to let it know where to set the image after downloading.
To get the image, you have to do something like :
URL new_url = new URL("your url");
Bitmap image_bitmap = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream()); ImageView image_view = new ImageView(this);
image_view.setImageBitmap(image_bitmap);
Anyway, it's better to download the image as background task. What I actually do is to create a custom view with one private inner class that extend AsyncTask to download the image for you.
I dnt know how to use the following in my code:
that code will download the image for you, you can place in separate thread either AsyncTask or Thread and set the downloaded image in the imageview... simple as that. There are so many example on the web you can google it out
EIDTED
code to download the image
public class AsyncFetchImage extends AsyncTask<String, Void, Bitmap>{
private WeakReference<ImageView> imageReference;
// private WeakReference<Dialog> dialogReferance;
public AsyncFetchImage(ImageView imageview) {
imageReference = new WeakReference<ImageView>(imageview);
// dialogReferance = new WeakReference<Dialog>(dialog);
}
#Override
protected Bitmap doInBackground(String... s) {
return downloadImage(s[0]);
}
private Bitmap downloadImage(String url) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("Nixit");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK){
Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if(entity != null){
InputStream is = null;
try{
is = entity.getContent();
final Bitmap bit = BitmapFactory.decodeStream(is);
return bit;
}finally{
if(is != null)
is.close();
entity.consumeContent();
}
}
} catch (IOException e) {
e.printStackTrace();
return null;
} finally{
if(client != null){
client.close();
}
}
Log.i("Image Fetch","Image Fetch Complete");
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
if(isCancelled()){
result = null;
}
if(imageReference != null){
ImageView imageView = imageReference.get();
// Dialog di = dialogReferance.get();
if (imageView != null) {
imageView.setImageBitmap(result);
// di.show();
}
}
}
}
How to use:-
imageView = (ImageView)dialog.findViewById(R.id.imageView1);
AsyncFetchImage fetchImage = new AsyncFetchImage(imageView);
fetchImage.execute(url);
You can use this in getview method of adapter
Hope that help