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

onCreateView中的Android片段getActivity().getApplicationContext()为空

田博易
2023-03-14

因此,我一直试图在我的应用程序中实现一个特性,其中所有帖子都将被列出到片段中的recycerview中。但是,每当我访问getActivity().getApplicationContext()时,它将返回null。

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"));
    }
}
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();
    }
}
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;
    }
}
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个答案

皇甫展
2023-03-14

您在oncreateview()上所做的一切(除了实际膨胀视图)都应该移到onviewcreate()。在实际膨胀或返回布局之前,您需要调用container.findviewbyid(r.id.homePostsrCyclerv)--实际上是在空容器中查找回收视图。

相反,您应该在oncreateview()中返回新膨胀的视图,并将作用于视图的逻辑移动到onviewcreated(),在这里您将获得刚刚创建的视图

 类似资料: