对Fragment的活动,getArgument返回null

时间:2017-10-05 19:13:04

标签: java android android-fragments

我正在尝试从mMeetingKeyView.class传递字符串“PostListFragment.class”,但该包正在返回null。我检查了View.class中的包,它不是空的。当我在PostListFragment.class中检查捆绑包时,它会一直返回null

代码主要来自“Firebase Quickstart for Database”。

感谢您的帮助。

View.class

  public class View extends BaseActivity {
    private FragmentPagerAdapter mPagerAdapter;
    private ViewPager mViewPager;
    private String mMeetingKey;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_posts);
        mViewPager = findViewById(R.id.container);
        mMeetingKey=getIntent().getStringExtra("meetingKey");

        Bundle bundle = new Bundle();
        bundle.putString("mMeetingKey", mMeetingKey);
        PostListFragment postListFragment=new PostListFragment();
         postListFragment.setArguments(bundle);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.container,postListFragment).commit();

        mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            private final Fragment[] mFragments = new Fragment[] {
                    new PostListFragment(),
                   // new MyPostsFragment(),
                   // new CompletedPostFragment(),
            };
            private final String[] mFragmentNames = new String[] {
                    getString(R.string.heading_recent),
                    //getString(R.string.heading_my_posts),
                    //getString(R.string.heading_completed_posts)
            };
            @Override
            public Fragment getItem(int position) {
                return mFragments[position];
            }
            @Override
            public int getCount() {
                return mFragments.length;
            }
            @Override
            public CharSequence getPageTitle(int position) {
                return mFragmentNames[position];
            }
        };

        mViewPager.setAdapter(mPagerAdapter);
        TabLayout tabLayout = findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        Toast.makeText(this,mMeetingKey,Toast.LENGTH_LONG).show();


        // Button launches NewPostActivity
        findViewById(R.id.fab_new_post).setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(android.view.View v) {
                Intent intent = new Intent(View.this, NewPostActivity.class);
                intent.putExtra("mMeetingKey",mMeetingKey);
                startActivity(intent);
            }
        });
    }

}

PostListFragment.class

    public class PostListFragment extends android.support.v4.app.Fragment {

    private static final String TAG = "PostListFragment";

    // [START define_database_reference]
    private DatabaseReference mDatabase;
    // [END define_database_reference]
    private String mMeetingKey;
    private FirebaseRecyclerAdapter<Post, PostViewHolder> mAdapter;
    private RecyclerView mRecycler;
    private String meetingKeyRef;
    private LinearLayoutManager mManager;
    public PostListFragment() {}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Override
    public View onCreateView (LayoutInflater inflater, ViewGroup container,
                              Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View rootView = inflater.inflate(R.layout.fragment_all_post, container, false);
        Bundle bundle = this.getArguments();
        if (bundle != null) {
            meetingKeyRef = bundle.getString("mMeetingKey").toString();
        }
      if (bundle!= null) {
          meetingKeyRef = this.getArguments().getString("mMeetingKey");
      }

        if (bundle == null) {
            throw new IllegalArgumentException("Bundle is null");
        }

        // [START create_database_reference]
        mDatabase = FirebaseDatabase.getInstance().getReference().child(meetingKeyRef);
        // [END create_database_reference]

        mRecycler = rootView.findViewById(R.id.messages_list);
        mRecycler.setHasFixedSize(true);

        return rootView;
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Set up Layout Manager, reverse layout
        mManager = new LinearLayoutManager(getActivity());
        mManager.setReverseLayout(true);
        mManager.setStackFromEnd(true);
        mRecycler.setLayoutManager(mManager);

        // Set up FirebaseRecyclerAdapter with the Query
        Query postsQuery = getQuery(mDatabase);
        mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(Post.class, R.layout.item_post,
                PostViewHolder.class, postsQuery) {
            @Override
            protected void populateViewHolder(final PostViewHolder viewHolder, final Post model, final int position) {
                final DatabaseReference postRef = getRef(position);
                mMeetingKey= postRef.getKey();
                // Set click listener for the whole post view
                final String postKey = postRef.child(mMeetingKey).getKey();
                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // Launch PostDetailActivity
                        Intent intent = new Intent(getActivity(), PostDetailActivity.class);
                        intent.putExtra(PostDetailActivity.EXTRA_POST_KEY, postKey);
                        intent.putExtra(PostDetailActivity.EXTRA_MEETING_KEY,mMeetingKey);
                        startActivity(intent);
                    }
                });

                // Determine if the current user has liked this post and set UI accordingly
                if (model.boxCount==1) {
                    viewHolder.boxView.setImageResource(R.drawable.ic_toggle_check_box_checked);
                } else {
                    viewHolder.boxView.setImageResource(R.drawable.ic_toggle_check_box_outline);
                }

                // Bind Post to ViewHolder, setting OnClickListener for the star button
                viewHolder.bindToPost(model, new View.OnClickListener() {
                    @Override
                    public void onClick(View boxView) {
                        // Need to write to both places the post is stored
                        DatabaseReference globalPostRef = mDatabase.child("posts").child(postRef.getKey());
                        DatabaseReference userPostRef = mDatabase.child("user-posts").child(model.uid).child(postRef.getKey());

                        // Run two transactions
                        onBoxClicked(globalPostRef);
                        onBoxClicked(userPostRef);
                    }
                });
            }
        };
        mRecycler.setAdapter(mAdapter);
    }
    // [START post_stars_transaction]
    private void onBoxClicked(DatabaseReference postRef) {
        postRef.runTransaction(new Transaction.Handler() {
            @Override
            public Transaction.Result doTransaction(MutableData mutableData) {
                Post p = mutableData.getValue(Post.class);
                if (p == null) {
                    return Transaction.success(mutableData);
                }

                if (p.checkbox.containsKey(getUid())) {
                    // Unstar the post and remove self from stars
                    p.boxCount = 0;
                    p.checkbox.remove(getUid());
                } else {
                    // Star the post and add self to stars
                    p.boxCount = 1;
                    p.checkbox.put(getUid(), true);
                }



                // Set value and report transaction success
                mutableData.setValue(p);
                return Transaction.success(mutableData);
            }

            @Override
            public void onComplete(DatabaseError databaseError, boolean b,
                                   DataSnapshot dataSnapshot) {
                // Transaction completed
                Log.d(TAG, "postTransaction:onComplete:" + databaseError);
            }
        });
    }
    // [END post_stars_transaction]

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mAdapter != null) {
            mAdapter.cleanup();
        }
    }

    public String getUid() {
        return FirebaseAuth.getInstance().getCurrentUser().getUid();
    }

    public Query getQuery(DatabaseReference databaseReference){
        Query recentPostsQuery = databaseReference.child("posts")
                .limitToFirst(100);
        // [END recent_posts_query]

        return recentPostsQuery;
    }
}

