Image reloaded when scroll listView in android

笑着哭i 提交于 2019-12-23 16:24:01

问题


I am trying write a news list application. I had parsed JSON data from Server and created CustomListAdapter. There are three textView and imageView in my listView. It works great, image loaded and I set it to imageView. When scroll list view images are reloaded from server. This is my Fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.news_fragment, container, false);
    this.drawerPosition = getArguments().getInt(ARG_PLANET_NUMBER);
    lv = (ListView) rootView.findViewById(R.id.listView);
    View v = inflater.inflate(R.layout.list_footer, null);
    lv.addFooterView(v);
    isLoading = true;
    Http.getLists(aContext, this.drawerPosition, pageNumber, resultHandler);
    lv.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView absListView, int i) {
        }

        @Override
        public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            int l = visibleItemCount + firstVisibleItem;
            if (l >= totalItemCount && !isLoading) {
                // It is time to add new data. We call the listener
                isLoading = true;
                Http.getLists(aContext, drawerPosition, pageNumber, appendHandler);
            }
        }
    });
    return rootView;
}

public void setListview() {
    listAdapter = new ListViewCustomAdapter(aContext, arrayList);
    lv.setAdapter(listAdapter);
}

AsyncHttpResponseHandler resultHandler = new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
        if (statusCode != 200)
            return;
        try {
            JSONObject json = new JSONObject(new String(responseBody));
            Log.d("JSON Result: ", json.toString());
            String result = json.getString("status");
            if (result.equalsIgnoreCase("complete")) {
                String pagenum = json.getString("pagenum");
                JSONArray items = json.getJSONArray("items");
                ArrayList<NewsList> s = new ArrayList<NewsList>();
                for (int i = 0; i < items.length(); i++) {
                    s.add(new NewsList(
                            Integer.parseInt(items.getJSONObject(i).getString("ID")),
                            items.getJSONObject(i).getString("post_date"),
                            items.getJSONObject(i).getString("category"),
                            items.getJSONObject(i).getString("post_title"),
                            items.getJSONObject(i).getString("image")
                    ));
                }
                arrayList = s;
                isLoading = false;
                pageNumber = Integer.valueOf(pagenum) + 1;
                setListview();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        String answ = error.getLocalizedMessage();
        Log.d("API", answ);
    }
};

This is my Custom ListView Adapter:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    ViewHolder holder;

    if (convertView == null) {
        convertView = inflater.inflate(R.layout.row, null);

        holder = new ViewHolder();
        holder.nTitle = (TextView) convertView.findViewById(R.id.listTitle);
        holder.nDate = (TextView) convertView.findViewById(R.id.listDate);
        holder.nCategory = (TextView) convertView.findViewById(R.id.listCategory);
        holder.nImage = (ImageView) convertView.findViewById(R.id.listImage);
        convertView.setTag(holder);
    } else
        holder = (ViewHolder) convertView.getTag();


    if (newsList.get(position) != null) {
        holder.imageUrl = newsList.get(position).image;
        holder.nTitle.setText(newsList.get(position).title);
        holder.nCategory.setText(newsList.get(position).category);
        holder.nDate.setText(Base.getInstance(context).getDateString(newsList.get(position).date));
        if (holder.imageUrl != null && !holder.imageUrl.equals("null")) {
            String thumbUrl = holder.imageUrl.substring(0, holder.imageUrl.lastIndexOf('.')) + "-260x145" + holder.imageUrl.substring(holder.imageUrl.lastIndexOf('.'), holder.imageUrl.length());
            imageView = holder.nImage;
            setImage(thumbUrl);
        }
    }

    return convertView;
}

private static class ViewHolder {
    TextView nTitle;
    TextView nDate;
    TextView nCategory;
    ImageView nImage;
    String imageUrl;
}

public void setImage(String imageUrl) {
    AsyncHttpClient client = new AsyncHttpClient();
    client.get(imageUrl, null, fileHandler);
}

FileAsyncHttpResponseHandler fileHandler = new FileAsyncHttpResponseHandler(context) {
    @Override
    public void onFailure(int statusCode, Header[] headers, Throwable throwable,
                          File response) {
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, File response) {
        imageView.setImageBitmap(BitmapFactory.decodeFile(response.getPath()));
    }
};

回答1:


Try Below code, It might help you to resolve your problem.

public class ListViewCustomAdapter extends..{

   //Map to cache Image Bitmap. Key= imageUrl,value =Image Bitmap
   private Map<String, Bitmap> mBitmapCache = new HashMap<String, Bitmap>();    

   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
      ViewHolder holder;

      if (convertView == null) {
          convertView = inflater.inflate(R.layout.row, null);
          holder = new ViewHolder();
          holder.nTitle = (TextView) convertView.findViewById(R.id.listTitle);
          holder.nDate = (TextView) convertView.findViewById(R.id.listDate);
          holder.nCategory = (TextView) convertView.findViewById(R.id.listCategory);
          holder.nImage = (ImageView) convertView.findViewById(R.id.listImage);
          convertView.setTag(holder);
      } else {
          holder = (ViewHolder) convertView.getTag();
      } 

      if (newsList.get(position) != null) {
          holder.imageUrl = newsList.get(position).image;
          holder.nTitle.setText(newsList.get(position).title);
          holder.nCategory.setText(newsList.get(position).category);
          holder.nDate.setText(Base.getInstance(context).getDateString(newsList.get(position).date));
          if (holder.imageUrl != null && !holder.imageUrl.equals("null")) {
               String thumbUrl = holder.imageUrl.substring(0, holder.imageUrl.lastIndexOf('.')) + "-260x145" + holder.imageUrl.substring(holder.imageUrl.lastIndexOf('.'), holder.imageUrl.length());
               holder.setImage(thumbUrl);
          }
      }
      return convertView;
   }

   private static class ViewHolder {
        TextView nTitle;
        TextView nDate;
        TextView nCategory;
        ImageView nImage;
        String imageUrl;

        public void setImage(String imageUrl) {
           this.imageUrl = imageUrl;
           Bitmap imageBitmap = mBitmapCache.get(imageUrl);
           if(imageBitmap!=null){
               nImage.setImageBitmap(imageBitmap);
           } else {
               AsyncHttpClient client = new AsyncHttpClient();
               client.get(imageUrl, null, fileHandler);
           }
        }

        FileAsyncHttpResponseHandler fileHandler = new FileAsyncHttpResponseHandler(context) {
             @Override
             public void onFailure(int statusCode, Header[] headers, Throwable throwable,
                      File response) {
             }

             @Override
             public void onSuccess(int statusCode, Header[] headers, File response) {
                   Bitmap imageBitmap = BitmapFactory.decodeFile(response.getPath());
                   imageView.setImageBitmap(imageBitmap);
                   mBitmapCache.put(imageUrl, imageBitmap);         
             }
        };
    }
}



回答2:


Your code in

public void setImage() {
    if (imageUrl != null && !imageUrl.equals("null") && !imageUrl.equals("")) {
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(imageUrl, null, fileHandler);
    }
}

looks suspicious: any valid URL will force a reloading as it matches all three conditions in

    imageUrl != null && !imageUrl.equals("null") && !imageUrl.equals("")

Example: http://www.google.com/logo.png is not null, does not equal the string "null" nor the string "", so the if will always be true and the AsyncLoader created. BTW, checking for "null" only makes sense if you are explicitly using that somewhere else in your code. Most probably you only want to check for the null value, not the "null" string.



来源:https://stackoverflow.com/questions/31746539/image-reloaded-when-scroll-listview-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!