Search code examples
androidlistviewonclicktextviewandroid-lazyloading

Lazy loading onclick listview


I am doing a lazyload code for list view in which i am getting a text and image url in json and putting them in the listview.

The image and text are both shown accordingly as what i wanted.

The problem i am facing is when the list is scrolled downwards or upwards the index of the view gets disturbed.

Suppose if have 10 elements in my list with images previewing sideways. Initially i can see 4 elements on whose onclick action works fine, But when i scrolldown and click the 7th ir 8th element the indexing gets disturbed and results in null pointer exception.

   l2.setOnItemClickListener(new OnItemClickListener() {
    @Override
     public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
        {
            View curr = parent.getChildAt((int) id);
            TextView c = (TextView)curr.findViewById(R.id.text);
            String sel_item = c.getText().toString();
            Intent intent = new Intent(SubCatListActivity.this,GridActivity.class);
             adapter.imageLoader.clearCache();
            intent.putExtra("gall", sel_item);
            intent.putExtra("cate", cate);
            startActivity(intent);
            Toast.makeText(SubCatListActivity.this,sel_item, Toast.LENGTH_SHORT).show();

         }});

the problem seems to be with the textview as i am not able to get the desired text on the onclick of list.

If i touch the 6th element i get the text of 7th or 8th item.


Solution

  • You can try by changing this line to

    TextView c = (TextView) view.findViewById(R.id.text);
    

    and remove your first line View curr = parent.getChildAt((int) id);

    l2.setOnItemClickListener(new OnItemClickListener() {
    @Override
     public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
        {
    
            TextView c = (TextView) view.findViewById(R.id.text);
            String sel_item = c.getText().toString();
            Intent intent = new Intent(SubCatListActivity.this,GridActivity.class);
             adapter.imageLoader.clearCache();
            intent.putExtra("gall", sel_item);
            intent.putExtra("cate", cate);
            startActivity(intent);
            Toast.makeText(SubCatListActivity.this,sel_item, Toast.LENGTH_SHORT).show();
    
         }});