从片段NullPointerException调用活动方法

时间:2012-12-16 02:00:16

标签: android casting android-fragments android-activity

我从片段访问活动的方法时遇到问题。 或者片段中活动的任何内容。

这是片段代码:

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提前

1 个答案:

答案 0 :(得分: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");
        }
    }