android using async http connection to get image bitmap - android

I am trying to use async requests to fetch the images from urls, to prevent the url from hanging. This is the piece of code i am using for this
private void setImg(final ImageView im, String url){
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new AsyncHttpResponseHandler(){
public void onSuccess(String response){
try{
byte[] imageAsBytes = response.getBytes();
im.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));
im.refreshDrawableState();
} catch(Throwable e){
e.printStackTrace();
}
}
});
}
This is always showing this warning in logcat
12-29 01:55:33.043: D/skia(14414): --- SkImageDecoder::Factory returned null
I cannot find a proper reason for this. Any help?

Now that a binary response handler has been added to AsyncHttp you can simply use androids BitmapFactory.decodeByeArray function:
AsyncHttpClient client = new AsyncHttpClient();
client.get(image_url, null, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(byte[] fileData) {
Bitmap image = BitmapFactory.decodeByteArray(fileData, 0, fileData.length);
//Do whatever you want with the image variable
}
});

I've been using lately the following library: UrlImageViewHelper. It uses an AsyncTask to download the image. Your code would be something like this:
private void setImg(final ImageView im, String url){
UrlImageViewHelper.setUrlDrawable(im, url) ;
}
Very simple now, am I right?

If anyone is still working on this, here's how I am doing it
public static void setImg(final ImageView im, final String url){
AsyncTask<Void, Void, Bitmap> t = new AsyncTask<Void, Void, Bitmap>(){
protected Bitmap doInBackground(Void... p) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.setUseCaches(true);
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bm;
}
protected void onPostExecute(Bitmap bm){
Bitmap output = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bm.getWidth(), bm.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = 5;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bm, rect, rect, paint);
im.setImageBitmap(output);
}
};
t.execute();
}

[UPDATE]
Image (and any binary data) response handling has been added to loopj's android-async-http library. Use the BinaryHttpResponseHandler
[old post]
loopj's AsyncHttpClient does not yet support handling of byte[] responses. There's a fork that does, but it's a mess. So the answer is one of these:
A1) You don't.
A2) You use the fork provided via link via this link: https://github.com/loopj/android-async-http/issues/8
A3) You fork AsyncHttpClient, add byte[] handling (without tearing out String response handling, jesus!), and commit it back to the project. By doing this you will also receive open-source karma credits.

Android using async http connection to get image and text and show in a listView
public class MainActivity extends Activity {
ListView list;
public String IPadd = "http://api.gifts.com/v2/search/product.json?category=Nur&api_key=fd2ut5evb9jgzerjkeph54pz";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=(ListView) findViewById(R.id.listView1);
new AsyTask().execute(IPadd);
}
private class AsyTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url[0]);
// HttpPost httpPost=new HttpPost(url[0]);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet);
text = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject jObject = new JSONObject(result);
JSONArray jarray = jObject.getJSONArray("products");
for (int i = 0; i < jarray.length(); i++) {
ProductInfo p=new ProductInfo();
JSONObject jObj = jarray.getJSONObject(i);
p.setTitle(jObj.getString("title"));
p.setId(jObj.getString("price"));
p.setImage(jObj.getString("largeProductImageUrl"));
ProductInfo.arrayList.add(p);
}
ArrAdapter adapter=new ArrAdapter(getApplicationContext(),ProductInfo.arrayList);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
public class ArrAdapter extends BaseAdapter{
TextView id,title;
ImageView img;
Context context;
static ArrayList<ProductInfo> listitem=new ArrayList<ProductInfo>();
public ArrAdapter(Context applicationContext,ArrayList<ProductInfo> arrayList) {
this.context=applicationContext;
listitem=arrayList;
}
#Override
public int getCount() {
return listitem.size();
}
#Override
public Object getItem(int position) {
return listitem.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ProductInfo p=listitem.get(position);
if(convertView==null)
{
LayoutInflater inflater=(LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.custom, null);
}
id=(TextView) convertView.findViewById(R.id.textView1);
id.setText(p.getId());
title=(TextView) convertView.findViewById(R.id.textView2);
title.setText(p.getTitle());
img=(ImageView) convertView.findViewById(R.id.imageView1);
ImageLoader imageloader=new ImageLoader(img);
imageloader.execute(p.getImage());
return convertView;
}
}
public class ProductInfo {
String ID,title,image;
static ArrayList<ProductInfo> arrayList=new ArrayList<ProductInfo>();
public void setId(String id)
{
this.ID=id;
}
public String getId()
{
return ID;
}
public void setTitle(String tit)
{
this.title=tit;
}
public String getTitle()
{
return title;
}
public void setImage(String img)
{
this.image=img;
}
public String getImage()
{
return image;
}
}
class ImageLoader extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public ImageLoader(ImageView bmImage) {
this.bmImage = bmImage;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
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) {
}
return mIcon11;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
bmImage.setImageBitmap(result);
}
}

