如何解决 recyclerView Android 中的 addInArray 异常和 removeFromArray 异常?

Posted

技术标签:

【中文标题】如何解决 recyclerView Android 中的 addInArray 异常和 removeFromArray 异常?【英文标题】:How to resolve addInArray exception and removeFromArray exception in recyclerView Android? 【发布时间】:2019-12-28 11:50:28 【问题描述】:

每当我尝试将自定义回收站视图中的数据加载为网格布局时,视图会突然消失,但有时它会完美地加载数据。我在滑动刷新布局下的嵌套滚动视图下使用了回收器视图。

我已经尝试了此链接“RecyclerView addInArray error when adding”上提供的所有内容,但没有任何帮助。

protected void onCreate(@Nullable Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.near_me_list_layout);

recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(NearMeListActivity.this, 2);
        recyclerView.setLayoutManager(mLayoutManager);
        //recyclerView.setAdapter(gridAdapter);

NearMeListActivity.requestSingleUpdate(this, new NearMeListActivity.LocationCallback() 
            @Override
            public void onNewLocationAvailable(GPSCoordinates location) 
                if (location != null) 
                    latitude = location.latitude;
                    longitude = location.longitude;
                    Log.d("Location", "my location is " + location.toString());
                    System.out.println("lat:" + latitude + ".....lng:" + longitude);
                    fetchItems(latitude, longitude);
                
            
        );

swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.darkBlue);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() 
            @Override
            public void onRefresh() 
                //fetchingData.setVisibility(View.INVISIBLE);
                checkLocationEnable();
                id.clear();
                placeName.clear();
                category.clear();
                lat.clear();
                lng.clear();
                NearMeListActivity.requestSingleUpdate(NearMeListActivity.this, new NearMeListActivity.LocationCallback() 
                    @Override
                    public void onNewLocationAvailable(GPSCoordinates location) 
                        if (location != null) 
                            latitude = location.latitude;
                            longitude = location.longitude;
                            System.out.println("lat:" + latitude + ".....lng:" + longitude);
                            loadCategories();
                            fetchItems(latitude, longitude);
                         else 
                            swipeRefreshLayout.setRefreshing(false);
                        
                    
                );
            
        );


private void fetchItems(double latitude, double longitude) 
        if (ConnectivityUtils.isConnectedMobile(this) || ConnectivityUtils.isConnectedWifi(this)) 
            AsyncHttpClient client = new AsyncHttpClient();
            String near_me = PropertyReader.getProperty("near_me", this) + "lat=" + latitude + "&long=" + longitude;
            client.get(near_me, new JsonHttpResponseHandler() 
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) 
                    try 
                        if (!response.getString("data").equals("null")) 
                            noData.setVisibility(View.INVISIBLE);
                            JSONArray getData = response.getJSONArray("data");
                            for (int i = 0; i < getData.length(); i++) 
                                JSONObject data = getData.getJSONObject(i);
                                id.add(data.getInt("id"));
                                placeName.add(data.getString("place_name"));
                                category.add(data.getString("category"));
                                lat.add(data.getString("latitude"));
                                lng.add(data.getString("longitude"));
                            
                            gridAdapter = new GridAdapter(NearMeListActivity.this, id, placeName, category, lat, lng);
                            recyclerView.setAdapter(gridAdapter); // set the Adapter to RecyclerView
                            gridAdapter.notifyDataSetChanged();
                            int resId = R.anim.layout_animation_fall_down;
                            LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(NearMeListActivity.this, resId);
                            recyclerView.setLayoutAnimation(animation);
                            fetchingData.setVisibility(View.INVISIBLE);
                         else 
                            noData.setVisibility(View.VISIBLE);
                            fetchingData.setVisibility(View.INVISIBLE);
                        
                     catch (Exception e) 
                        e.printStackTrace();
                    
                

                @Override
                public void onFinish() 
                    swipeRefreshLayout.setRefreshing(false);
                

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) 
                    Toast.makeText(NearMeListActivity.this, R.string.isOnline, Toast.LENGTH_SHORT).show();
                    swipeRefreshLayout.setRefreshing(false);
                    fetchingData.setVisibility(View.INVISIBLE);
                
            );
         else 
            Toast.makeText(NearMeListActivity.this, R.string.isOnline, Toast.LENGTH_SHORT).show();
            swipeRefreshLayout.setRefreshing(false);
            fetchingData.setVisibility(View.INVISIBLE);
        
    

我的自定义recyclerView:

