我一直在尝试从 SharedPreferences 作为字符串获取一个键的值,以便我可以修改连接到片段的布局中的数据。这是我的 OneFragment.java 代码public class OneFragment extends Fragment{private TextView mText;public OneFragment() { // Required empty public constructor}@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);}@Overridepublic 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)
2 回答
翻阅古今
TA贡献1780条经验 获得超5个赞
如果您无法在 Fragment 中获取该值,则可以从您的 Activity 中获取该值。调用片段:
String value = ((YourActivityName)getActivity()).getValuePreference();
并在您的活动中添加方法:
public String getValuePreference(){
SharedPreferences preferences = getSharedPreferences("SharedPreferences", Context.MODE_PRIVATE);
return preferences.getString("EID", "0");
}
心有法竹
TA贡献1866条经验 获得超5个赞
试试这个:
在片段中添加以下代码
Context context;
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
在onCreateView替换getActivity()用context
SharedPreferences prefs = context.getSharedPreferences("EID", Context.MODE_PRIVATE);
String value = prefs.getString("EID", "0");
添加回答
举报
0/150
提交
取消