2017-01-02 49 views
0

我已經將一個單擊事件放置在片段內的ImageButton上進行一項活動。但該應用程序崩潰,出現以下錯誤。創建片段視圖時發生崩潰

嘗試上的空對象引用

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("123456789","scheme1","current","120000")); 
     myAccountsCardData.add(new MyAccountsCard("123456789","scheme2","savings","5000")); 
    } 

} 
+0

u能張貼fragment_account_info.xml – Raghavendra

+0

存在於你的XML按鈕? –

+0

[什麼是NullPointerException,以及如何解決它?]可能重複(http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it ) – Raghavendra

回答

3
調用虛擬方法 '無效android.widget.ImageButton.setOnClickListener(android.view.View $ OnClickListener)'

iButtonShare對象爲空。您確定您已將此按鈕添加到您的xml佈局R.layout.fragment_account_info?並且此佈局中的按鈕是否有正確的編號(shareButton)?

+0

實際上,圖像按鈕位於卡中,卡使用recyclerview放置。 –

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)

0

您的ID沒有corrent,這裏是錯誤

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

我認爲你是使用錯誤的ID。還要檢查是否正在使用的ImageView或ImageButton的

現在,當你開始新的活動,試試這個

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