onCreateView中的Android片段getActivity()。getApplicationContext()为null

时间:2019-03-03 04:53:38

标签: java android android-fragments

因此,我一直在尝试在我的应用中实现一项功能,该功能会将所有帖子都列在recyclerView中的Fragment内。但是,每当我访问getActivity().getApplicationContext()时,其返回null。

据我了解,getActivity仅在片段已分离时才返回null。我以为我的片段还没有拆下来,因为我是第一次打开它。

getActivity().getApplicationContext()HomeFragment.java内部被调用。

这是我的代码: HomeFragment.java

public class HomeFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    List<Post> posts = new ArrayList<>();
    private RecyclerView postsRecyclerView;
    private HomePostsAdapter pAdapter;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    //private Activity fragmentContext;

    public HomeFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        pAdapter = new HomePostsAdapter(posts);
        RecyclerView.LayoutManager pLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
        postsRecyclerView = (RecyclerView) container.findViewById(R.id.homePostsRcyclerV);
        postsRecyclerView.setLayoutManager(pLayoutManager);
        postsRecyclerView.setItemAnimator(new DefaultItemAnimator());
        postsRecyclerView.setAdapter(pAdapter);

        populatePostsDetails();
        pAdapter.notifyDataSetChanged();

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }

    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private void populatePostsDetails() {
        posts.add(new Post(1, "A Post: The First One", "Once upon a time, there was this useless app", "July"));
        posts.add(new Post(2, "The Story begins today", "It was I the allfather who did it!", "July"));
        posts.add(new Post(3, "Another POST!", "what is the point of this thing h8uh?", "July"));
        posts.add(new Post(4, "Dandandan", "asdasdasdasdasdasdasdasdasdasd", "July"));
        posts.add(new Post(5, "A Post: The First One", "Once upon a time, there was this useless app", "July"));
        posts.add(new Post(6, "The Story begins today", "It was I the allfather who did it!", "July"));
        posts.add(new Post(7, "Another POST!", "what is the point of this thing h8uh?", "July"));
        posts.add(new Post(8, "Dandandan", "asdasdasdasdasdasdasdasdasdasd", "July"));
        posts.add(new Post(9, "A Post: The First One", "Once upon a time, there was this useless app", "July"));
        posts.add(new Post(10, "The Story begins today", "It was I the allfather who did it!", "July"));
        posts.add(new Post(11, "Another POST!", "what is the point of this thing h8uh?", "July"));
        posts.add(new Post(12, "Dandandan", "asdasdasdasdasdasdasdasdasdasd", "July"));
    }
}

HomePostsAdapter.java

public class HomePostsAdapter extends  RecyclerView.Adapter<HomePostsAdapter.CustomViewHolder>{
    private List<Post> posts;

    public class CustomViewHolder extends RecyclerView.ViewHolder {
        public TextView pTitle, pContent;

        public CustomViewHolder(View view) {
            super(view);
            pTitle = (TextView) view.findViewById(R.id.postTitle);
            pContent = (TextView) view.findViewById(R.id.postContent);
        }
    }

    public HomePostsAdapter(List<Post> posts){
        this.posts = posts;
    }

    @Override
    public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.posts_list, parent, false);

        return new CustomViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(CustomViewHolder holder, int position) {
        Post post = posts.get(position);
        holder.pTitle.setText(post.getPostTitle());
        holder.pContent.setText(post.getPostContent());
    }

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

Post.java

public class Post {
    int id;
    String title;
    String content;
    String date_created;

    // sets values for the posts
    public Post(int p_id, String p_title, String p_content, String p_date_created) {
        this.id = p_id;
        this.title = p_title;
        this.content = p_content;
        this.date_created = p_date_created;
    }

    public int getPostId() {
        return this.id;
    }

    public String getPostTitle() {
        return this.title;
    }

    public String getPostContent() {
        return this.content;
    }

    public String getPostDateCreated() {
        return this.date_created;
    }
}

任何帮助将不胜感激!

Logcat:

03-02 23:18:03.974 3377-3377/com.example.darkestmidnight.lykeyfoods E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.darkestmidnight.lykeyfoods, PID: 3377
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
        at com.example.darkestmidnight.lykeyfoods.activities.main_navigation.HomeFragment.onCreateView(HomeFragment.java:85)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
        at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
        at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

1 个答案:

答案 0 :(得分:3)

您在onCreateView()上所做的所有操作(除了实际上使视图变大之外)都应移至onViewCreated()。您实际上是在夸大或返回布局之前调用container.findViewById(R.id.homePostsRcyclerV)-有效地在空容器中查找RecyclerView。

您应该只返回onCreateView()中新近膨胀的视图,然后将作用于该视图的逻辑移至onViewCreated(),并在其中传递刚刚创建的View