我的活动包含带片段的ViewPager
MainActivity.java:
public class MainActivity extends AppCompatActivity {
@BindView(R.id.viewPager) ViewPager viewPager;
private ViewPagerAdapter pagerAdapter;
private void initView() {
pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
viewPager.addOnPageChangeListener(pagerAdapter);
}
}
InfoFragment.Java:
public class InfoFragment extends Fragment implements View.OnClickListener {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_info, container, false);
ButterKnife.bind(this, root);
initView();
return root;
}
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), ContactActivity.class);
intent.putParcelableArrayListExtra(MainActivity.CONTACT_LIST, (ArrayList<? extends Parcelable>) contactList);
startActivityForResult(intent, CONTACT_ACTIVITY);
}
}
在此行完全执行onClick方法时:
Intent intent = new Intent(getActivity(), ContactActivity.class);
发生此异常
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:77)
at android.content.Intent.<init>(Intent.java:4618)
at com.swazer.smares.ui.fragments.InfoFragment$1.onClick(InfoFragment.java:128)
at android.view.View.performClick(View.java:5217)
at android.view.View$PerformClick.run(View.java:20983)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6117)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
任何人都知道为什么会这样?
答案 0 :(得分:0)
请尝试以下代码之一:
1)试试这段代码:
Intent i = new Intent(getApplicationContext(), ContactActivity.class);
2)将其添加到您的java文件中:
<强> MainActivity.java .. 强>
public static Context cxt;
public class MainActivity extends AppCompatActivity {
cxt = this;
@BindView(R.id.viewPager) ViewPager viewPager;
private ViewPagerAdapter pagerAdapter;
private void initView() {
pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
viewPager.addOnPageChangeListener(pagerAdapter);
}
}
<强> InfoFragment.java: 强>
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.cxt, ContactActivity.class);
intent.putParcelableArrayListExtra(MainActivity.CONTACT_LIST, (ArrayList<? extends Parcelable>) contactList);
startActivityForResult(intent, CONTACT_ACTIVITY);
}