我一直在尝试从 SharedPreferences 作为字符串获取一个键的值,以便我可以修改连接到片段的布局中的数据。
这是我的 OneFragment.java 代码
public class OneFragment extends Fragment{
private TextView mText;
public OneFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_one, container, false);
SharedPreferences prefs = getActivity().getSharedPreferences("EID", Context.MODE_PRIVATE);
String value = prefs.getString("EID", "0");
mText = (TextView) view.findViewById(R.id.textView2);
mText.setText(value);
return view;
}
}
该应用程序说它在打开时已停止。我正在调用来自主要活动的片段。
工作室怎么说:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dell.tab2, PID: 3857
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.dell.tab2/com.example.dell.tab2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
翻阅古今
心有法竹
相关分类