activity_view_posts.xml

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

<android.support.design.widget.TabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/tabs"/>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab_new_post"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_margin="16dp"
    android:src="@drawable/ic_create"
    app:backgroundTint="@android:color/holo_orange_dark" />

fragment_all_post.xml

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".checklist.View">

<android.support.v7.widget.RecyclerView
    android:id="@+id/messages_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentTop="true"
    android:clipToPadding="false"
    android:padding="5dp"
    android:scrollbars="vertical"
    tools:listitem="@layout/item_post" />

1 个答案:

答案 0 :(得分:0)

您正在使用ViewPager,那么为什么要用片段替换容器。删除该代码并使用以下代码View

    public class View extends BaseActivity {
private FragmentPagerAdapter mPagerAdapter;
private ViewPager mViewPager;
private String mMeetingKey;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_posts);
    mViewPager = findViewById(R.id.container);
    mMeetingKey=getIntent().getStringExtra("meetingKey");

    Bundle bundle = new Bundle();
    bundle.putString("mMeetingKey", mMeetingKey);
    PostListFragment postListFragment=new PostListFragment();
     postListFragment.setArguments(bundle);


    mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
        private final Fragment[] mFragments = new Fragment[] {
                postListFragment ,
               // new MyPostsFragment(),
               // new CompletedPostFragment(),
        };
        private final String[] mFragmentNames = new String[] {
                getString(R.string.heading_recent),
                //getString(R.string.heading_my_posts),
                //getString(R.string.heading_completed_posts)
        };
        @Override
        public Fragment getItem(int position) {
            return mFragments[position];
        }
        @Override
        public int getCount() {
            return mFragments.length;
        }
        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentNames[position];
        }
    };

    mViewPager.setAdapter(mPagerAdapter);
    TabLayout tabLayout = findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
    Toast.makeText(this,mMeetingKey,Toast.LENGTH_LONG).show();


    // Button launches NewPostActivity
    findViewById(R.id.fab_new_post).setOnClickListener(new android.view.View.OnClickListener() {
        @Override
        public void onClick(android.view.View v) {
            Intent intent = new Intent(View.this, NewPostActivity.class);
            intent.putExtra("mMeetingKey",mMeetingKey);
            startActivity(intent);
        }
    });
}
}