创建片段视图时崩溃

时间:2017-01-02 10:19:37

标签: java android nullpointerexception android-view

我在一个片段内部的ImageButton上设置了一个on Click事件来实现一个活动。但该应用程序崩溃时出现以下错误。

  

尝试调用虚方法' void android.widget.ImageButton.setOnClickListener(android.view.View $ OnClickListener)'在空对象引用上

AccountFragment.java

    public class AccountInfoFragment extends Fragment {
    private ArrayList<MyAccountsCard> myAccountsCardData;

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


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view =  inflater.inflate(R.layout.fragment_account_info, container, false);
        RecyclerView myAccountView=(RecyclerView) view.findViewById(R.id.my_accounts_view);


        myAccountView.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL, false));

        initializeData();

        MyAccountsCardAdapter myAccountsCardAdapter= new MyAccountsCardAdapter(myAccountsCardData);
        myAccountView.setAdapter(myAccountsCardAdapter);
        final ImageButton iButtonShare = (ImageButton)view.findViewById(R.id.shareButton);
        iButtonShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getContext().getApplicationContext(),AccountShareActivity.class);
                startActivity(i);
            }
        });

        return view;
    }

    private void initializeData(){
        myAccountsCardData= new ArrayList<>();
        myAccountsCardData.add(new MyAccountsCard("12345678901234","scheme1","current","120000"));
        myAccountsCardData.add(new MyAccountsCard("12345678901234","scheme2","savings","5000"));
    }

}

3 个答案:

答案 0 :(得分:3)

iButtonShare对象为null。您确定已将此按钮添加到xml布局R.layout.fragment_account_info吗?此布局中的按钮是否具有正确的ID(shareButton)?

答案 1 :(得分:0)

  片段中的

getActivity()返回片段的活动   目前与。相关联。

首先添加 getActivity()而不是 getApplicationContext()

       Intent i = new Intent(getActivity(),AccountShareActivity.class);
        startActivity(i);
  

当应用程序尝试使用时抛出NullPointerException   具有空值的对象引用。

final ImageButton iButtonShare = (ImageButton)view.findViewById(R.id.shareButton);

确保您的ImageButton具有正确的ID (R.id.shareButton)

答案 2 :(得分:0)

你的身份不正确,这是错误

final ImageButton iButtonShare = (ImageButton)view.findViewById(R.id.shareButton);

我认为您使用的是错误的ID。还要检查您是否使用imageView或imageButton

现在,当您开始新活动时,请尝试此

Intent i = new Intent(getActivity().getApplicationContext(),AccountShareActivity.class);
        startActivity(i);