ImageView Glitching AsyncTask - android

Im pulling images from the server with asyncTask and drawing them on imageViews. The problem is that Images sometimes get "shuffled" and it takes them couple of seconds to deploy proper image. And it can get laggy too. Is there any easier way to do that? Am I doing something wrong?
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(RecipeActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting to 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 array = jsono.getJSONArray("recepies");
JSONArray array = new JSONArray(data);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
Recepies rec = new Recepies();
rec.setName(object.getString("name"));
rec.setPciture(object.getString("picture"));
receptis.add(rec);
}
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();
}
}
and this is the MainActivity:
ArrayList<Recepies> recepies;
String nameRecepie, ingredients, priprema, picture;
Toolbar toolbar;
RecipesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipes_activity);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle("Dog recepies");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
receptis = new ArrayList<Recepti>();
new JSONAsyncTask().execute("url");
ListView listview = (ListView) findViewById(R.id.list);
adapter = new RecipesAdapter(getApplicationContext(), R.layout.row, receptis);
listview.setAdapter(adapter); //onclick listener ->
and my Adapter class
public class RecipesAdapter extends ArrayAdapter<Recepti> {
ArrayList<Recepti> receptisList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public RecipesAdapter(Context context, int resource, ArrayList<Recepti> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
receptisList = 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.tvName = (TextView) v.findViewById(R.id.tvName);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
new DownloadImageTask(holder.imageview).execute(receptisList.get(position).getSlika());
holder.tvName.setText(receptisList.get(position).getNaziv());
return v;
}
static class ViewHolder {
public TextView tvName;
public ImageView imageview;
}
protected 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);
}
}
}

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

staggeredgrid view in portrait and landscape mode

I'm using the staggered grid view to display my information that I get via a webservice. when i displayed it in format portrait there is no problem.( I have 2 grids). In landscape mode I have 3 grids. The problem is here, the textview change the size and became bigger and when I scroll to the end, I will have 2 or 1 grids (not 3) and sometime no grid.
This is the adapter code:
public class StaggeredAdapterVraiCategorie extends ArrayAdapter<VraiCategorie> {
ArrayList<VraiCategorie> categorieList;
LayoutInflater vi;
int Resource;
private ImageLoader mLoader;
Context context;
public StaggeredAdapterVraiCategorie(Context context, int resource,ArrayList<VraiCategorie> objects) {
super(context, resource, objects);
categorieList = objects;
Resource = resource;
this.context=context;
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mLoader = new ImageLoader(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater layoutInflator = LayoutInflater.from(getContext());
convertView = layoutInflator.inflate(R.layout.vrai_list_item_sample,null);
holder = new ViewHolder();
holder.imageView = (DynamicHeightImageView)convertView.findViewById(R.id.image);
holder.namecateg = (TextView)convertView.findViewById(R.id.namecateg);
holder.reftype = (TextView)convertView.findViewById(R.id.reftype);
holder.myid = (TextView)convertView.findViewById(R.id.myid);
convertView.setTag(holder);
}
// else {
holder =(ViewHolder)convertView.getTag();
// }
holder.namecateg.setText(categorieList.get(position).getNamecateg());
holder.reftype.setText(categorieList.get(position).getReftype());
holder.myid.setText(categorieList.get(position).getMyid());
String imgget=categorieList.get(position).getImagecateg();
if(!imgget.equals("null")){
String mylink="http://myserver/images/";
String imgexe=mylink+imgget;
new DownloadImageTask(holder.imageView).execute(imgexe);
}
else if (imgget.equals("null")){
holder.imageView.setHeightRatio(1.0); //ta3mel prob fel staggered
holder.imageView.setImageResource(R.drawable.nophoto);
}
if(!categorieList.get(position).getImagecateg().equals("null")) {
String mylink = "http://myserver/images/";
// holder = (ViewHolder) convertView.getTag();
mLoader.DisplayImage(mylink + categorieList.get(position).getImagecateg(), holder.imageView);
}
return convertView;
}
static class ViewHolder {
public DynamicHeightImageView imageView;
public TextView namecateg;
public TextView reftype;
public TextView myid;
}
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);
}
}
}
This is the main class:
public class VraiCateg extends BaseFragment implements StaggeredGridView.OnItemClickListener {
ArrayList<VraiCategorie> categorieList;
StaggeredAdapterVraiCategorie adapter;
StaggeredGridView staggeredGridView;
String passtitle="";
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES="My profile info";
public static final String keyidhotel="idH";
private String myidhotel="";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.vrai_main, container, false);
Main activity = (Main) getActivity();
String myDataFromActivity = activity.getData();
myidhotel = myDataFromActivity;
final String url = "http://myserver/api/type_etablissement/categories/id/"+myidhotel;
//url = url + myidhotel;
Toast.makeText(getActivity().getApplicationContext(), "Adresse categ URL "+url, Toast.LENGTH_LONG).show();
staggeredGridView = (StaggeredGridView) view.findViewById(R.id.grid_view);
// myidhotel = getArguments().getString("idH");
int margin = getResources().getDimensionPixelSize(R.dimen.margin);
staggeredGridView.setPadding(margin, 0, margin, 0);
if(!(MySuperScaler.scaled))
MySuperScaler.scaleViewAndChildren(view, MySuperScaler.scale);
categorieList = new ArrayList<VraiCategorie>();
new CategorieAsyncTask().execute(url);
staggeredGridView.setOnItemClickListener(this);
return view;
}
class CategorieAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
dialog.cancel();
if (result == false){
//show a msg to user that data not parsed
Toast.makeText(getActivity().getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
else {
//call etab adapter and create now adapter
StaggeredAdapterVraiCategorie adapter = new StaggeredAdapterVraiCategorie(getActivity().getApplicationContext(),R.layout.vrai_list_item_sample,categorieList);
staggeredGridView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
protected Boolean doInBackground(String... params) {
try {
HttpClient client = new DefaultHttpClient();
//HttpPost post = new HttpPost(uri); //uri in oncreate method
HttpGet get = new HttpGet(params[0]);
HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
if(status ==200){
//get the response and pars it
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jObj = new JSONObject(data);
JSONArray jArray = jObj.getJSONArray("categories");
for(int i=0;i<jArray.length();i++ ){
VraiCategorie categ = new VraiCategorie();
JSONObject jRealObject = jArray.getJSONObject(i);
categ.setImagecateg(jRealObject.getString("image_categorie"));
categ.setNamecateg(jRealObject.getString("description_type"));
//ref_type=jRealObject.getString("ref_type");
categ.setReftype(jRealObject.getString("ref_type"));
categ.setMyid(jRealObject.getString("my_id"));
categorieList.add(categ);
}
return true; //verifie the parse
}
}catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
//http call
return false;
}
}
#Override
public void onItemClick(StaggeredGridView parent, View view, int position, long id) {
final String ref_type= categorieList.get(position).getReftype();
Fragment newFragment = new VraiRela();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Bundle args=new Bundle();
args.putString("ref_type",ref_type);
args.putString("idH",myidhotel);
// Toast.makeText(getActivity().getApplicationContext(), "ref_type"+ref_type+"idH"+myidhotel, Toast.LENGTH_LONG).show();
newFragment.setArguments(args);
transaction.replace(R.id.frame_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
/* myidhotel="";
sharedpreferences = getActivity().getApplicationContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
myidhotel="";
editor.putString(keyidhotel, myidhotel);
editor.commit();*/
}
}

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.

Load Images from url in 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

Categories

Resources