Массив изображений петлиется в каждом элементе в моем списке объектов массива

Peter спросил: 03 февраля 2018 в 12:01 в: java

Пожалуйста, помогите мне. Я получаю изображение из JSON API в свое приложение для Android для каждого элемента в моем arraylist. Изображения правильно выбираются, но вместо того, чтобы устанавливать только изображение, предназначенное для каждого элемента списка, оно циклически перемещает и заменяет все изображения во всем списке по одному элементу и всем элементам списка соответственно, тем самым делая изображение в каждом списке элемент, который нужно переключать на разные изображения в секундах.

См. файл JSON

{  "data":[  
  {  
     "sno":1,
     "id":"3",
     "title":"This Is Great Again",
     "desc":"The details of how a UUID is generated are determined by the device manufacturer and are specific to the device's platform or model.The details of...",
     "free":"Yes",
     "image":"http:\/\/app-web.moneyacademy.ng\/uploads\/145277f3d0499ee8e0dafbac384ca9b4.jpg",
     "date_added":"2017-10-12 10:26PM",
     "no_comment":3,
     "comments":[  ]
  },
  {  
     "sno":2,
     "id":"6",
     "title":"Money Makes The World Go Round",
     "desc":"On this realm, nothing works without money. You need to get some of it or else you'll be grounded.",
     "free":"Yes",
     "image":"http:\/\/app-web.moneyacademy.ng\/uploads\/546a4c29a94f3d70ae9a075ce8afcc6b.jpg",
     "date_added":"2018-02-18 10:06AM",
     "no_comment":0,
     "comments":[  ]
  },
  {  
     "sno":3,
     "id":"7",
     "title":"No One Is Destined To Be Poor",
     "desc":"You will not be poor.",
     "free":"Yes",
     "image":"http:\/\/app-web.moneyacademy.ng\/uploads\/8f19b9cebd1ca4dec74fafcfe23ae0f0.jpg",
     "date_added":"2018-02-18 01:03PM",
     "no_comment":0,
     "comments":[  ]
  },
  {  
     "sno":4,
     "id":"8",
     "title":"What Is Your Money?",
     "desc":"Understand the true definition of your money.",
     "free":"Yes",
     "image":"http:\/\/app-web.moneyacademy.ng\/uploads\/49b35ffb5cabcb7e01dab2d452ec6025.jpg",
     "date_added":"2018-02-18 01:30PM",
     "no_comment":0,
     "comments":[  ]
  },                

Вот мой код для извлечения каждого элемента и изображения

private static ArrayList<nauget> extractFeatureFromJson(String freeNaugetJson) {
    // If the JSON string is empty or null, then return early.
    if (TextUtils.isEmpty(freeNaugetJson)) {
        return null;
    }    ArrayList<nauget> naugets = new ArrayList<nauget>();    try {        JSONObject baseJsonResponse = new JSONObject(freeNaugetJson);
        JSONArray dataArray = baseJsonResponse.getJSONArray("data");        // If there are results in the data array
        for (int i = 0; i < dataArray.length(); i++){            String title = dataArray.getJSONObject(i).getString("title");
            String body = dataArray.getJSONObject(i).getString("desc");
            String totalComments = dataArray.getJSONObject(i).getString("no_comment");
            String image = dataArray.getJSONObject(i).getString("image");
            int id = dataArray.getJSONObject(i).getInt("id");            ArrayList<Comment> comments = new ArrayList<Comment>();            //fetch each comment detail
            if (Integer.parseInt(totalComments) > 0) {
                JSONArray commentArray = dataArray.getJSONObject(i).getJSONArray("comments");                for (int j = 0; j < commentArray.length(); j++) {
                    String userName = commentArray.getJSONObject(j).getString("userName");
                    String comment_image = commentArray.getJSONObject(j).getString("userPhoto");
                    String comment = commentArray.getJSONObject(j).getString("comment");
                    String date = commentArray.getJSONObject(j).getString("date_commented");                    comments.add(new Comment(userName, comment_image, comment, date));
                }
            }            // Create a new nauget object
            naugets.add(new nauget(title, body, image, totalComments, comments, id));
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Problem parsing the nauget JSON results", e);
    }    return naugets;
}

Вот мой код адаптера, где я устанавливаю изображение и его текстовые данные для каждого элемента списка.

 public class NaugetAddapter extends ArrayAdapter<nauget> {    ArrayList<nauget> naugets;
    private nauget currentNauget;
    private ImageView naugetImage;    private TextView naugetTitle;
    private TextView naugetBody;
    private TextView commentCount;    public NaugetAddapter(@NonNull Context context, ArrayList<nauget> naugets) {
        super(context, 0, naugets);
    }    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        //check if the convert view is null and inflate the view
        if (convertView == null){
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.free_nauget_item, parent, false);
        }        currentNauget = (nauget) getItem(position);        //find the nauget title textView and set the text
        naugetTitle = (TextView) convertView.findViewById(R.id.nauget_title);
        naugetTitle.setText(currentNauget.getNauget_title());        //find the nauget body textView and set the text
        naugetBody = (TextView) convertView.findViewById(R.id.nauget_body);
        naugetBody.setText(currentNauget.getNauget_body());        //set the nauget total comment count
        commentCount = (TextView) convertView.findViewById(R.id.comment_count);
        commentCount.setText(currentNauget.getNaugetTotalComments());        //set the comment text
        TextView commentText = (TextView) convertView.findViewById(R.id.comment_text);
        commentText.setText(currentNauget.getNaugetCommentText());        //set the nauget image
        naugetImage = (ImageView) convertView.findViewById(R.id.nauget_image);
        new DownloadImageTask().execute(currentNauget.getImageUrl());        //set the share icon
        ImageView shareIcon = (ImageView) convertView.findViewById(R.id.share_icon);
        shareIcon.setImageResource(currentNauget.getNaugetShareIcon());        //set share functionality on the share icon
        shareIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent shareIntent = new Intent(Intent.ACTION_SEND);
                shareIntent.setType("text/plain");
                shareIntent.putExtra(Intent.EXTRA_SUBJECT, "My App");
                shareIntent.putExtra(Intent.EXTRA_TEXT,
                        naugetTitle.getText()
                        + "\n" + naugetBody.getText()
                        + "\n" + naugetImage.getDrawable());
                startActivity(getContext(), Intent.createChooser(shareIntent, "Share via"), null);
            }
        });        return convertView;
    }    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {        @Override
        protected void onPreExecute() {
            super.onPreExecute();
//            mLoadingIndicator.setVisibility(View.VISIBLE);
        }        protected Bitmap doInBackground(String... urls) {
            Bitmap image = null;
            HttpURLConnection urlConnection = null;
            try {URL url = new URL(urls[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                int statusCode = urlConnection.getResponseCode();
                if (statusCode != 200) {
                    return null;
                }                InputStream inputStream = urlConnection.getInputStream();
                if (inputStream != null) {
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    return bitmap;
                }
            } catch (Exception e) {
                urlConnection.disconnect();
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }
            return null;
        }        protected void onPostExecute(Bitmap result) {
//            mLoadingIndicator.setVisibility(View.INVISIBLE);
            naugetImage.setImageBitmap(result);
        }
    }    @NonNull
    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                ArrayList<nauget> filteredResults = new ArrayList<>();                FilterResults results = new FilterResults();
                results.values = filteredResults;
                return results;
            }            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {            }
        };
    }    void setFilter(ArrayList<nauget> listItem){
        naugets = new ArrayList();
        naugets.addAll(listItem);
        notifyDataSetChanged();
    }}

0 ответов