2012-12-16 60 views
0

我遇到了從片段訪問活動的方法的問題。 或其他東西int從片段的活動。從片段調用活動方法空指針異常

這裏的片段代碼:

public class MainFragment extends Fragment { 

private MainActivity ma = (MainActivity) getActivity(); 
public SipAudioCall call = null; 
public SipManager mSipManager = null; 
public SipProfile mSipProfile = null; 



public MainFragment() { 
    // TODO Auto-generated constructor stub 

} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    // Create a new TextView and set its text to the fragment's section 
    // number argument value. 
    LinearLayout mLinearLayout = (LinearLayout) inflater.inflate(R.layout.main_layout, container, false); 

    final Button callbtn = (Button) mLinearLayout.findViewById(R.id.callbtn); 
    final Button endbtn = (Button) mLinearLayout.findViewById(R.id.endbtn); 



    callbtn.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      callbtn.setVisibility(View.GONE); 
      endbtn.setVisibility(View.VISIBLE); 
      ma.initiateCall();  
     } 
    }); 

也許鑄造的活動是錯誤的? Thx提前

+0

後的堆棧跟蹤。 – gsingh2011

回答

1

我猜測,當你調用getActivity()時片段沒有附加到活動。嘗試在片段方法onAttach()中初始化活動引用。

因此,像這樣:

@Override 
    public void onAttach(Activity activity) { 
     super.onAttach(activity); 
     try { 
      ma = (MainActivity) activity; 
     } catch (ClassCastException e) { 
      throw new ClassCastException(activity.toString() + " Not MainActivity class instance"); 
     } 
    } 
+0

這使得總的感覺....感謝您的幫助! –