Related

download BLOB in AsyncTask

I have a method where I would download an image from a folder based on the link passed into the AsyncMethod
I have since made some changes and now the image resides on the database. I am having a little problem editing my downloadAsyn Task as it no longer receives a link but instead a long string of characters (BLOB from the database).
I have pasted my code below, and is trying to find assistance in assigning cImg1 the bitmap to display my image.
Thank you
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];// this parameter once had url of image
//but now it has the image bitmap.
Bitmap cImg1= null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
// cImg1= BitmapFactory.decodeStream(in);
cImg1=urldisplay;//Assign strings to BitMap?
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return cImg1;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
Below code will be worked fine.
public class DownloadImageTask extends AsyncTask<String, Integer, Bitmap> {
Context _context;
ImageView _imageView;
private OnResponseListener _responder;
private String _errorMessage;
public DownloadImageTask(ImageView bmImage, OnResponseListener responseListener) {
this._imageView = bmImage;
_context = bmImage.getContext();
_responder = responseListener;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... urls) {
int count;
String urlDisplay = urls[0];
Bitmap bitmap = null;
try {
InputStream in = new java.net.URL(urlDisplay).openStream();
BitmapFactory.Options options = new BitmapFactory.Options(); options.inPurgeable = true; options.inInputShareable = true;
bitmap = BitmapFactory.decodeStream(in, null, options);
URLConnection urlConnection = new java.net.URL(urlDisplay).openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
int lengthOfFile = urlConnection.getContentLength();
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
int progress = (int) total * 100 / lengthOfFile;
publishProgress(progress);
}
} catch (Exception e) {
_errorMessage = e.getMessage();
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
protected void onPostExecute(Bitmap result) {
if (result != null){
_responder.onSuccess(result);
}
else
_responder.onFailure(_errorMessage);
}
public interface OnResponseListener {
void onSuccess(Bitmap result);
void onFailure(String message);
}
}

Image does not loaded and throwingjava.net.MalformedURLException

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);

Parsing the same tags name for child nodes using DOM Parser Android

