如何在片段内的 SharedPreferences 中获取我的 pref_name 的值?

我一直在尝试从 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)


白衣非少年
浏览 199回答 2
2回答

翻阅古今

如果您无法在 Fragment 中获取该值,则可以从您的 Activity 中获取该值。调用片段:String value = ((YourActivityName)getActivity()).getValuePreference();并在您的活动中添加方法:public String getValuePreference(){    SharedPreferences preferences = getSharedPreferences("SharedPreferences", Context.MODE_PRIVATE);    return preferences.getString("EID", "0");}

心有法竹

试试这个:在片段中添加以下代码  Context context;@Overridepublic 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");
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java