【发布时间】:2019-03-05 03:13:43
【问题描述】:
我在我的动态应用程序中使用片段,其中 User.java 文件包含值,TabbedActivity.java 文件包含三个片段。我想在ProfileFrgament.java 中将文本设置为TextView。因此,我在fragment_profile.xml 中创建了一个TextView,并使用以下代码从TabbedActivity.java 文件中引用它
name = findViewById(R.id.name);
//getting the current user
User user = SharedPrefManager.getInstance(this).getUser();
//setting values to textviews
name.setText(user.getUsername());
它没有显示任何编译错误,但打开TabbedActivity.java后,应用程序在name.setText(user.getUsername());行停止并出现NullPointerException如何解决这个问题?
这是ProfileFragment.java文件的代码
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
name = getActivity().findViewById(R.id.name);
//getting the current user
User user = SharedPrefManager.getInstance(getActivity()).getUser();
//setting values to textviews
name.setText(user.getUsername());
return inflater.inflate(R.layout.fragment_profile, container, false);
}
【问题讨论】:
-
没错,您的 textview 在
fragment_profile.xml中可用,并且您在TabbedActivity.java中找到该 textview 并设置,因此发生了 NullpointerException。 -
@ChiragSavsani 那么,解决方案是什么?
标签: android android-fragments textview