我正在为我的应用程序使用一个片段。我还在我的片段中添加了一个bundle但是当我想从bundle中获取添加的String时,编译器会向我显示一个空指针错误,如下所示
Process: com.softmaker.gazi_opu.personalhealthcare, PID: 3253
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.softmaker.gazi_opu.personalhealthcare.fragment.GeneralInformationFragment.setValue(GeneralInformationFragment.java:67)
at com.softmaker.gazi_opu.personalhealthcare.fragment.GeneralInformationFragment.onCreateView(GeneralInformationFragment.java:59)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
我添加的代码和获取添加的数据代码如下所示
public static GeneralInformationFragment getInstance(String profileID){
Bundle bundle = new Bundle();
bundle.putString("profileId",profileID);
GeneralInformationFragment generalFragment = new GeneralInformationFragment();
generalFragment.setArguments(bundle);
return generalFragment;
}
现在从onCreateMethod
中获取此片段的数据String id = getArguments().getString("profileId");
Log.e("ID :", "" + id.toString());
任何人都可以建议我。我在哪里弄错了?
答案 0 :(得分:4)
我总是传递这样的数据并且工作得很好:
public class CategoryResultFragment extends BaseListFragment {
private static final String CATEGORY_ID = "EXTRA_CATEGORY_ID";
private static final String CATEGORY_SLUG = "EXTRA_CATEGORY_SLUG";
private String mCategoryId;
private String mCategorySlug;
public static CategoryResultFragment newInstance(String categoryId, String categorySlug) {
Bundle bundle = new Bundle();
bundle.putString(CATEGORY_ID, categoryId);
bundle.putString(CATEGORY_SLUG, categorySlug);
CategoryResultFragment categoryResultFragment = new CategoryResultFragment();
categoryResultFragment.setArguments(bundle);
return categoryResultFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (getArguments() != null) {
mCategoryId = getArguments().getString(CATEGORY_ID);
mCategorySlug = getArguments().getString(CATEGORY_SLUG);
}
return super.onCreateView(inflater, container, savedInstanceState);
}
}
答案 1 :(得分:0)
在转换为String
之前始终检查nullcenter