本文介绍了从片段NullPointerException异常调用活动的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个从片段访问活动的方法的问题。或任何诠释从该片段的活性。
I have a problem with accessing activity's method from fragment.Or anything int the activity from the 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();
}
});
也许铸造的活动是错了吗?THX提前
Maybe casting the activity is wrong?Thx in advance
推荐答案
我猜的片段没有连接到活动当u调用getActivity()。尝试初始化片段的方法onAttach活动参考()。
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().
因此,像这样:
@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");
}
}
这篇关于从片段NullPointerException异常调用活动的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!