简体   繁体   English

ArrayList 中需要不同的元素<modelclass></modelclass>

[英]Need different elements in ArrayList<ModelClass>

I am developing an app in android studio that takes movie names and places them onto cards that swipe left and right.我正在 android 工作室开发一个应用程序,该应用程序获取电影名称并将它们放置在左右滑动的卡片上。 I am having a problem with my MovieList, it will populate but the same movie name goes into it 20 times rather than what I want which is 20 different movie names from the TMDB API.我的 MovieList 有问题,它会填充但相同的电影名称会出现 20 次,而不是我想要的,即来自 TMDB API 的 20 个不同的电影名称。 I just created this new MyAdapter class also.我刚刚也创建了这个新的 MyAdapter class。 So I am not sure why I am not getting different elements into the list.所以我不确定为什么我没有将不同的元素放入列表中。 When I use string instead of my MovieModelClass it gets different elements.当我使用字符串而不是我的 MovieModelClass 时,它会得到不同的元素。 OnPostExecute is where I loop through the title and add it to the array OnPostExecute 是我遍历标题并将其添加到数组的地方

Heres my MainActivity这是我的 MainActivity

public class MainActivity extends AppCompatActivity {
    private MyAdapter adapter;
    private ArrayList<MovieModelClass> movieList = new ArrayList<>();
  
    SwipeFlingAdapterView flingContainer;

    private static String JSON_URL = "https://api.themoviedb.org/3/movie/popular?api_key=8099f5720bad1f61f020fdbc855f73db";
    //List<MovieModelClass> movieList;
    //@InjectView(R.id.frame) SwipeFlingAdapterView flingContainer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
        
        GetData getData = new GetData();
        getData.execute();

     
        flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
           
            @Override
            public void removeFirstObjectInAdapter() {
              
              Log.d("LIST", "removed object!");
               movieList.remove(0);
              adapter.notifyDataSetChanged();
            }

            @Override
            public void onLeftCardExit(Object dataObject) {
                
                Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onRightCardExit(Object dataObject) {
                Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAdapterAboutToEmpty(int itemsInAdapter) {
            
            }

            @Override
            public void onScroll(float scrollProgressPercent) {
              
            }


        });

        // Optionally add an OnItemClickListener
        flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
            @Override
            public void onItemClicked(int itemPosition, Object dataObject) {
                Toast.makeText(MainActivity.this, "click", Toast.LENGTH_SHORT).show();
            }
        });


    }

    public class GetData extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... strings) {

            String current = "";

            try {
                URL url;
                HttpURLConnection urlConnection = null;

                try {

                    url = new URL(JSON_URL);
                    urlConnection = (HttpURLConnection) url.openConnection();

                    InputStream is = urlConnection.getInputStream();
                    InputStreamReader isr = new InputStreamReader(is);

                    int data = isr.read();
                    while (data != -1) {
                        current += (char) data;
                        data = isr.read();
                    }

                    return current;

                } catch (MalformedURLException e) {
                    e.printStackTrace();;
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (urlConnection != null) {
                        //  urlConnection.disconnect();
                    }
                }

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

            return current;
        }

        @Override
        protected void onPostExecute(@org.jetbrains.annotations.NotNull String s){

            try{
                JSONObject jsonObject = new JSONObject(s);
                JSONArray jsonArray = jsonObject.getJSONArray("results");

                movieList = new ArrayList<>();

                MovieModelClass model = new MovieModelClass();

                for(int i = 0; i< jsonArray.length(); i++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                   
                     model.setName(jsonObject1.getString("title"));
                                
                    movieList.add(model);
                }
         

                adapter = new MyAdapter(MainActivity.this, R.layout.item, movieList);
                flingContainer.setAdapter(adapter);
                adapter.notifyDataSetChanged();


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


        }
    }


and this is MyAdapter class which I use for the arrayAdapter这是我用于 arrayAdapter 的 MyAdapter class

public class MyAdapter extends ArrayAdapter {

    public MyAdapter(Context context, int resource, ArrayList<MovieModelClass> objects) {
        super(context, resource, objects);
    }


    public View getView(int position, View convertView, ViewGroup parent) {


       MovieModelClass movies = (MovieModelClass) getItem(position);

       if(convertView == null)
       {
           convertView = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
       }

       TextView name = (TextView) convertView.findViewById(R.id.name);

       name.setText(movies.getName());

       return convertView ;
    }
}

and my model class和我的 model class

public class MovieModelClass {
    String name;

    public MovieModelClass(String id) {
        this.name = name;  
    }
    public MovieModelClass() {

    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
}

Java reference variable will point an Object unless reassigned Java 参考变量将指向 Object 除非重新分配

The code below下面的代码

  1. creates a single model object MovieModelClass model = new MovieModelClass();创建单个 model object MovieModelClass model = new MovieModelClass(); and assigns to reference model并分配给参考model
  2. inside the for loop, the same object is updated and added to arraylist在 for 循环内,同样的 object 被更新并添加到 arraylist
  3. this results in multiple occurrence of the same object inside List (its only a single object that is referenced multiple times inside the List)这会导致 List 内多次出现相同的 object(它只有一个 object 在List内被多次引用)
movieList = new ArrayList<>();

MovieModelClass model = new MovieModelClass();

for(int i = 0; i< jsonArray.length(); i++) {
  JSONObject jsonObject1 = jsonArray.getJSONObject(i);
  model.setName(jsonObject1.getString("title"));
  movieList.add(model);
}

Especially, this part of the MovieModelClass model = new MovieModelClass();特别是 MovieModelClass 的这一部分MovieModelClass model = new MovieModelClass(); should be moved inside the loop应该在循环内移动

Fix使固定

movieList = new ArrayList<>();
for(int i = 0; i< jsonArray.length(); i++) {
  JSONObject jsonObject1 = jsonArray.getJSONObject(i);
  MovieModelClass model = new MovieModelClass();
  model.setName(jsonObject1.getString("title"));
  movieList.add(model);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 是否可以使用ArrayList执行AsyncTask <ModelClass> 作为Android中的参数? - Is it Possible to execute AsyncTask with ArrayList<ModelClass> as parameter in android? 具有不同类型元素的复杂ArrayList - Complex ArrayList with different type elements 将不同类型的元素添加到 arraylist - Adding elements of different type to arraylist 需要从ArrayLists的ArrayList中删除元素<Double> - Need to remove elements from an ArrayList of ArrayLists<Double> 需要将元素从网络传输到数组列表 - Need to transfer Elements from the web to an arraylist 如何将 Arraylist 的最后 3 个元素添加到不同的 Arraylist? - How can I add the last 3 elements of an Arraylist to a different Arraylist? java arrayList不同地对待不同元素 - java arrayList treating different elements differently 如何将ArrayList中的元素更改为其他对象类型? - How to change elements in the ArrayList to a different object type? 发出将元素从其他类添加到ArrayList的问题 - Issue adding elements to an ArrayList from a different class 如何添加一个ArrayList <Integer> 到ArrayList <ArrayList<Integer> &gt;一次又一次地使用ArrayList中的不同元素 <Integer> - How to add an ArrayList<Integer> to an ArrayList<ArrayList<Integer>> again and again with different elements in ArrayList<Integer>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM