Calling activity method from fragment NullPointerException

霸气de小男生 提交于 2019-12-12 05:27:50

问题


I have a problem with accessing activity's method from fragment. Or anything int the activity from the fragment.

Here's fragment code:

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();    
        }
    });

Maybe casting the activity is wrong? Thx in advance


回答1:


I'm guessing that the fragment is not attached to the activity when u call getActivity(). Try to initialize the activity reference in the fragment method onAttach().

So something like this:

@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");
        }
    }


来源:https://stackoverflow.com/questions/13897949/calling-activity-method-from-fragment-nullpointerexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!