class GridAdapter extends RecyclerView.Adapter<GridAdapter.MyViewHolder> 

        final private Context context;
        final private ArrayList<Integer> id;
        final private ArrayList<String> nameOfPlace, category;
        final private ArrayList<String> longitudes;
        final private ArrayList<String> latitudes;

        GridAdapter(Context context, ArrayList<Integer> id, ArrayList<String> nameOfPlace, ArrayList<String> category, ArrayList<String> latitudes, ArrayList<String> longitudes) 
            this.context = context;
            this.id = id;
            this.nameOfPlace = nameOfPlace;
            this.category = category;
            this.latitudes = latitudes;
            this.longitudes = longitudes;
        

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 
            // inflate the item Layout
            View view;
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_list_layout, parent, false);
            return new MyViewHolder(view);
        

        @Override
        public void onBindViewHolder(@NonNull GridAdapter.MyViewHolder myViewHolder, int position) 
            Glide.with(context).load(PropertyReader.getProperty("get_img", context) + "location_id=" + id.get(position)).into(myViewHolder.thumbnail);
            myViewHolder.nameOfPlace.setText(nameOfPlace.get(position));
            myViewHolder.category.setText(category.get(position));
            final String destLat = latitudes.get(position);
            final String destLng = longitudes.get(position);

            myViewHolder.itemView.setOnClickListener(new View.OnClickListener() 
                @Override
                public void onClick(View view) 
                    String uri = "http://maps.google.com/maps?daddr=" + destLat + "," + destLng;
                    Intent mapIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                    mapIntent.setPackage("com.google.android.apps.maps");
                    context.startActivity(mapIntent);
                
            );
        

        @Override
        public int getItemCount() 
            return id.size();
        

        class MyViewHolder extends RecyclerView.ViewHolder 
            ImageView thumbnail;
            TextView nameOfPlace, category;

            MyViewHolder(View view) 
                super(view);
                thumbnail = view.findViewById(R.id.thumbnail);
                nameOfPlace = view.findViewById(R.id.nameOfPlace);
                category = view.findViewById(R.id.category);
            
        
    

我的布局:

<android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeRefresh"
        android:layout_
        android:layout_
        app:layout_constraintBottom_toTopOf="@id/spinner"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/toolbar">

        <android.support.v4.widget.NestedScrollView
            android:layout_
            android:layout_>

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/recycler_view"
                    android:layout_
                    android:layout_
                    android:clipToPadding="false"
                    android:scrollbars="vertical"
                    android:orientation="vertical"/>

        </android.support.v4.widget.NestedScrollView>

    </android.support.v4.widget.SwipeRefreshLayout>

项目视图:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:id="@+id/cardLayout"
        android:layout_
        android:layout_
        android:layout_gravity="center"
        android:layout_margin="4dp"
        android:elevation="8dp"
        android:focusable="true"
        android:foreground="?attr/selectableItemBackground"
        card_view:cardCornerRadius="4dp">

        <RelativeLayout
            android:layout_
            android:layout_>

            <ImageView
                android:id="@+id/thumbnail"
                android:layout_
                android:layout_
                android:background="?attr/selectableItemBackgroundBorderless"
                android:contentDescription="@string/image_of_place"
                android:focusable="true"
                android:scaleType="fitXY" />

            <TextView
                android:id="@+id/nameOfPlace"
                style="@style/TextAppearance.AppCompat.Subhead"
                android:layout_
                android:layout_
                android:layout_below="@id/thumbnail"
                android:layout_marginStart="4dp"
                android:layout_marginTop="2dp"
                android:hint="@string/name_of_place1"
                android:maxLines="2"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/category"
                style="@style/TextAppearance.AppCompat.Caption"
                android:layout_
                android:layout_
                android:layout_below="@id/nameOfPlace"
                android:layout_marginStart="4dp"
                android:hint="@string/category"
                android:textSize="12sp" />

            <RatingBar
                style="?android:attr/ratingBarStyleSmall"
                android:layout_
                android:layout_
                android:layout_below="@id/category"
                android:layout_marginStart="4dp"
                android:layout_marginBottom="4dp"
                android:layout_marginTop="4dp"
                android:numStars="5"
                android:rating="2.0"
                android:stepSize="1.0" />
        </RelativeLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

错误:

