1

私のリストビューには、個々のカスタム アダプター上の画像の正確な配置が表示されません。AsyncTask を使用して画像を読み込もうとしています。画像が重複することがありますが、その理由はわかりません。ここに私のArrayAdapterコードがあります:

public class NewsPromoAdapter extends ArrayAdapter<NewsPromosDTO> {
    private final Context context;
    List<NewsPromosDTO> npList;
    LayoutInflater inflater;
    Bitmap src;

    public NewsPromoAdapter(Context context, List<NewsPromosDTO> npList) {
        super(context, R.layout.news_and_promos, npList);
        this.context = context;
        this.npList = npList;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public static class ViewHolder {
        TextView nameText;
        TextView date1Text;
        ImageView imageView;
        ProgressBar prg;
        LoadImage loadImg;
    }

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

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.news_and_promos, parent,
                    false);
            holder = new ViewHolder();
            holder.nameText = (TextView) convertView
                    .findViewById(R.id.newspromo_name);
            holder.date1Text = (TextView) convertView
                    .findViewById(R.id.newspromo_date);
            holder.imageView = (ImageView) convertView
                    .findViewById(R.id.newspromo_imageView);
            holder.prg = (ProgressBar) convertView
                    .findViewById(R.id.progressBar1);

            convertView.setTag(holder);
        } else {

            holder = (ViewHolder) convertView.getTag();
            holder.loadImg.cancel(true);
        }

        if (!(npList.get(position).getName().equals(""))) {
            holder.nameText.setVisibility(View.VISIBLE);
            holder.nameText.setText(npList.get(position).getName());

        } else {
            holder.nameText.setVisibility(View.GONE);
        }

        if (!(npList.get(position).getDate().equals(""))) {
            holder.date1Text.setVisibility(View.VISIBLE);
            holder.date1Text.setText(npList.get(position).getDate());

        } else {
            holder.date1Text.setVisibility(View.GONE);
        }

        if (!(npList.get(position).getImageURL().equals(""))) {
            holder.imageView.setVisibility(View.VISIBLE);
            holder.loadImg = new LoadImage(holder.imageView, npList.get(
                    position).getImageURL(), holder);
            holder.loadImg.execute();
        } else {
            holder.imageView.setVisibility(View.GONE);
            holder.prg.setVisibility(View.GONE);
        }

        return convertView;
    }

    class LoadImage extends AsyncTask<Object, Void, Bitmap> {
        ViewHolder viewH;
        private ImageView imv;
        private String url;

        public LoadImage(ImageView imv, String imageURL, ViewHolder viewH) {
            this.imv = imv;
            this.url = imageURL;
            this.viewH = viewH;

        }

        @Override
        protected Bitmap doInBackground(Object... params) {
            BitmapFromURL bmpURL = new BitmapFromURL();
            src = bmpURL.getBitmapFromURL(url);

            return src;
        }

        @Override
        protected void onPostExecute(Bitmap result) {

            // imv.setImageBitmap(result);
            // viewH.prg.setVisibility(View.GONE);
            viewH.prg.setVisibility(View.GONE);

            imv.setImageBitmap(result);

        }
    }

}

ADAPTER を処理するアクティビティは次のとおりです。一部の大規模サイトで使用されているエンドレス リストビュー アプローチを実装しています。Facebook、Twitter などのように、下にスクロールするとリストビューにロードされる新しいアイテム。うまくやれたかどうかはわかりません。

public class ListNewsPromoActivity extends Activity {

    List<NewsPromosDTO> npList;
    String url, user_email;
    Bundle extras;
    int user_points;
    List<Integer> npIDs;
    private ProgressDialog progressDialog;
    BitmapFromURL bmpURL;
    JSONArray users = null;

    String TAG_ID = "id";
    String TAG_NAME = "name";
    String TAG_PHOTO = "photo";
    String TAG_DATE = "date";
    String TAG_DESC = "description";
    ListView list;
    NewsPromoAdapter newsAdapter;