I'm currently building an Application which reads an xml file from the following website: http://wx.toronto.ca/festevents.nsf/tpaview?readviewentries and then displays it in a listview with an image and in a single list view. The Problem i'm facing is that once parsed using the following code :
NodeList nodeList = document.getElementsByTagName("viewentry");
it only return the first child element from the xml file. The following is a partial copy of the xml file to get an idea:
<viewentries timestamp="20141204T225826,77Z" toplevelentries="486">
<viewentry position="1" unid="76D2D8314E365A2A85257DA4004B11B7" noteid="56C06" siblings="486">
<entrydata columnnumber="0" name="EventName">
<text>Learn To Skate Lessons</text>
</entrydata>
<entrydata columnnumber="1" name="Area">
<textlist>
<text>Central East</text>
<text>Southeast</text>
</textlist>
</entrydata>
<entrydata columnnumber="2" name="CategoryList">
<textlist>
<text>Family/Children</text>
<text>Sports</text>
</textlist>
</entrydata>
<entrydata columnnumber="3" name="PresentedByOrgName">
<text/>
</entrydata>
<entrydata columnnumber="4" name="Image">
<text>
http://wx.toronto.ca/festevents.nsf/all/76D2D8314E365A2A85257DA4004B11B7/$File/learntoskate.jpg
</text>
</entrydata>
</viewentry>
The following is my Android Code...I have tested my singleListview and my imageloader than they both work.
MainActivity
public class TorontourismActivity extends Activity{
ListView listView;
ListViewAdapter adapter;
ProgressDialog progressDialog;
ArrayList<HashMap<String,String>> arrayList;
static String Event = "text";
static String Area = "text";
static String Category = "textlist";
static String Presented = "entrydata";
static String Image = "entrydata columnnumber=4 name=Image";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main); //View from the layout file in res folder
new DownloadXMLFile().execute();
}
private class DownloadXMLFile extends AsyncTask<Void,Void,Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(TorontourismActivity.this);
progressDialog.setTitle("Torontourism the know it all for Toronto Events");
progressDialog.setMessage("I'm loading....Give me a minute.");
progressDialog.setIndeterminate(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
arrayList = new ArrayList<HashMap<String, String>>();
TorontourismParser parser = new TorontourismParser();
String xml = parser.getXMLfromURL("http://wx.toronto.ca/festevents.nsf/tpaview?readviewentries");
Document document = parser.getElements(xml);
try
{
NodeList nodeList = document.getElementsByTagName("viewentry");
for(int i =0; i < nodeList.getLength(); i++)
{
Element element = (Element) nodeList.item(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(Event, parser.getValue(element, Event));
map.put(Area, parser.getValue(element, Area));
// map.put(Category, parser.getValue(element, Category));
map.put(Image, parser.getValue(element, Image));
/*map.put(ShowDate, parser.getValue(element, ShowDate));
map.put(BeginTime, parser.getValue(element, BeginTime));
map.put(EndShowDate, parser.getValue(element, EndShowDate));*/
System.out.println(Event);
arrayList.add(map);
}
} catch (Exception e)
{
Log.i("Error in Torontourism Activity", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void arguments)
{
listView = (ListView) findViewById(R.id.listView);
adapter = new ListViewAdapter(TorontourismActivity.this, arrayList);
listView.setAdapter(adapter);
progressDialog.dismiss();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_torontourism, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
DOM Parser
public class TorontourismParser {
static final String FesEventURL = "http://wx.toronto.ca/festevents.nsf/tpaview?readviewentries";
//constructor
public TorontourismParser()
{
}
//open a HTTP Connection
public String getXMLfromURL(String urlString)
{
String xmlfile = null;
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urlString);
HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xmlfile = EntityUtils.toString(httpEntity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return xmlfile;
}
public Document getElements(String xml)
{
Document document = null;
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputSource inputSource = new InputSource();
inputSource.setCharacterStream(new StringReader(xml));
document = documentBuilder.parse(inputSource);
} catch (Exception e) {
Log.e("Error in Parser file", e.getMessage());
e.printStackTrace();
}
return document;
}
public final String getElements(Node node)
{
Node element;
StringBuilder value = new StringBuilder();
if(node != null)
{
if(node.hasChildNodes())
{
for(element = node.getFirstChild(); element != null;
element = element.getNextSibling())
{
if (element.getNodeType() == Node.TEXT_NODE)
{
value.append(element.getNodeValue());
}
}
}
}
return value.toString();
}
public String getValue(Element element, String string) {
NodeList nodeList = element.getElementsByTagName(string);
return this.getElements(nodeList.item(0));
}
}
ListViewAdapter
public class ListViewAdapter extends BaseAdapter {
Context context;
LayoutInflater layoutInflater;
ArrayList<HashMap<String,String>> xmldata;
ImageLoader imageLoader;
HashMap<String,String> hashMap = new HashMap<String, String>();
public ListViewAdapter(Context context,ArrayList<HashMap<String,String>> arrayList)
{
this.context = context;
xmldata = arrayList;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return xmldata.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
TextView Event;
TextView Area;
TextView Category;
TextView Presented;
ImageView Image;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.listview_item, parent, false);
hashMap = xmldata.get(position);
Event = (TextView) view.findViewById(R.id.Event);
Area = (TextView) view.findViewById(R.id.Area);
//Category = (TextView) view.findViewById(R.id.Category);
//Presented = (TextView) view.findViewById(R.id.Presented);
Image = (ImageView) view.findViewById(R.id.Image);
Event.setText(hashMap.get(TorontourismActivity.Event));
Area.setText(hashMap.get(TorontourismActivity.Area));
//Category.setText(hashMap.get(TorontourismActivity.Category));
// Presented.setText(hashMap.get(TorontourismActivity.Presented));
imageLoader.DisplayImage(hashMap.get(TorontourismActivity.Image),Image);
Log.i("Event:", hashMap.get(TorontourismActivity.Event));
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view1) {
hashMap = xmldata.get(position);
Intent intent = new Intent(context,SingleItemView.class);
intent.putExtra("Event", hashMap.get(TorontourismActivity.Event));
intent.putExtra("Area", hashMap.get(TorontourismActivity.Area));
// intent.putExtra("Category", hashMap.get(TorontourismActivity.Category));
//intent.putExtra("Presented", hashMap.get(TorontourismActivity.Presented));
intent.putExtra("Image", hashMap.get(TorontourismActivity.Event));
context.startActivity(intent);
}
});
return view;
}
}
Single Item viewer
public class SingleItemView extends Activity {
String Event;
String Area;
String Presented;
String Category;
String Image;
ImageLoader imageLoader = new ImageLoader(this);
#Override
public void onCreate(Bundle saveInstanceState)
{
super.onCreate(saveInstanceState);
setContentView(R.layout.singleitemview);
Intent intent = getIntent();
Event = intent.getStringExtra("Event");
Area = intent.getStringExtra("Area");
//Presented = intent.getStringExtra("Presented");
// Category = intent.getStringExtra("Category");
Image = intent.getStringExtra("Image");
TextView textView = (TextView) findViewById(R.id.Event);
//TextView textView1 = (TextView) findViewById(R.id.Area);
//TextView textView2 = (TextView) findViewById(R.id.Presented);
//TextView textView3 = (TextView) findViewById(R.id.Category);
ImageView imageView = (ImageView) findViewById(R.id.Image);
textView.setText(Event);
//textView1.setText(Area);
//textView2.setText(Presented);
//textView3.setText(Category);
imageLoader.DisplayImage(Image, imageView);
}
}
Image Loader
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViewStringMap
= Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int NoImage_Id = R.drawable.temp_img;
public void DisplayImage(String url, ImageView imageView) {
imageViewStringMap.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
queuePhoto(url, imageView);
//imageView.setImageDrawable(getResources().getDrawable());
// imageView.setImageResource(R.drawable.temp_img);
}
}
private void queuePhoto(String url, ImageView imageView)
{
PhotoToLoad photoToLoad = new PhotoToLoad(url,imageView);
executorService.submit(new PhotoLoader(photoToLoad));
}
private Bitmap getBitmap(String url) {
File file = fileCache.getFile(url);
Bitmap bitmap = decodeFile(file);
if (bitmap != null)
return bitmap;
try {
Bitmap bitmap1 = null;
URL imageurl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) imageurl.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setInstanceFollowRedirects(true);
InputStream inputStream = connection.getInputStream();
OutputStream outputStream = new FileOutputStream(file);
Utils.CopyStream(inputStream, outputStream);
outputStream.close();
connection.disconnect();
bitmap = decodeFile(file);
return bitmap;
} catch (Throwable ex) {
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
private Bitmap decodeFile(File file) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
FileInputStream fileInputStream = new FileInputStream(file);
BitmapFactory.decodeStream(fileInputStream, null, options);
fileInputStream.close();
final int Size = 1000;
int width_temp = options.outWidth, height_temp = options.outHeight;
int scale = 1;
while (true) {
if (width_temp / 2 < Size || height_temp / 2 < Size)
break;
width_temp /= 2;
height_temp /= 2;
scale *= 2;
}
BitmapFactory.Options options1 = new BitmapFactory.Options();
options1.inSampleSize = scale;
FileInputStream inputStream = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options1);
inputStream.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String uri, ImageView ImView)
{
url = uri;
imageView = ImView;
}
}
class PhotoLoader implements Runnable
{
PhotoToLoad photoToLoad;
PhotoLoader(PhotoToLoad photoToLoad){
this.photoToLoad = photoToLoad;
}
#Override
public void run() {
try{
if(ImageViewReused(photoToLoad))
return;
Bitmap bitmap = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bitmap);
if(ImageViewReused(photoToLoad))
return;
BitmapDisplayer bitmapDisplayer = new BitmapDisplayer(bitmap,photoToLoad);
handler.post(bitmapDisplayer);
} catch (Throwable throwable){
throwable.printStackTrace();
}
}
}
boolean ImageViewReused(PhotoToLoad photoToLoad)
{
String string = imageViewStringMap.get(photoToLoad.imageView);
if(string == null || !string.equals(photoToLoad.url))
return true;
return false;
}
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap bitmap1, PhotoToLoad photoToLoad1)
{
bitmap = bitmap1;
photoToLoad = photoToLoad1;
}
public void run() {
if(ImageViewReused(photoToLoad))
return;
if(bitmap != null){
photoToLoad.imageView.setImageBitmap(bitmap);
}else{
//photoToLoad.imageView.setImageResource(NoImage_Id);
}
}
}
public void clearCache()
{
memoryCache.clear();
fileCache.clear();
}
}
Any help is appreciated. From what i believe the problem lies inside the parser file. Other than that please help me.
Thank you!

