"指定的孩子已经有父母"在notifyDataSetChanged之后

时间:2016-12-19 15:23:46

标签: android callback

尝试更新我的模拟用户集,并将其反映在我的RecyclerView中。当我在Firebase数据库的回调中添加新数据并在我的notifyDataSetChanged适配器上调用RecyclerView时,我收到错误The specified child already has a parent。有什么想法吗?

我的活动中的相关代码是onCreate

// Initialize Firebase and get mock users from DB
mDatabase = FirebaseDatabase.getInstance().getReference();
final ArrayList<String> userNames = new ArrayList<String>();
DatabaseReference mockUserRef = mDatabase.child("mock_users");

ValueEventListener mockUserListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        userNames.add(dataSnapshot.getValue().toString());
        mRecyclerView.getAdapter().notifyDataSetChanged();
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.w(TAG, "Mock user fetch cancelled");
    }
};

mockUserRef.addListenerForSingleValueEvent(mockUserListener);

// Initialize RecyclerView used to display users
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);

mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);

mAdapter = new UserStackAdapter(userNames);
mRecyclerView.setAdapter(mAdapter);

这是我的UserStackAdapter中的相关代码

private ArrayList<String> mDataset;

static class ViewHolder extends RecyclerView.ViewHolder {
    TextView mTextView;

    ViewHolder(TextView v) {
        super(v);
        mTextView = v;
    }
}

public UserStackAdapter(ArrayList<String> myDataset) {
    mDataset = myDataset;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.my_text_view, parent, false);

    LinearLayout ll = (LinearLayout) v; // get the parent layout view
    TextView tv = (TextView) ll.findViewById(R.id.item_title); // get the child text view

    ViewHolder vh = new ViewHolder(tv);
    return vh;
}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context="io.backlund.roomie.MainActivity">

    <android.support.v7.widget.Toolbar
            android:id="@+id/my_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:elevation="4dp"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <android.support.v7.widget.RecyclerView
            android:id="@+id/my_recycler_view"
            android:scrollbars="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</RelativeLayout>

my_text_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
            android:id="@+id/item_title"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="@android:color/darker_gray"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="8dp"
            android:textSize="22dp" />

</LinearLayout>

调试日志

E/AndroidRuntime: FATAL EXCEPTION: main
Process: io.backlund.roomie, PID: 11149
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
    at android.view.ViewGroup.addViewInner(ViewGroup.java:4417)
    at android.view.ViewGroup.addView(ViewGroup.java:4258)
    at android.view.ViewGroup.addView(ViewGroup.java:4198)
    at android.support.v7.widget.RecyclerView$5.addView(RecyclerView.java:676)
    at android.support.v7.widget.ChildHelper.addView(ChildHelper.java:107)
    at android.support.v7.widget.RecyclerView$LayoutManager.addViewInt(RecyclerView.java:7404)
    at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:7362)
    at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:7350)
    at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1459)
    at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1408)
    at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:580)
    at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3379)
    at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3188)
    at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3632)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at com.android.internal.policy.DecorView.onLayout(DecorView.java:726)
    at android.view.View.layout(View.java:17637)
    at android.view.ViewGroup.layout(ViewGroup.java:5575)
    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6337)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
    at android.view.Choreographer.doCallbacks(Choreographer.java:686)
    at android.view.Choreographer.doFrame(Choreographer.java:621)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

1 个答案:

答案 0 :(得分:1)

我不确定你为什么会收到这个错误。经过多一点挖掘后会更新答案。

我做的改变是,

  • TextView初始化移至ViewHolder
  • 通过了膨胀的视图,view而不是TextView

以下代码将解决错误。

public class UserStackAdapter extends RecyclerView.Adapter<UserStackAdapter.ViewHolder> {
    LayoutInflater inflater;
    private ArrayList<String> mDataset;

    public UserStackAdapter(ArrayList<String> myDataset) {
        mDataset = myDataset;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_text_view, parent, false);
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.mTextView.setText(mDataset.get(position));
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView mTextView;

        ViewHolder(View v) {
            super(v);
            mTextView = (TextView) v.findViewById(R.id.item_title);
        }
    }
}