当前位置: 首页 > 知识库问答 >
问题:

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

从开济
2023-03-14

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

我已经尝试了这个链接“添加时RecycerView addInArray error”上给出的所有内容,但没有任何帮助。

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);
        }
    }
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_width="0dp"
        android:layout_height="0dp"
        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_width="match_parent"
            android:layout_height="wrap_content">

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/recycler_view"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    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_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:id="@+id/cardLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        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_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/thumbnail"
                android:layout_width="match_parent"
                android:layout_height="150dp"
                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_width="match_parent"
                android:layout_height="wrap_content"
                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_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/nameOfPlace"
                android:layout_marginStart="4dp"
                android:hint="@string/category"
                android:textSize="12sp" />

            <RatingBar
                style="?android:attr/ratingBarStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                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.RecyclerView{42adb848 VFED.V.. ......ID 0,0-540,0 #7f0a00f4 app:id/recycler_view}call 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.RecyclerView{42adb848 VFED.V.. ......ID 0,0-540,2449 #7f0a00f4 app:id/recycler_view}call 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个答案

仉磊
2023-03-14
gridAdapter = new GridAdapter(NearMeListActivity.this, id, placeName, category, lat, lng);
recyclerView.setAdapter(gridAdapter); 
// set the Adapter to RecyclerView
gridAdapter.notifyDataSetChanged();

移除

gridAdapter.notifyDataSetChanged();
 类似资料:
  • 未处理 异常: java.io.FileNotFoundException 测试过文件存在,但放在Scanner里面报错。有佬能帮忙分析下吗

  • 如何使用实现以下功能? 这是完全不一样的,我实际上如何解决?

  • 线程“main”java.lang.ArithmeticException中出现异常:/by zero at run.prg34.main(prg34.java:8) 如何在java中解决上述算法异常?

  • 我正在开发一个Android应用程序,使用ExoPlayer用于视频播放,Glide用于图像显示,以及用于文件下载的下载库,并且它们都具有与HttpURLConnection相关的NullPointerExctive,我确信使用的链接是可用的。 神奇的是,我只是按照这些库的官方留档中描述的方法正常加载数据,这种错误时有发生,三个库可能不会同时抛出NullPointerExctive,我甚至不知道如

  • 我正在尝试将50000条记录插入到一个五节点的卡桑德拉集群中。我正在使用执行异步以提高性能(减少应用程序端的插入时间)。我尝试了具有多个批处理大小的批处理语句,但每次我都遇到以下异常。 我插入了数据,即10000,20000到40000条记录,没有任何问题。以下是我编写的java代码。 其中ps是准备好的语句,batches是批数,batchSize是批中的记录数。 我无法理解这个问题的根本原因。