Load Images from url in Android - android

I am trying to load images from url and set in to gridview, when i scroll my screen images changes. I am a beginner in android. I don't know what is the problem in my code.
Here is my code..
public class Photos extends Activity {
public static final String TAG_IMAGE_NAME = "image_name";
public static final String TAG_IMAGE_THUMB_NAME = "image_thumb_name";
public static String URL = "http://...../..../..../mainAPI.php";
ArrayList<HashMap<String, String>> photoList;
String responseData = null;
static GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photos);
gridView = (GridView)findViewById(R.id.gridView);
photoList = new ArrayList<HashMap<String,String>>();
new AsyncData().execute();
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), FullImage.class);
// passing array index
i.putExtra("ImageName", TAG_IMAGE_NAME);
startActivity(i);
}
});
}
class AsyncData extends AsyncTask<String, Void, Void> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(Photos.this);
pDialog.setTitle("Loading....");
pDialog.setMessage("Please wait...");
pDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... args) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("rquest","{\"method\":\"photogallery\",\"body\":[{}]}"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
responseData = EntityUtils.toString(resEntity);
try {
JSONArray data = new JSONArray(responseData);
for (int i = 0; i < data.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = data.getJSONObject(i);
String photoName = c.getString(TAG_IMAGE_NAME);
String imageThumbName = c.getString(TAG_IMAGE_THUMB_NAME);
map.put(TAG_IMAGE_NAME, photoName);
map.put(TAG_IMAGE_THUMB_NAME, imageThumbName);
photoList.add(map);
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
gridView.setAdapter(new PhotosAdapter(Photos.this, R.layout.photo_row, photoList));
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
PhgotosAdapter Class
public class PhotosAdapter extends ArrayAdapter<HashMap<String, String>>{
Context context;
String uri;
Bitmap bitmap;
ArrayList<HashMap<String, String>> myList;
HashMap<String, String> myData;
int layout;
public PhotosAdapter(Context context, int textViewResourceId, List<HashMap<String, String>> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
this.context = context;
this.myList = (ArrayList<HashMap<String, String>>) objects;
this.layout = textViewResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = null;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layout, parent, false);
myData = myList.get(position);
ImageView image = (ImageView)row.findViewById(R.id.imagePhoto);
try{
ImageDownloadTask task = new ImageDownloadTask(image);
task.execute();
uri = "" + myData.get(Photos.TAG_IMAGE_THUMB_NAME).replace(" ", "%20");
image.setImageBitmap(bitmap);
image.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return row;
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
class ImageDownloadTask extends AsyncTask<Void, Integer, Bitmap> {
private ImageView mView;
ProgressDialog pDialog;
ImageDownloadTask(ImageView view){
mView = view;
}
#Override
protected Bitmap doInBackground(Void... params) {
try {
bitmap = getBitmapFromURL(uri);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
mView.setImageBitmap(result);
}
}
}
I don't know what is the problem in it, Please Help me and give some solution.

ImageLoader imageLoader;
imageLoader=new ImageLoader(context.getApplicationContext());
imageLoader.DisplayImage(urlname, imageViewname);
try it

Related

android json parsing and image loading

I want to parse data and images via url of json.
I have used following code to do same. But i am not getting why the images disappear when i scroll down.
Can Anyone please tell me how can i stop to disappear images when i scroll down ?
Images are loading randomly how can i fix it?
Please find below link of source code :-
http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/
public class MainActivity extends Activity {
ArrayList<Actors> actorsList;
ActorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://milagro.in/wip/apps/n/THDC2.json");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), actorsList.get(position).gettata_project_name(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.settata_project_name(object.getString("tata_project_name"));
actor.setproject_Typology(object.getString("project_Typology"));
actor.setproject_logo_url(object.getString("project_logo_url"));
actor.setprice(object.getString("price"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.Projectname = (TextView) v.findViewById(R.id.Projectname);
holder.typology = (TextView) v.findViewById(R.id.typology);
holder.price = (TextView) v.findViewById(R.id.price);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getproject_logo_url());
holder.imageview.setImageResource(R.drawable.ic_launcher);
//new DownloadImageTask(holder.imageview).execute(actorList.get(position).getproject_logo_url());
holder.Projectname.setText(actorList.get(position).gettata_project_name());
holder.typology.setText(actorList.get(position).getproject_Typology());
holder.price.setText("Price: " + actorList.get(position).getprice());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView Projectname;
public TextView typology;
public TextView price;
}
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);
}
}
public class Actors {
private String tata_project_name;
private String project_Typology;
private String project_logo_url;
private String price;
public Actors() {
// TODO Auto-generated constructor stub
}
public Actors(String tata_project_name, String project_Typology,String project_logo_url, String price ) {
super();
this.tata_project_name = tata_project_name;
this.project_Typology = project_Typology;
this.project_logo_url = project_logo_url;
this.price = price;
}
public String gettata_project_name() {
return tata_project_name;
}
public void settata_project_name(String tata_project_name) {
this.tata_project_name = tata_project_name;
}
public String getproject_Typology() {
return project_Typology;
}
public void setproject_Typology(String project_Typology) {
this.project_Typology = project_Typology;
}
public String getproject_logo_url() {
return project_logo_url;
}
public void setproject_logo_url(String project_logo_url) {
this.project_logo_url = project_logo_url;
}
public String getprice() {
return price;
}
public void setprice(String price) {
this.price = price;
}
}
try this library Picaso this is the best image loading library from url.
After using Volley library The problem is solved.

Android listview scrolling image wrong (shuffle)

I have a big problem.I'm trying to make a ListView with dynamically loaded images, using an AsyncTask to download the image and then set it into the ListView. My problem is that, while scrolling down, the images get randomly changed.I saw answers but I can't figure.
My Codes:
(Adapter)
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
private static LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageHaberFoto = (ImageView) v.findViewById(R.id.ivImage);
holder.tvHaberBaslik = (TextView) v.findViewById(R.id.tvHaberBaslik);
holder.tvHaberTarihi = (TextView) v.findViewById(R.id.tvHaberTarihi);
holder.tvKisaTanim = (TextView) v.findViewById(R.id.tvKisaTanim);
holder.tvDetay = (TextView) v.findViewById(R.id.tvDetay);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
new DownloadImageTask(holder.imageHaberFoto).execute(actorList.get(position).getHaberFoto());
holder.tvHaberBaslik.setText(actorList.get(position).getHaberBaslik());
holder.tvKisaTanim.setText(actorList.get(position).getHaberKisatanim());
holder.tvHaberTarihi.setText(actorList.get(position).getHaberTarihi());
holder.tvDetay.setText(actorList.get(position).getDetay());
return v;
}
static class ViewHolder {
public ImageView imageHaberFoto;
public TextView tvHaberBaslik;
public TextView tvHaberTarihi;
public TextView tvKisaTanim;
public TextView tvDetay;
}
private static 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);
}
}
}
Actor Class :
public class Actors {
private String HaberBaslik;
private String HaberTarihi;
private String HaberKisatanim;
private String HaberlerLink;
private String HaberFoto;
private String Detay;
public Actors() {
}
//Getters and setters
public String getHaberBaslik() {
return HaberBaslik;
}
public void setHaberBaslik(String HaberBaslik) {
this.HaberBaslik = HaberBaslik;
}
public String getHaberTarihi() {
return HaberTarihi;
}
public void setHaberTarihi(String HaberTarihi) {
this.HaberTarihi = HaberTarihi;
}
public String getHaberKisatanim() {
return HaberKisatanim;
}
public void setHaberKisatanim(String HaberKisatanim) {
this.HaberKisatanim = HaberKisatanim;
}
public String getHaberlerLink() {
return HaberlerLink;
}
public void setHaberlerLink(String HaberlerLink) {
this.HaberlerLink = HaberlerLink;
}
public String getDetay() {
return Detay;
}
public void setDetay(String Detay) {
this.Detay = Detay;
}
public String getHaberFoto() {
return HaberFoto;
}
public void setHaberFoto(String HaberFoto) {
this.HaberFoto = "http://www.developers.net/images/"+HaberFoto;
}
}
ListView:
ArrayList actorsList;
ActorAdapter adapter;
new JSONAsyncTask().execute("http://www.developers.net/WebServices/GetJson.aspx?q=Haber");
ListView listview = (ListView) findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
//JSONAsyncTask
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(haberler.this);
dialog.setMessage("Lütfen bekleyin.");
dialog.setTitle("İçerik Yüklemesi");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("Haberler");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setHaberBaslik(object.getString("Baslik"));
actor.setHaberKisatanim(object.getString("Kisa"));
actor.setDetay(object.getString("Detay"));
actor.setHaberTarihi(object.getString("Tarih").replace("00:00:00",""));
actor.setHaberFoto(object.getString("Foto"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if (result == false)
Toast.makeText(getApplicationContext(), "Veri alınamıyor.Lütfen daha sonra tekrar deneyin.", Toast.LENGTH_LONG).show();
}
}