    boolean loadingMore = false;
    private Runnable returnRes;
    int itemsPerPage = 3;
    int currentIndex = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.news_promo_listview);
        list = (ListView) findViewById(R.id.mainView);
        extras = getIntent().getExtras();
        if (extras != null) {

            user_points = extras.getInt("user_points");
            user_email = extras.getString("user_email");
        }
        url = getString(R.string.app_url_news_promos);
        npIDs = new ArrayList<Integer>();
        npList = new ArrayList<NewsPromosDTO>();


        View footerView = ((LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
                R.layout.footer, null, false);

        newsAdapter = new NewsPromoAdapter(ListNewsPromoActivity.this, npList);

        list.addFooterView(footerView);
        list.setAdapter(newsAdapter);

        list.setOnScrollListener(new OnScrollListener() {
            // useless here, skip!
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                    int visibleItemCount, int totalItemCount) {
                // what is the bottom item that is visible
                int lastInScreen = firstVisibleItem + visibleItemCount;
                // is the bottom item visible & not loading more already ? Load
                if ((lastInScreen == totalItemCount) && !(loadingMore)) {
                    Thread thread = new Thread(null, getRunnable());
                    thread.start();

                }
            }
        });

        // Runnable to load the items
        // Since we cant update our UI from a thread this Runnable takes care of
        // that!
        returnRes = new Runnable() {
            @Override
            public void run() {

                // Loop thru the new items and add them to the adapter

                for (NewsPromosDTO np : npList) {
                    System.out.println(np.getName() + " andito ako!!");
                    newsAdapter.add(np);
                }

                newsAdapter.notifyDataSetChanged();


                              // Done loading more.
                loadingMore = false;
            }
        };

    }

    protected class loadNewsPromo extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {

            super.onPreExecute();

        }

        protected String doInBackground(Void... params) {
            // Creating JSON Parser instance

            loadingMore = true;
            JSONParser jParser = new JSONParser();
            JSONObject json;

            if (jParser.checkServer(url)) {
                try {
                    // Getting Array of UserNews
                    json = jParser.getJSONFromUrl(url);
                    users = json.getJSONArray(user_email);
                    // looping through All UserNews

                    for (int i = currentIndex; i < itemsPerPage; i++) {
                        if (itemsPerPage == i) {
                            // currentIndex--;
                            break;
                        } else {
                            JSONObject c = users.getJSONObject(i);
                            // Storing each json item in variable
                            NewsPromosDTO npDTO = new NewsPromosDTO();

                            npDTO.setImageURL(c.getString(TAG_PHOTO));
                            npDTO.setId(c.getInt(TAG_ID));
                            npDTO.setName(c.getString(TAG_NAME));
                            npDTO.setDate(c.getString(TAG_DATE));
                            npDTO.setDescription(c.getString(TAG_DESC));
                            npList.add(npDTO);
                            currentIndex++;
                        }

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    return null;
                } finally {

                }
            } 
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) { //
            // progressDialog.dismiss();
            loadingMore = false;
            list();
        }
    }

    public void list() {
        // add the footer before adding the adapter, else the footer will not
        // load!
        View footerView = ((LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
                R.layout.footer, null, false);

        newsAdapter = new NewsPromoAdapter(ListNewsPromoActivity.this, npList);

        list.addFooterView(footerView);
        list.setAdapter(newsAdapter);
    }



    public Runnable getRunnable() {
        Runnable loadMoreListItems = new Runnable() {
            @Override
            public void run() {
                // Set flag so we cant load new items 2 at the same time
                loadingMore = true;
                // Reset the array that holds the new items

                // Simulate a delay, delete this on a production environment!
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
                // Get 15 new listitems
                JSONParser jParser = new JSONParser();
                JSONObject json;
                npList = new ArrayList<NewsPromosDTO>();
                if (jParser.checkServer(url)) {
                    try {
                        // Getting Array of Contacts
                        json = jParser.getJSONFromUrl(url);
                        users = json.getJSONArray(user_email);
                        // looping through All Contacts

                        // if (itemsPerPage > users.length() - currentIndex) {
                        // itemsPerPage = users.length();
                        // }
                        npList = new ArrayList<NewsPromosDTO>();
                        System.out.println(users.length() + " Laman ng users");
                        int counter = 0;
                        for (int i = currentIndex; i < users.length(); i++) {

                            if (itemsPerPage == counter) {

                                break;
                            } else {
                                JSONObject c = users.getJSONObject(i);
                                // Storing each json item in variable
                                NewsPromosDTO npDTO = new NewsPromosDTO();

                                npDTO.setImageURL(c.getString(TAG_PHOTO));
                                npDTO.setId(c.getInt(TAG_ID));
                                npDTO.setName(c.getString(TAG_NAME));
                                npDTO.setDate(c.getString(TAG_DATE));
                                npDTO.setDescription(c.getString(TAG_DESC));
                                npList.add(npDTO);
                                currentIndex++;
                            }
                            counter++;
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();

                    } finally {

                    }
                }
                // Done! now continue on the UI thread
                runOnUiThread(returnRes);
            }
        };

        return loadMoreListItems;

    }

}
4

0 に答える 0