D/ViewGroup: addInArray been called, this = android.support.v7.widget.RecyclerView42adb848 VFED.V.. ......ID 0,0-540,0 #7f0a00f4 app:id/recycler_viewcall stack =
    java.lang.Throwable: addInArray
        at android.view.ViewGroup.addInArray(ViewGroup.java:3786)
        at android.view.ViewGroup.addViewInner(ViewGroup.java:3740)
        at android.view.ViewGroup.addView(ViewGroup.java:3564)
        at android.view.ViewGroup.addView(ViewGroup.java:3509)
        at android.support.v7.widget.RecyclerView$5.addView(RecyclerView.java:851)
        at android.support.v7.widget.ChildHelper.addView(ChildHelper.java:107)
        at android.support.v7.widget.RecyclerView$LayoutManager.addViewInt(RecyclerView.java:8336)
        at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:8294)
        at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:8282)
        at android.support.v7.widget.GridLayoutManager.layoutChunk(GridLayoutManager.java:580)
        at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at android.support.v7.widget.GridLayoutManager.onLayoutChildren(GridLayoutManager.java:171)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924)
        at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3336)
        at android.view.View.measure(View.java:16834)
        at android.support.v4.widget.NestedScrollView.measureChildWithMargins(NestedScrollView.java:1502)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
        at android.support.v4.widget.NestedScrollView.onMeasure(NestedScrollView.java:556)
        at android.view.View.measure(View.java:16834)
        at android.support.v4.widget.SwipeRefreshLayout.onMeasure(SwipeRefreshLayout.java:641)
        at android.view.View.measure(View.java:16834)
        at android.support.constraint.ConstraintLayout$Measurer.deprecatedMeasure(ConstraintLayout.java:865)
        at android.support.constraint.solver.widgets.analyzer.BasicMeasure.simpleSolverMeasure(BasicMeasure.java:232)
        at android.support.constraint.solver.widgets.ConstraintWidgetContainer.measure(ConstraintWidgetContainer.java:102)
        at android.support.constraint.ConstraintLayout.resolveSystem(ConstraintLayout.java:1556)
        at android.support.constraint.ConstraintLayout.onMeasure(ConstraintLayout.java:1588)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
        at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5374)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2368)
        at android.view.View.measure(View.java:16834)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2246)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1312)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1509)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1189)
D/ViewGroup: removeFromArray been called, this = android.support.v7.widget.RecyclerView42adb848 VFED.V.. ......ID 0,0-540,2449 #7f0a00f4 app:id/recycler_viewcall stack =
    java.lang.Throwable: removeFromArray
        at android.view.ViewGroup.removeFromArray(ViewGroup.java:3833)
        at android.view.ViewGroup.detachViewFromParent(ViewGroup.java:4401)
        at android.support.v7.widget.RecyclerView.access$100(RecyclerView.java:207)
        at android.support.v7.widget.RecyclerView$5.detachViewFromParent(RecyclerView.java:941)
        at android.support.v7.widget.ChildHelper.detachViewFromParent(ChildHelper.java:284)
        at android.support.v7.widget.RecyclerView$LayoutManager.detachViewInternal(RecyclerView.java:8526)
        at android.support.v7.widget.RecyclerView$LayoutManager.detachViewAt(RecyclerView.java:8519)
        at android.support.v7.widget.RecyclerView$LayoutManager.scrapOrRecycleView(RecyclerView.java:8947)
        at android.support.v7.widget.RecyclerView$LayoutManager.detachAndScrapAttachedViews(RecyclerView.java:8930)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:580)
        at android.support.v7.widget.GridLayoutManager.onLayoutChildren(GridLayoutManager.java:171)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3647)
        at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:4194)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4862)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
        at android.support.v4.widget.NestedScrollView.onLayout(NestedScrollView.java:1733)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4862)
        at android.support.v4.widget.SwipeRefreshLayout.onLayout(SwipeRefreshLayout.java:625)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4862)
        at android.support.constraint.ConstraintLayout.onLayout(ConstraintLayout.java:1762)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4862)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4862)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1888)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1742)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1651)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4862)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4862)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1888)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1742)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1651)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4862)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:450)
        at android.view.View.layout(View.java:15125)
        at android.view.ViewGroup.layout(ViewGroup.java:4862)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2317)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2023)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1189)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6223)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
        at android.view.Choreographer.doCallbacks(Choreographer.java:591)
        at android.view.Choreographer.doFrame(Choreographer.java:560)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Ch

我希望数据在给定的布局条件下完美加载。

【问题讨论】:

【参考方案1】:
gridAdapter = new GridAdapter(NearMeListActivity.this, id, placeName, category, lat, lng);
recyclerView.setAdapter(gridAdapter); 
// set the Adapter to RecyclerView
gridAdapter.notifyDataSetChanged();

删除

gridAdapter.notifyDataSetChanged();

【讨论】:

recyclerView.setLayoutAnimation(animation);您可以尝试删除它吗? 仍然遇到同样的问题@hfarhanahmed 你也可以分享你的项目布局吗? 我分享了我的视图布局@hfarhanahmed

以上是关于如何解决 recyclerView Android 中的 addInArray 异常和 removeFromArray 异常?的主要内容,如果未能解决你的问题,请参考以下文章

我们如何在 android 的 RecyclerView 片段中使用 bottomSheet?

一起Talk Android吧(第五百零一回:如何正确地更新RecyclerView中的数据)

如何将json数据从json数组解析到recyclerview java android?

RecyclerView 动画问题 Android Kotlin

Android SwipeRefreshLayout RecyclerView冲突下拉冲突的解决方案

Android之解决NestedScrollView嵌套RecyclerView部分手机返回到这个页面Recyclerview顶部,而不是页面NestedScrollView顶部