android asynctask is not executing inside baseadapter

I have a Baseadapter for a listview, when 1 of the elements inside gets clicked it is supposed to execute an AsyncTask. The onClick is inside Baseadapter and that works however the async execute is not working here is my baseAdapter
public class LocalFeed_CustomView extends BaseAdapter {
JSONObject names;
Context ctx;
LayoutInflater myiflater;
public LocalFeed_CustomView(){}
public LocalFeed_CustomView(JSONObject arr,Context c) {
ctx = c;
names = arr;
// myiflater = (LayoutInflater)c.getSystemService(c.LAYOUT_INFLATER_SERVICE);
// System.err.println("vv:" + arr);
}
#Override
public int getCount() {
try {
JSONArray jaLocalstreams = names.getJSONArray("localstreams");
return jaLocalstreams.length();
} catch (Exception e) {
Toast.makeText(ctx,"Error: Please try again",Toast.LENGTH_LONG).show();
return names.length();
}
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position,View convertView, ViewGroup parent) {
try {
if(convertView==null) {
LayoutInflater li = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.customadapter, null);
}
TextView votes= (TextView)convertView.findViewById(R.id.votes);
JSONArray jaLocalstreams = names.getJSONArray("localstreams");
final JSONObject jsonObject = jaLocalstreams.getJSONObject(position);
jsonObject.getInt("id");
// the click works because the toast message fires
votes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
int Stream_ID= jsonObject.getInt("id");
SharedPreferences myaccount = ctx.getSharedPreferences("userInfo", ctx.MODE_PRIVATE);
int Profile_id=myaccount.getInt("id", 0);
Toast.makeText(ctx, "click worked", Toast.LENGTH_SHORT).show();
// the execute below is not firing off
new Add_Votes(Stream_ID,Profile_id).execute();
}
catch (Exception e)
{
e.getCause();
}
}
});
return convertView;
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
}
As you can see the execute is not working and both of the int values have numbers in them. This is my AsyncTask
public class Add_Votes extends AsyncTask<String,String,String> {
HttpURLConnection conn;
URL url;
String result="";
DataOutputStream wr;
String Stream_URL;
Activity m;
int stream_id,profile_id;
public Add_Votes(int stream_id,int profile_id)
{
this.stream_id=stream_id;
this.profile_id=profile_id;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Stream_URL= m.getResources().getString(R.string.PathUrl)+"/api/addvote";
//this Toast never fires off
Toast.makeText(m.getApplicationContext(),"clicked",Toast.LENGTH_SHORT);
}
#Override
protected String doInBackground(String... params) {
BufferedReader reader=null;
try{
url = new URL(Stream_URL);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
String cert="id="+profile_id+"&stream_id="+stream_id;
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(cert);
wr.flush();
wr.close();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sBuilder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sBuilder.append(line + "\n");
}
result = sBuilder.toString();
reader.close();
conn.disconnect();
return result;
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
Toast.makeText(m.getApplicationContext(),"Voted",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(m.getApplicationContext(),"Inconclusive",Toast.LENGTH_SHORT).show();
}
}
}
Add_Votes is only an AsyncTask there is no activity associated with it. Any suggestions on how I can call an AsyncTask from a baseadapter would be great. It needs to be from a baseadapter because each row has different values depending on the item clicked which then I pass on to the Async Task.
One thing I notice is you are using a variable Activity m and you have not initialised it in your AsyncTask. try passing a context from your BaseAdapter to AsyncTask.
In Add_Votes :
private Context context;
public Add_Votes(Context context ,int stream_id,int profile_id)
{
this.stream_id=stream_id;
this.profile_id=profile_id;
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(context,"clicked",Toast.LENGTH_SHORT).show();
}
In your BaseAdapter:
Add_Votes add_Votes = new Add_Votes(ctx,Stream_ID,Profile_id);
add_Votes.execute();