Parsing an image in android when we receive a relative path from server

I have the JSON:: http://54.218.73.244:7002/
"restaurants": [
{
"restaurantID": 1,
"restaurantNAME": "CopperChimney",
"restaurantIMAGE": "http://54.218.73.244:7002/CopperChimney.png",
"restaurantDISTANCE": 5,
"restaurantTYPE": "Indian",
"restaurantRATING": 3,
"restaurantPrice": 20,
"restaurantTime": "8pm to 11pm"
},
{
"restaurantID": 2,
"restaurantNAME": "Aroy",
"restaurantIMAGE": "http://54.218.73.244:7002/Aroy.png",
"restaurantDISTANCE": 10,
"restaurantTYPE": "Thai",
"restaurantRATING": 4,
"restaurantPrice": 8,
"restaurantTime": "10pm to 12pm"
}
I have used image loader to load the image in JSON and the classes i have used are listed below
FileCache.java
public class FileCache {
private File cacheDir;
public FileCache(Context context) {
// Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"JsonParseTutorialCache");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url) {
String filename = String.valueOf(url.hashCode());
// String filename = URLEncoder.encode(url);
File f = new File(cacheDir, filename);
return f;
}
public void clear() {
File[] files = cacheDir.listFiles();
if (files == null)
return;
for (File f : files)
f.delete();
}
}
ImageLoader.java
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// Handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.temp_img;
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
Bitmap b = decodeFile(f);
if (b != null)
return b;
// Download Images from the Internet
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
// Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
// Recommended Size 512
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
#Override
public void run() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
JSONfunctions.java
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView rank;
TextView country;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
rank.setText(resultp.get(MainActivity.NAME));
country.setText(resultp.get(MainActivity.TYPE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("name", resultp.get(MainActivity.NAME));
// Pass all data country
intent.putExtra("type", resultp.get(MainActivity.TYPE));
// Pass all data flag
intent.putExtra("flag", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
MemoryCache.java
public class MemoryCache {
private static final String TAG = "MemoryCache";
// Last argument true for LRU ordering
private Map<String, Bitmap> cache = Collections
.synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));
// Current allocated size
private long size = 0;
// Max memory in bytes
private long limit = 1000000;
public MemoryCache() {
// Use 25% of available heap size
setLimit(Runtime.getRuntime().maxMemory() / 4);
}
public void setLimit(long new_limit) {
limit = new_limit;
Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");
}
public Bitmap get(String id) {
try {
if (!cache.containsKey(id))
return null;
return cache.get(id);
} catch (NullPointerException ex) {
ex.printStackTrace();
return null;
}
}
public void put(String id, Bitmap bitmap) {
try {
if (cache.containsKey(id))
size -= getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size += getSizeInBytes(bitmap);
checkSize();
} catch (Throwable th) {
th.printStackTrace();
}
}
private void checkSize() {
Log.i(TAG, "cache size=" + size + " length=" + cache.size());
if (size > limit) {
// Least recently accessed item will be the first one iterated
Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, Bitmap> entry = iter.next();
size -= getSizeInBytes(entry.getValue());
iter.remove();
if (size <= limit)
break;
}
Log.i(TAG, "Clean cache. New size " + cache.size());
}
}
public void clear() {
try {
cache.clear();
size = 0;
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
long getSizeInBytes(Bitmap bitmap) {
if (bitmap == null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
}
SingleItemView.java
public class SingleItemView extends Activity {
// Declare Variables
String name;
String type;
String flag;
String position;
ImageLoader imageLoader = new ImageLoader(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from singleitemview.xml
setContentView(R.layout.singleitemview);
Intent i = getIntent();
// Get the result of rank
name = i.getStringExtra("name");
// Get the result of country
type = i.getStringExtra("type");
// Get the result of flag
flag = i.getStringExtra("flag");
// Locate the TextViews in singleitemview.xml
TextView txtrank = (TextView) findViewById(R.id.rank);
TextView txtcountry = (TextView) findViewById(R.id.country);
// Locate the ImageView in singleitemview.xml
ImageView imgflag = (ImageView) findViewById(R.id.flag);
// Set results to the TextViews
txtrank.setText(name);
txtcountry.setText(type);
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(flag, imgflag);
}
}
MainActivity.java
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
static String TYPE = "country";
static String FLAG = "flag";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7002/");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(MainActivity.NAME, jsonobject.getString("restaurantNAME"));
map.put(MainActivity.TYPE, jsonobject.getString("restaurantTYPE"));
map.put(MainActivity.FLAG, jsonobject.getString("restaurantIMAGE"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
Now suppose i have a JSON like below
"restaurants": [
{
"restaurantID": 1,
"restaurantNAME": "CopperChimney",
"restaurantIMAGE": "CopperChimney.png",
"restaurantDISTANCE": 5,
"restaurantTYPE": "Indian",
"restaurantRATING": 3,
"restaurantPrice": 20,
"restaurantTime": "8pm to 11pm"
},
{
"restaurantID": 2,
"restaurantNAME": "Aroy",
"restaurantIMAGE": "Aroy.png",
"restaurantDISTANCE": 10,
"restaurantTYPE": "Thai",
"restaurantRATING": 4,
"restaurantPrice": 8,
"restaurantTime": "10pm to 12pm"
}
I need to append the below
http://54.218.73.244:7002/
for restaurantIMAGE on the android client part so when I receive the relative path from server i can use it ..... how to perform this process and make changes in code
Any ideas
Hope I am clear
try this, Instead of this
imageLoader.DisplayImage(flag, imgflag);
Use this one it will help you.
imageLoader.DisplayImage("http://54.218.73.244:7002/"+flag, imgflag);
Loop through the arraylist and append the imagename to the URL. Add URl="http://54.218.73.244:7002" in your constant class( if you have any )So you dont need to edit the code everywhere if the url changes. And you can also use
http://loopj.com/android-smart-image-view/ for automatic image caching

Android : Loading an image from the Web with Asynctask

How do I replace the following lines of code with an Asynctask ?
How do you "get back" the Bitmap from the Asynctask ? Thank you.
ImageView mChart = (ImageView) findViewById(R.id.Chart);
String URL = "http://www...anything ...";
mChart.setImageBitmap(download_Image(URL));
public static Bitmap download_Image(String url) {
//---------------------------------------------------
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//---------------------------------------------------
}
I thought about something like this :
replace :
mChart.setImageBitmap(download_Image(graph_URL));
by something like :
mChart.setImageBitmap(new DownloadImagesTask().execute(graph_URL));
and
public class DownloadImagesTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
return download_Image(urls[0]);
}
#Override
protected void onPostExecute(Bitmap result) {
mChart.setImageBitmap(result); // how do I pass a reference to mChart here ?
}
private Bitmap download_Image(String url) {
//---------------------------------------------------
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//---------------------------------------------------
}
}
but How do I pass a reference to mChart in onPostExecute(Bitmap result) ???
Do I need to pass it with the URL in some way ?
I would like to replace all my lines of code :
mChart1.setImageBitmap(download_Image(URL_1));
mChart2.setImageBitmap(download_Image(URL_2));
with something similar ... but in Asynctask way !
mChart1.setImageBitmap(new DownloadImagesTask().execute(graph_URL_1));
mChart2.setImageBitmap(new DownloadImagesTask().execute(graph_URL_2));
Is there an easy solution for this ?
Do I get something wrong here ?
If there is no good reason to download the image yourself then I would recommend to use Picasso.
Picasso saves you all the problems with downloading, setting and caching images.
The whole code needed for a simple example is:
Picasso.with(context).load(url).into(imageView);
If you really want to do everything yourself use my older answer below.
If the image is not that big you can just use an anonymous class for the async task.
This would like this:
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) {
...
}
Hiding the URL in the tag is a bit tricky but it looks nicer in the calling class if you have a lot of imageviews that you want to fill this way. It also helps if you are using the ImageView inside a ListView and you want to know if the ImageView was recycled during the download of the image.
I wrote if you Image is not that big because this will result in the task having a implicit pointer to the underlying activity causing the garbage collector to hold the whole activity in memory until the task is finished. If the user moves to another screen of your app while the bitmap is downloading the memory can't be freed and it may make your app and the whole system slower.
Try this code:
ImageView myFirstImage = (ImageView) findViewById(R.id.myFirstImage);
ImageView mySecondImage = (ImageView) findViewById(R.id.mySecondImage);
ImageView myThirdImage = (ImageView) findViewById(R.id.myThirdImage);
String URL1 = "http://www.google.com/logos/2013/estonia_independence_day_2013-1057005.3-hp.jpg";
String URL2 = "http://www.google.com/logos/2013/park_su-geuns_birthday-1055005-hp.jpg";
String URL3 = "http://www.google.com/logos/2013/anne_cath_vestlys_93rd_birthday-1035005-hp.jpg";
myFirstImage.setTag(URL1);
mySecondImage.setTag(URL2);
myThirdImage.setTag(URL3);
new DownloadImageTask.execute(myFirstImage);
new DownloadImageTask.execute(mySecondImage);
new DownloadImageTask.execute(myThirdImage);
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) {
Bitmap bmp =null;
try{
URL ulrn = new URL(url);
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = con.getInputStream();
bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
return bmp;
}catch(Exception e){}
return bmp;
}
}
you can create a class say..BkgProcess which contains an inner class that extends AsyncTask. while instantiating BkgProcess pass the context of your Activity class in BkgProcess constructor. for eg:
public class BkgProcess {
String path;
Context _context;
public Download(Downloader downloader, String path2){
this.path = path2;
_context = downloader;
}
public void callProgressDialog(){
new BkgProcess().execute((Void)null);
}
class Downloads extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(_context);
protected void onPreExecute(){
dialog.setMessage("Downloading image..");
dialog.show();
}
protected void onPostExecute(Boolean success) {
dialog.dismiss();
if(success)
Toast.makeText(_context, "Download complete", Toast.LENGTH_SHORT).show();
}
#Override
protected Boolean doInBackground(Void... params) {
return(startDownload(path));
}
public boolean startDownload(String img_url) {
// download img..
return true;
}
}
}
from your activity class..
BkgProcess dwn = new BkgProcess (Your_Activity_class.this, img_path);
dwn.callProgressDialog();
This will get you images of any size...
if you dont want the progress dialog just comment the codes in onPreExecute();
for(int i = 0 ; i < no_of_files ; i++ )
new FetchFilesTask().execute(image_url[i]);
private class FetchFilesTask extends AsyncTask<String, Void, Bitmap> {
private ProgressDialog dialog = new ProgressDialog(FileExplorer.this);
Bitmap bitmap[];
protected void onPreExecute(){
dialog.setMessage("fetching image from the server");
dialog.show();
}
protected Bitmap doInBackground(String... args) {
bitmap = getBitmapImageFromServer();
return bitmap;
}
protected void onPostExecute(Bitmap m_bitmap) {
dialog.dismiss();
if(m_bitmap != null)
//store the images in an array or do something else with all the images.
}
}
public Bitmap getBitmapImageFromServer(){
// fetch image form the url using the URL and URLConnection class
}

Categories

Resources