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();
}
}
Related
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);
}
}
}
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.
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();*/
}
}
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.
i hv an application in which i am getting data from api,when data get loads and i tried to scroll the listview it get starts jerking,i tried to find the solution but get nothing.please help me to sort it out.
InboxActivity.java
list=(ListView)rootView.findViewById(R.id.list);
catagery = new ArrayList<ProfileInbox>();
String fontPath = "font/Roboto-Regular.ttf";
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), fontPath);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View arg1,
int position, long id) {
// TODO Auto-generated method stub
//arg0.getp.setBackgroundColor(Color.WHITE);
//parent.getChildAt(position).setBackgroundColor(Color.BLUE);
IsRead=true;
catagery.get(position).setRead(IsRead);
new Task().execute(url);
adapter.notifyDataSetChanged();
msg=catagery.get(position).getMessage();
dateFrom=catagery.get(position).getSentDate();
sub=catagery.get(position).getSubject();
Intent i= new Intent(getActivity(),InboxDetail.class);
startActivity(i);
}
});
return rootView;
}
private void loadNextPageOfReviews()
{
page_no_count += 1;
new JSONAsyncTask().execute(loadMoreUrl);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Please Wait, Loading...");
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("inbox");
String unread_msg= jsono.getString("unread_msg");
Log.i("unreadMsg", unread_msg);
for (int i = 0; i < jarray.length(); i++) {
JSONObject c = jarray.getJSONObject(i);
ProfileInbox category = new ProfileInbox();
String id = c.getString("msg_id");
String sub = c.getString("subject");
String name = c.getString("message");
String imageSetter=c.getString("sent_on");
//Log.i("id", id);
//Log.i("name", name);
//Log.i("imageSetter", imageSetter);
category.setMsgId(((JSONObject) c).getString("msg_id"));
if(unread_msg.contains(id)){
category.setRead(false);
}
else{
category.setRead(true);
}
category.setSubject(((JSONObject) c).getString("subject"));
category.setMessage(((JSONObject) c).getString("message"));
category.setSentDate(((JSONObject) c).getString("sent_on"));
//Log.i("category", category.toString());
catagery.add(category);
//Log.i("category", category.toString());
}
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();
if (result == false){
Toast.makeText(getActivity(),
"Unable to fetch data from server", Toast.LENGTH_LONG)
.show();
}
else if(Blank.notice.equals("true")){
msg=catagery.get(0).getMessage();
dateFrom=catagery.get(0).getSentDate();
sub=catagery.get(0).getSubject();
adapter = new InboxAdaptor(getActivity(),
catagery);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
Intent i= new Intent(getActivity(),InboxDetail.class);
startActivity(i);
}
else if(Blank.notice.equals("false"))
{
//adapter.notifyDataSetChanged();
adapter = new InboxAdaptor(getActivity(),
catagery);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
InboxAdapter
public class InboxAdaptor extends BaseAdapter {
private List<ProfileInbox> originalData;
private List<ProfileInbox> filteredData;
private Context context;
public static String url;
public static String bussinessId;
public InboxAdaptor(Context context, ArrayList<ProfileInbox> Data) {
this.context = context;
this.originalData = Data;
//Log.i("originalData", Data.toString());
filteredData = new ArrayList<ProfileInbox>();
filteredData.addAll(this.originalData);
//Log.i("filterData", filteredData.toString());
}
#Override
public int getCount() {
return filteredData.size();
}
#Override
public Object getItem(int position) {
return filteredData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.inboxlist, null,false);
holder.coloredlay=(RelativeLayout)convertView.findViewById(R.id.coloredlay);
holder.txtWelcom = (TextView) convertView.findViewById(R.id.txtWelcom);
holder.dateTime = (TextView) convertView.findViewById(R.id.dateTime);
holder.txtdetails = (TextView) convertView.findViewById(R.id.txtdetails);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
if(filteredData.get(position).getRead()==true)
{
holder.coloredlay.setBackgroundColor(Color.WHITE);
notifyDataSetChanged();
}else{
holder.coloredlay.setBackgroundColor(Color.parseColor("#E5E4E2"));
}
// holder.img.setTag(position);
String fontPath = "font/Roboto-Regular.ttf";
// Loading Font Face
Typeface tf = Typeface.createFromAsset(convertView.getContext().getAssets(), fontPath);
holder.txtWelcom.setText(filteredData.get(position).getSubject());
holder.txtWelcom.setTypeface(tf);
holder.dateTime.setText(filteredData.get(position).getSentDate());
holder.dateTime.setTypeface(tf);
holder.txtdetails.setText(filteredData.get(position).getMessage());
holder.txtdetails.setTypeface(tf);
/* if(Blank.notice.equals("true")){
holder.coloredlay.setBackgroundColor(Color.WHITE);
notifyDataSetChanged();
}
*/
notifyDataSetChanged();
return convertView;
}
public static class ViewHolder {
public RelativeLayout coloredlay;
public TextView txtdetails;
public TextView dateTime;
public TextView txtWelcom;
}
Remove notifyDataSetChanged() from getView() , notifyDataSetChanged() will update adapter when the data which you provided for your adapter has been changed , but you are using that wrong when a View of your list has been changed.
Remove notifyDataSetChanged() from getView().
You dot need that here. Rather have Remove notifyDataSetChanged() in onPostExecute() call back of JSONAsyncTask
Use cachecolorHint for come out of your solution:
<ListView
android:id="#+id/listNewsMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#android:color/transparent" >
</ListView>