Custom Listview Loops through all images in first listItem

i have a list view that is populated from a database with a customlistview...everything works fine except when i first start activity, the first item on the list view, loops through all images and then sets each image to corresponding item. I cannot figure out what i am doing wrong. pls help. I have gone through al the answers on stackoverflow but nothing works for me. Here is my custom list view:
***Edit:This code is working fine now. I fixed it.
public class FriendsListView extends ArrayAdapter<FriendsRowItem> {
Context context;
ArrayList<FriendsRowItem> infoList;
private LayoutInflater inflater = null;
int Resource;
ViewHolder holder;
public FriendsListView(Context context, int resourceId,
ArrayList<FriendsRowItem> items) {
super(context, resourceId, items);
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resourceId;
infoList = items;
}
/* private view holder class */
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
}
public int getCount() {
return infoList.size();
}
public RowItem getItem(RowItem position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (vi == null) {
vi = inflater.inflate(R.layout.list_item_3, parent, false);
holder = new ViewHolder();
holder.txtTitle = (TextView) vi.findViewById(R.id.title3);
holder.imageView = (ImageView) vi.findViewById(R.id.icon3);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.txtTitle.setText(infoList.get(position).getTitle());
holder.imageView.setImageResource(R.drawable.ic_launcher);
new DownloadImageTask(holder.imageView).execute(infoList.get(position)
.getImage());
return vi;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
int position;
public DownloadImageTask(ImageView bmImage, int position) {
this.bmImage = bmImage;
this.position = position;
bmImage.setTag(position);
bmImage.setImageBitmap(null);
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = (InputStream) new java.net.URL(urldisplay)
.getContent();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
// Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
if (result != null && (bmImage.getTag()).equals(this.position))
bmImage.setImageBitmap(result);
bmImage.setImageBitmap(result);
}
}
And how i populate my list view using JSON:
class RetrieveFriendsTask extends AsyncTask<Void, Void, Void> {
ArrayList<FriendsRowItem> FriendList = new ArrayList<FriendsRowItem>();
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pDialog != null) {
pDialog.dismiss();
}
// Showing progress dialog
else {
pDialog = new ProgressDialog(Friends.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("eposta", email));
pairs.add(new BasicNameValuePair("sifre", pass));
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET, pairs);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonStr);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
JSONObject obj = jsonObj.getJSONObject("data");
friends = obj.getJSONArray(TAG_EVENTS);
for (int i = 0; i < friends.length(); i++) {
friend = new FriendsRowItem();
JSONObject c = friends.getJSONObject(i);
nick = c.optString("nick");
// friend.setTitle(c.optString("nick"));
img = c.optString("url_resim");
// friend.setImage(c.optString("url_resim"));
friend.setTitle(nick);
friend.setImage(img);
FriendList.add(friend);
}
}
catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(Void result) {
if (pDialog.isShowing())
pDialog.dismiss();
adapter = new FriendsListView(Friends.this, R.layout.list_item_3,
FriendList);
lvfriends.setAdapter(adapter);
OnItemClickListener myListViewClicked = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
FriendsRowItem name = (FriendsRowItem) parent
.getItemAtPosition(position);
Intent i = new Intent(Friends.this, FriendsDisplay.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("FriendName", name.toString());
startActivity(i);
}
};
lvfriends.setOnItemClickListener(myListViewClicked);
}
}
I would really appreciate the help.

Downloading images from a link displaying them in a listview

I have a list where for each item i need to display a image. I am downloading the image from a link and displaying it but with i am facing problems to display them as the list gets populated by text first and then downloads the images later.Also another problem is whenever i go up or down in the list image disappears and download again so the images are gone when i come to to the top the list items
EventTask
public RecieveEventsTask(EventListActivity c, String critiria) {
appContext = c;
session = new SessionManager(appContext);
HashMap<String, String> user = session.getUserDetails();
String id = user.get(SessionManager.KEY_ID);
url = "http://bioscopebd.com/mobileappand/geteventlist?user_id=" + id;
}
public RecieveEventsTask(MyEventList c, String critiria) {
my_appContext = c;
session = new SessionManager(my_appContext);
HashMap<String, String> user = session.getUserDetails();
// id
String id = user.get(SessionManager.KEY_ID);
url = "http://bioscopebd.com/mobileappand/getmyeventlist?user_id=" + id;
}
protected void onPreExecute() {
dialog = new ProgressDialog(appContext == null ? my_appContext
: appContext);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading Events...");
dialog.show();
super.onPreExecute();
}
String filterResponseString(String r) {
return r.replace("\r\n", "");
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(new HttpGet(url));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
responseString = filterResponseString(responseString);
} else {
// Closes the connection.
response.getEntity().getContent().close();
Utility.showMessage(appContext, "Cannot Connect To Internet");
}
} catch (Exception e) {
// TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
if (responseString != null) {
ArrayList<EventModel> eventsList = new ArrayList<EventModel>();
;
JSONArray jsonArr;
try {
// Log.v("json", responseString);
jsonArr = new JSONArray(responseString);
// jsonArr = events.getJSONArray("events");
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
EventModel event = new EventModel();
event.setTitle(jsonObj.getString("event_info_title"));
event.setDescription(jsonObj.getString("event_info_desc"));
// Log.v("logo data "+i, jsonObj.getString("image_logo"));
event.setBanner(jsonObj.getString("image_banner"));
event.setLogo(jsonObj.getString("image_logo"));
// event.setDescription(jsonObj.getString("event_info_desc"));
event.setCategory(jsonObj.getString("event_cat_title"));
event.setStartDate(jsonObj
.getString("event_info_start_date"));
event.setEndDate(jsonObj.getString("event_info_end_date"));
event.setStartTime(jsonObj
.getString("event_info_start_time"));
event.setEndTime(jsonObj.getString("event_info_end_time"));
event.setEventId(jsonObj.getString("event_info_id"));
event.setPhone(jsonObj.getString("event_info_mobile"));
event.setEmail(jsonObj.getString("event_info_email"));
event.setWeblink(jsonObj.getString("event_info_web"));
//
// logoDownloader = new ImageDownloader(event.getLogoBitmap());
// logoDownloader.execute(event.getLogo());
//
// bannerDownloader = new ImageDownloader(event.getBannerBitmap());
// bannerDownloader.execute(event.getBanner());
//
eventsList.add(event);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (appContext != null) {
appContext.showEventsDataLoaded(eventsList);
}
if (my_appContext != null) {
my_appContext.showEventsDataLoaded(eventsList);
}
// else
// {
// Log.v("check:","null");
//
// }
//
} else {
if(appContext!=null)
{
Utility.showMessage(appContext, "Cannot Connect To Internet");
}
else {
Utility.showMessage(my_appContext, "Cannot Connect To Internet");
}
//
}
super.onPostExecute(result);
// Do anything with response..
}
i get the image link in my setlogo and setbanner method
Adapter class
private final Activity context;
private final ArrayList<EventModel> events;
ImageDownloader imgDownloader;
Bitmap bitmap;
ImageView icon;
public EventsListAdapter(Activity context, ArrayList<EventModel> events) {
super(context, com.bioscope.R.layout.event_listitem, events);
this.context = context;
this.events = events;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(com.bioscope.R.layout.event_listitem,
null, true);
TextView title = (TextView) rowView
.findViewById(com.bioscope.R.id.title);
title.setText(events.get(position).getTitle());
TextView description = (TextView) rowView
.findViewById(com.bioscope.R.id.description);
description.setText(events.get(position).getDescription());
TextView category = (TextView) rowView
.findViewById(com.bioscope.R.id.category);
category.setText(events.get(position).getCategory());
Log.v("logo", events.get(position).getLogo());
icon = (ImageView) rowView
.findViewById(com.bioscope.R.id.event_icon);
//imgDownloader = new ImageDownloader(icon);
new LoadImage().execute(events.get(position).getLogo());
//ImageLoader.displayImage(events.get(position).getLogo().toString(), icon);
return rowView;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// pDialog = new ProgressDialog(MainActivity.this);
// pDialog.setMessage("Loading Image ....");
// pDialog.show();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
icon.setImageBitmap(image);
//pDialog.dismiss();
}else{
//pDialog.dismiss();
// Toast.makeText(EventListActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
// icon.set
}
}
}
}
i am setting the image in my icon of list items
Activity class
private ListView list;
private MenuItem myActionMenuItem;
private EditText myActionEditText;
private TextView myActionTextView;
private AutoCompleteTextView actv;
// private Spinner spinner;
private Button liveEvent;
private ArrayList<EventModel> eventsList;
private static final String[] paths = { "All", "Favourites" };
private ArrayList<String> array_sort;
int textlength = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.bioscope.R.layout.eventlist);
RecieveEventsTask task = new RecieveEventsTask(this, "all");
task.execute();
}
public void showEventsDataLoaded(ArrayList<EventModel> eventsList) {
this.eventsList = eventsList;
// for(EventModel e:eventsList )
// {
// Log.v("title", e.getTitle());
// }
EventsListAdapter adapter = new EventsListAdapter(
EventListActivity.this, eventsList);
list = (ListView) findViewById(com.bioscope.R.id.listView1);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// Toast.makeText(EventList.this, "You Clicked an item ",
// Toast.LENGTH_SHORT).show();
showEventInformaion(position);
}
});
// RecieveCategoriesTask task = new RecieveCategoriesTask(this, "all");
// task.execute();
liveEvent = (Button) findViewById(R.id.liveEvent);
liveEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(EventListActivity.this,
LiveEventActivity.class);
startActivity(i);
}
});
}
public void showCategoryListDataLoaded(String response) {
Utility.showMessage(this, response);
}
Then in my activity i called the async reciver task to load all the data along with link and gave set them in my model class.
You haveto set ResponseCache in your Main class while downloading bitmap:
Like this:
try {
File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) { }
and
connection.setUseCaches(true);
http://practicaldroid.blogspot.com/2013/01/utilizing-http-response-cache.html

Categories

Resources